{"id": "dfc898f22f4a3f599e08dbf3a99245f57cf9ffb0f55d2279dbe215c18e4d4345", "license": {"spdx": ["MIT"], "repo": "majo-icutech/hmhome", "path": "addon/hmhome.js", "repo_head_hexsha": "26179e07893142038b439f516c5679591e4e3679", "stack_hexsha": "4160489544a38e52e3777814da0ad53655045a5c", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Weak Server Certificate", "issueDescriptionEn": "The Weak Server Certificate checker finds code that specifies rejectUnauthorized option to false to authenticate a server.\nYou need to validate the X.509 certificate to generate an SSL/TLS session secure against the MITM (Man In The Middle) attacks.\nIf the certificate is not properly validated, you may connect to a malicious host or receive data generated by an untrusted host.\nSpecify rejectUnauthorized option to true to verify the certificate.", "issueLineNumber": 28, "entireCode": "const async = require('async');\nconst express = require('express');\nconst fs = require('fs');\nconst https = require('https')\nconst url = require('url');\n\nconst app = express();\nconst port = 4449;\n\nfunction getDevice(device, channel, datapoint, callback) {\n const path = '/device/' + device + '/' + channel + '/' + datapoint + '/~pv';\n\n const options = {\n hostname: 'localhost',\n port: 2122,\n path: path,\n method: 'GET',\n auth: 'has:5mUQzSXLwASQtRm',\n rejectUnauthorized: false,\n headers: {\n 'Content-Type': 'application/json',\n 'Content-Length': 0\n }\n };\n\n var request_data = '';\n\n const req = https.request(options, res => {\n if (res.statusCode == 200) {\n res.on('data', d => {\n request_data += d;\n });\n\n res.on('end', () => {\n var data = {};\n try {\n data = JSON.parse(request_data);\n }\n catch (e) {\n data.error = 'JSON error: '+ e.toString() + ' ' + request_data;\n }\n callback(null, data);\n });\n }\n else {\n callback(res.statusCode + ': ' + res.statusMessage);\n }\n });\n\n req.on('error', error => {\n callback(error);\n });\n\n req.end();\n}\n\nfunction setDevice(device, channel, datapoint, value, callback) {\n const path = '/device/' + device + '/' + channel + '/' + datapoint + '/~pv';\n const content = JSON.stringify({\n v: value\n });\n\n const options = {\n hostname: 'localhost',\n port: 2122,\n path: path,\n method: 'PUT',\n auth: 'has:5mUQzSXLwASQtRm',\n rejectUnauthorized: false,\n headers: {\n 'Content-Type': 'application/json',\n 'Content-Length': content.length\n }\n };\n\n var request_data = '';\n\n const req = https.request(options, res => {\n if (res.statusCode == 200) {\n res.on('end', () => {\n callback(null);\n });\n }\n else {\n callback(res.statusCode + ': ' + res.statusMessage);\n }\n });\n\n req.on('error', error => {\n callback(error);\n });\n\n req.write(content);\n req.end();\n}\n\nconst config = JSON.parse(fs.readFileSync('hmhome.cfg'));\nconst devices = config.devices;\n\nvar long_on = {\n 1: { active: false, timeout: null },\n 2: { active: false, timeout: null },\n 3: { active: false, timeout: null },\n 4: { active: false, timeout: null },\n 5: { active: false, timeout: null },\n 6: { active: false, timeout: null }\n};\n\napp.get('/cux/set/short', (req, res) => {\n var req_q = url.parse(req.url, true).query;\n\n if (devices[req_q.id]) {\n var device = devices[req_q.id];\n\n async.map(device.addresses, (address, callback) => {\n getDevice(address, 3, 'WORKING', (err, data) => {\n callback(err, data.v);\n });\n }, (err, result) => {\n if (!err) {\n const working = result.reduce((a, b) => a || b);\n console.log('short', device.addresses, device.level, working);\n\n if (working) {\n async.map(device.addresses, (address, callback) => {\n setDevice(address, 3, 'STOP', true, (err) => {\n callback(err);\n });\n }, (err,) => {\n if (err) console.log('short', err);\n });\n }\n else {\n async.map(device.addresses, (address, callback) => {\n setDevice(address, 3, 'LEVEL', device.level, (err) => {\n callback(err);\n });\n }, (err) => {\n if (err) console.log('short', err);\n });\n }\n }\n else {\n console.log('short', err);\n }\n });\n }\n\n res.send('OK');\n});\n\napp.get('/cux/set/long', (req, res) => {\n var req_q = url.parse(req.url, true).query;\n\n if (devices[req_q.id]) {\n var device = devices[req_q.id];\n\n //console.log('long', Date.now(), device.addresses, device.level);\n\n var stopTimeout = () => {\n long_on[req_q.id].timeout = setTimeout(() => {\n long_on[req_q.id].active = false;\n console.log('long', 'end', device.addresses, device.level);\n async.map(device.addresses, (address, callback) => {\n setDevice(address, 3, 'STOP', true, (err) => {\n callback(err);\n });\n }, (err,) => {\n if (err) console.log('short', err);\n });\n }, 300);\n }\n\n if (long_on[req_q.id].active == false) {\n async.map(device.addresses, (address, callback) => {\n setDevice(address, 3, 'LEVEL', device.level, (err) => {\n callback(err);\n });\n }, (err) => {\n if (err) console.log('short', err);\n });\n console.log('long', 'start', device.addresses, device.level);\n\n long_on[req_q.id].active = true;\n stopTimeout();\n }\n else {\n clearTimeout(long_on[req_q.id].timeout);\n stopTimeout();\n }\n }\n\n res.send('OK');\n});\n\napp.listen(port, () => {\n console.log('HMHome app listening at http://localhost:' + port);\n});\n", "dangerousExampleEn": "1. const https = require('https');\n2. \n3. let options = {\n4. hostname: 'www.example.com',\n5. port: 443,\n6. path: '/',\n7. method: 'GET',\n8. secureProtocol: 'TLSv1_2_method',\n9. rejectUnauthorized: false\n10. };\n11. \n12. let req = https.request(options, (res) => {\n13. res.on('data', (d) => {\n14. process.stdout.write(d);\n15. });\n16. });\nLine 9: rejectUnauthorized option is set to false.\nLine 12: The rejectUnauthorized option is set to false, and used as an argument of https.request function.", "safeExampleEn": "1. const https = require('https');\n2. \n3. let options = {\n4. hostname: 'www.example.com',\n5. port: 443,\n6. path: '/',\n7. method: 'GET',\n8. secureProtocol: 'TLSv1_2_method'\n9. };\n10. \n11. let req = https.request(options, (res) => {\n12. res.on('data', (d) => {\n13. process.stdout.write(d);\n14. });\n15. });\nLine 11: Remove the rejectUnauthorized option or specify it to true.", "contexts": [{"lineNo": 28, "eventType": "sink", "messageKey": "jschk.WEAK_SERVER_CERTIFICATES.JS.defect", "params": {"arg0": "request", "arg1": "0"}}]}} {"id": "9c2cc4d93cbf5c7d6433fd231716c15513656a326fc8dac9051a285db088791c", "license": {"spdx": ["MIT"], "repo": "1714080902120/bilibili-backend", "path": "apps/server/src/yutu/user/zhenzisms.js", "repo_head_hexsha": "4a0d04fe914919bc6b5589d886582d30e9012a31", "stack_hexsha": "acebb75d15bd083d8ca3177d8fb8bd9984a1cb00", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Weak Server Certificate", "issueDescriptionEn": "The Weak Server Certificate checker finds code that specifies rejectUnauthorized option to false to authenticate a server.\nYou need to validate the X.509 certificate to generate an SSL/TLS session secure against the MITM (Man In The Middle) attacks.\nIf the certificate is not properly validated, you may connect to a malicious host or receive data generated by an untrusted host.\nSpecify rejectUnauthorized option to true to verify the certificate.", "issueLineNumber": 26, "entireCode": "const https = require('https');\nvar querystring = require('querystring');\n\nclass ZhenzismsClient{\n constructor(apiUrl, appId, appSecret){\n this.apiUrl=apiUrl;\n this.appId=appId;\n this.appSecret=appSecret;\n }\n\t//发送短信\n\tsend(data){\n\t\tconst options = {\n\t\t hostname: this.apiUrl,\n\t\t method: 'POST',\n\t\t path: '/sms/v2/send.do',\n\t\t rejectUnauthorized: false,\n\t\t headers: {\n\t\t 'Content-Type': 'application/x-www-form-urlencoded'\n\t\t }\n\t\t};\n\t\tdata.appId = this.appId;\n\t\tdata.appSecret = this.appSecret;\n\t\tif(data.templateParams)\n\t\t data.templateParams = JSON.stringify(data.templateParams);\n\t\treturn new Promise(function (resolve, reject) {\n\t\t const req = https.request(options, (res) => {\n\t\t\t res.setEncoding('utf8'); \n\t\t\t res.on('data', (d) => {\n\t\t\t \tvar result = JSON.parse(d);\n\t\t\t resolve(result);\n\t\t\t }); \n\t\t\t \n\t\t\t});\n\t\t\tvar content = querystring.stringify(data);\n\t\t\treq.write(content);\n\t\t\treq.end();\n\t\t});\n\t}\n\t//查看余额\n\tbalance(){\n\t\tconst options = {\n\t\t hostname: this.apiUrl,\n\t\t method: 'POST',\n\t\t path: '/account/balance.do',\n\t\t rejectUnauthorized: false,\n\t\t headers: {\n\t\t 'Content-Type': 'application/x-www-form-urlencoded'\n\t\t }\n\t\t};\n\t\tvar data = {\n\t\t appId: this.appId,\n\t\t appSecret: this.appSecret\n\t\t};\n\t\treturn new Promise(function (resolve, reject) {\n\t\t const req = https.request(options, (res) => {\n\t\t\t res.setEncoding('utf8'); \n\t\t\t res.on('data', (d) => {\n\t\t\t \tvar result = JSON.parse(d);\n\t\t\t resolve(result);\n\t\t\t }); \n\t\t\t \n\t\t\t});\n\t\t\tvar content = querystring.stringify(data);\n\t\t\treq.write(content);\n\t\t\treq.end();\n\t\t});\n\t}\n\t//查询单条短信\n\tfindSmsByMessageId(messageId){\n\t\tconst options = {\n\t\t hostname: this.apiUrl,\n\t\t method: 'POST',\n\t\t path: '/smslog/findSmsByMessageId.do',\n\t\t rejectUnauthorized: false,\n\t\t headers: {\n\t\t 'Content-Type': 'application/x-www-form-urlencoded'\n\t\t }\n\t\t};\n\t\tvar data = {\n\t\t appId: this.appId,\n\t\t appSecret: this.appSecret,\n\t\t messageId: messageId\n\t\t};\n\t\treturn new Promise(function (resolve, reject) {\n\t\t const req = https.request(options, (res) => {\n\t\t\t res.setEncoding('utf8'); \n\t\t\t res.on('data', (d) => {\n\t\t\t \tvar result = JSON.parse(d);\n\t\t\t resolve(result);\n\t\t\t }); \n\t\t\t \n\t\t\t});\n\t\t\tvar content = querystring.stringify(data);\n\t\t\treq.write(content);\n\t\t\treq.end();\n\t\t});\n\t}\n}\n\n\nmodule.exports = ZhenzismsClient;", "dangerousExampleEn": "1. const https = require('https');\n2. \n3. let options = {\n4. hostname: 'www.example.com',\n5. port: 443,\n6. path: '/',\n7. method: 'GET',\n8. secureProtocol: 'TLSv1_2_method',\n9. rejectUnauthorized: false\n10. };\n11. \n12. let req = https.request(options, (res) => {\n13. res.on('data', (d) => {\n14. process.stdout.write(d);\n15. });\n16. });\nLine 9: rejectUnauthorized option is set to false.\nLine 12: The rejectUnauthorized option is set to false, and used as an argument of https.request function.", "safeExampleEn": "1. const https = require('https');\n2. \n3. let options = {\n4. hostname: 'www.example.com',\n5. port: 443,\n6. path: '/',\n7. method: 'GET',\n8. secureProtocol: 'TLSv1_2_method'\n9. };\n10. \n11. let req = https.request(options, (res) => {\n12. res.on('data', (d) => {\n13. process.stdout.write(d);\n14. });\n15. });\nLine 11: Remove the rejectUnauthorized option or specify it to true.", "contexts": [{"lineNo": 26, "eventType": "sink", "messageKey": "jschk.WEAK_SERVER_CERTIFICATES.JS.defect", "params": {"arg0": "request", "arg1": "0"}}]}} {"id": "f6554600002e88349752ec0dce517e1ed0cea9359ef69a115b0463ac62be98d6", "license": {"spdx": ["MIT"], "repo": "kallisp/GCMS", "path": "app.js", "repo_head_hexsha": "b3f2b8e685bd826defde580762e35d16f2f44c67", "stack_hexsha": "64624614c6b3dcfba75f7fcb7f4cb8f7d8a999e7", "match": "repo_path"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "SQL Injection (PostgreSQL)", "issueDescriptionEn": "When code does not validate data entered on a web program and the program integrates with the database, an attacker can inject SQL statements in an input form or URL field to view or manipulate information from the database. A vulnerable web application creates dynamic queries with user input.\nThis can execute unintended queries and cause data leak.\nIn Node.js, using input values that do not use the Escaping query function of SQL modules, such as MySQL and PostgreSQL, for SQL queries creates dynamic queries without filtering and allows an attacker to inject a manipulated query to change the meaning.\nThis vulnerability allows an attacker to view or manipulate information from the database.\nTo prevent SQL injection, you can invoke PreparedStatement method to fetch data compiled to the database, or filter out special characters. PostgreSQL provides the escaping query, which adds special characters to the queries and eventually prevents the SQL injection as PreparedStatement does. This validates user inputs from urls or login pages and executes queries.", "issueLineNumber": 80, "entireCode": "// first time only - insert \"prestart\": \"npm install\" in package.json\n\nconst express = require('express')\nvar proxy = require('http-proxy-middleware');\nvar bodyParser = require('body-parser');\n\nconst app = express()\nconst { Client } = require('pg')\nconst client = new Client({\n user: 'postgres',\n host: 'localhost',\n database: 'GCMS',\n password: '',\n port: 5432,\n})\n\nclient.connect(function (err) {\n if (err) {\n console.error('connection error', err.stack)\n } else {\n console.log('connected')\n }\n})\n\napp.use('/', express.static('app'))\napp.use('/geoserver', proxy({ target: 'http://localhost:8080', changeOrigin: true }));\napp.use(bodyParser.json()); // for parsing application/json\n\napp.get('/persons', function (request, response) {\n client.query('SELECT * FROM persons', function (err, results) {\n response.json(results);\n })\n});\n\napp.get('/persons_graves', function (request, response) {\n console.log(request.param);\n var query = \"SELECT graves.gid,persons.pid,persons_in_grave.pgid,diadromos,thesi,category,availability,grave_level,entry_date,exit_date,name,surname,father_name,mother_name,birth_date,death_date,age,death_place,geom\\\n FROM graves\\\n LEFT JOIN persons_in_grave ON graves.gid = persons_in_grave.gid\\\n LEFT JOIN persons ON persons.pid = persons_in_grave.pid \\\n WHERE diadromos='\"+ request.param('diadromos') + \"' \" + \"OR thesi='\" + request.param('thesi') + \"'\";\n\n console.log(query);\n\n client.query(query, function (err, results) {\n if (err != undefined) {\n return response.status(500).send(err);\n }\n response.json(results);\n })\n});\n\napp.post('/persons_graves', function (request, response) {\n // console.log(request.body) //εμφανιση του body από το request\n var updatePersonsQuery = \"UPDATE persons SET name='\" + request.body.name +\n \"', surname='\" + request.body.surname +\n \"', father_name='\" + request.body.father_name +\n \"', mother_name='\" + request.body.mother_name + \"'\" +\n // \", birth_date=\" + request.body.birth_date +\n // \", death_date=\" + request.body.death_date +\n \", age=\" + request.body.age +\n \", death_place='\" + request.body.death_place +\n \"' WHERE pid=\" + request.body.pid;\n\n var updateGravesQuery = \"UPDATE graves SET diadromos='\" + request.body.diadromos +\n \"', thesi='\" + request.body.thesi +\n \"', category='\" + request.body.category +\n \"', availability='\" + request.body.availability +\n \"' WHERE gid=\" + request.body.gid;\n\n var updatePersonsInGraveQuery = \"UPDATE persons_in_grave SET grave_level=\" + request.body.grave_level +\n // \", entry_date=\" + request.body.entry_date + \", exit_date=\" + request.body.exit_date +\n \" WHERE pgid= \" + request.body.pgid;\n\n console.log(updatePersonsQuery)\n // console.log(updateGravesQuery)\n console.log(updatePersonsInGraveQuery)\n\n\n client.query(updateGravesQuery, function (err, results) {\n\n if (err != undefined) {\n console.warn(err);\n return response.status(500).send(err);;\n }\n\n client.query(updatePersonsQuery, function (err, results) {\n\n if (err != undefined) {\n console.warn(err);\n return response.status(500).send(err);;\n }\n\n client.query(updatePersonsInGraveQuery, function (err, results) {\n\n if (err != undefined) {\n console.warn(err);\n return response.status(500).send(err);\n }\n return response.status(200).end();\n })\n })\n })\n});\n\napp.get('/grave_history', function (request, response) {\n console.log(request.param);\n var query = \"SELECT graves.gid,persons.pid,persons_in_grave.pgid,diadromos,thesi,category,availability,grave_level,entry_date,exit_date,name,surname,father_name,mother_name,birth_date,death_date,age,death_place,geom\\\n FROM graves\\\n LEFT JOIN persons_in_grave ON graves.gid = persons_in_grave.gid\\\n LEFT JOIN persons ON persons.pid = persons_in_grave.pid \\\n WHERE exit_date IS NOT NULL AND graves.gid = \" + request.param('gid') + \" ORDER BY entry_date ASC\";\n\n console.log(query);\n\n client.query(query, function (err, results) {\n if (err != undefined) {\n return response.status(500).send(err);\n }\n response.json(results);\n })\n});\n\n// app.post('/insert_person', function (request, response) {\n// var insertPersonsQuery = \"INSERT INTO persons (surname,name,father_name,mother_name,birth_date,death_date,age,death_place) VALUES '\" + request.body.surname +\n// \"', '\" + request.body.name + \"', '\" + request.body.father_name + \"', '\" + request.body.mother_name + \"', \" + request.body.birth_date + \", \" + request.body.death_date + \n// \", \" + request.body.age + \", '\" + request.body.death_place + \"'\";\n\n// var updateGravesQuery = \"UPDATE graves SET diadromos='\" + request.body.diadromos +\n// \"', thesi='\" + request.body.thesi +\n// \"', category='\" + request.body.category +\n// \"', availability='\" + request.body.availability +\n// \"' WHERE gid=\" + request.body.gid;\n\n// var insertPersonsInGraveQuery = \"INSERT INTO persons_in_grave (grave_level,entry_date,exit_date) VALUES \" + request.body.grave_level + \", entry_date=\" + request.body.entry_date + \", exit_date=\" + request.body.exit_date +\n// \" WHERE pgid= \" + request.body.pgid;\n\n// console.log(insertPersonsQuery)\n// // console.log(updateGravesQuery)\n// console.log(insertPersonsInGraveQuery)\n\n\n// client.query(insertPersonsQuery, function (err, results) {\n\n// if (err != undefined) {\n// console.warn(err);\n// return response.status(500).send(err);;\n// }\n\n// client.query(updateGravesQuery, function (err, results) {\n\n// if (err != undefined) {\n// console.warn(err);\n// return response.status(500).send(err);;\n// }\n\n// client.query(insertPersonsInGraveQuery, function (err, results) {\n\n// if (err != undefined) {\n// console.warn(err);\n// return response.status(500).send(err);\n// }\n// return response.status(200).end();\n// })\n// })\n// })\n// });\n\napp.listen(8000, () => console.log('Example app listening on port 8000!'))", "dangerousExampleEn": "1. const id = req.params.id;\n2. const sql = 'SELECT * FROM users WHERE id=' + id;\n3. pgconn.query(sql, function(err, rows) {\n4. ...\n5. });\nLine 3: This is insecure because the unvalidated user input is used in queries.", "safeExampleEn": "1. const id = req.params.id;\n2. const sql = 'SELECT * FROM users WHERE id= $1'\n3. pgconn.query(sql, id, function(err, rows) {\n4. ...\n5. });\nLine 3: Execute the received value as constant with the compiled query statement using $1.", "contexts": [{"lineNo": 65, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 69, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 80, "eventType": "sink", "messageKey": "jschk.SQL_INJECTION_POSTGRESQL.JS.defect.sink", "params": {}}]}} {"id": "1e5023c572d624e196ad8c8b8b8cf01c703ff890630027f25061d884e17318f0", "license": {"spdx": ["Fair"], "repo": "LeadProgramming/Ecommerce-Cuddles", "path": "items.js", "repo_head_hexsha": "0322fa09c4c131c2f6386b4fc56b8675fb75c316", "stack_hexsha": "6d12106b6b3a7e12a01856451906318c8a97575f", "match": "repo_path"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "SQL Injection (mySQL)", "issueDescriptionEn": "When code does not validate data entered on a web program and the program integrates with the database, an attacker can inject SQL statements in an input form or URL field to view or manipulate information from the database. A vulnerable web application creates dynamic queries with user input.\nThis can execute unintended queries and cause data leak.\nIn Node.js, using input values that do not use the Escaping query function of SQL modules, such as MySQL and PostgreSQL, for SQL queries creates dynamic queries without filtering and allows an attacker to inject a manipulated query to change the meaning.\nThis vulnerability allows an attacker to view or manipulate information from the database.\nTo prevent SQL injection, you can invoke PreparedStatement method to fetch data compiled to the database, or filter out special characters. MySQL provides the escaping query with the npm module, which adds special characters to the queries and eventually prevents the SQL injection as PreparedStatement does. This validates user inputs from urls or login pages and executes queries.", "issueLineNumber": 62, "entireCode": "require('dotenv').config()\nconst express = require('express');\nconst router = express.Router();\nconst bodyParser = require('body-parser');\nconst mysql = require('mysql');\nconst fileUpload = require('express-fileupload');\n\nrouter.use(bodyParser.json());\nrouter.use(bodyParser.urlencoded({ extended: true }));\nrouter.use(fileUpload());\n\nlet pool = mysql.createPool({\n connectionLimit: 10,\n host: process.env.MYSQL_HOST,\n user: process.env.MYSQL_USER,\n password: ,\n port: process.env.MYSQL_PORT,\n database: process.env.MYSQL_DB\n})\n\nrouter.get(\"/api/items\", (req, res) => {\n pool.query(`SELECT * FROM item`, (err, result) => {\n if (err) {\n res.status(400).send(\"Cannot update address information.\");\n throw err;\n }\n else {\n res.status(200).send(result);\n }\n });\n})\n\nrouter.post(\"/api/items\", (req, res) => {\n let query = \"INSERT INTO item SET ?\", values = {\n ItemID: req.body.id,\n ItemName: req.body.name,\n ItemQuantity: req.body.quantity,\n ItemPrice: req.body.price,\n ItemDescription: req.body.description,\n ItemImage: req.files.image.data\n };\n pool.query(query, values, (err, result) => {\n console.log(err);\n if (err) {\n res.status(400).send(`Cannot create ${values.ItemName}.`);\n throw err(`Cannot create ${values.ItemName}`);\n }\n else {\n res.status(200).send(`Successfully created ${values.ItemName}.`);\n }\n });\n});\nrouter.put(\"/api/items\", (req, res) => {\n let query = `UPDATE item SET ? WHERE ItemID = ${req.body.id};`, values = {\n ItemID: req.body.id,\n ItemName: req.body.name,\n ItemQuantity: req.body.quantity,\n ItemPrice: req.body.price,\n ItemDescription: req.body.description,\n ItemImage: req.files.image.data\n }\n pool.query(query, values, (err) => {\n if (err) {\n res.status(400).send(`Cannot update ${values.ItemName}.`);\n throw err(\"Cannot Update Item\")\n }\n else {\n res.status(200).send(values.ItemName + \" has been updated.\");\n }\n })\n})\nrouter.delete(\"/api/items\", (req, res) => {\n const { ItemID } = req.body;\n pool.query(`DELETE FROM item WHERE item.ItemID = ${ItemID}`, (err, result) => {\n if (err) {\n res.status(400).send(\"Cannot delete Item\");\n }\n else {\n res.status(200).send(result);\n }\n })\n})\n\n\n\nmodule.exports = router;", "dangerousExampleEn": "1. router.post('/login', function (req, res) {\n2. const id = req.body.input1;\n3. const pwd = req.body.input2;\n4. \n5. \tconst query = 'SELECT * FROM users WHERE id=' + id;\n6. \n7. db.connection.query(query,(err,result,field)=>{\n8. ...\n9. });\n10. });\nLine 7: This is insecure because a value received directly from an external source is used in the query.", "safeExampleEn": "1. router.post('/login', function (req, res) {\n2. const id = req.body.input1;\n3. const pwd = req.body.input2;\n4. \n5. \tconst query = 'SELECT * from info where Id = ? and pwd = ?';\n6. \n7. db.connection.query(query, [id, pwd], (err, result, field) => {\n8. \t...\n9. });\n10. });\nLine 7: This is secure because the external input is bound.", "contexts": [{"lineNo": 54, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 55, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "req"}}, {"lineNo": 62, "eventType": "sink", "messageKey": "jschk.SQL_INJECTION_MYSQL.JS.defect.sink", "params": {}}]}} {"id": "6f7de7d5569627960d550d8d925aedc1af4cdf1bebbf1d005740fabf30c2a715", "license": {"spdx": ["MIT"], "repo": "pholawat-tle/crypto-line-bot", "path": "server/src/index.js", "repo_head_hexsha": "95d04e1b17da50bb432dacea38d403b526205321", "stack_hexsha": "b16d3a740385a973743bbbfffc02371989f2c392", "match": "repo_path"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "SQL Injection (mySQL)", "issueDescriptionEn": "When code does not validate data entered on a web program and the program integrates with the database, an attacker can inject SQL statements in an input form or URL field to view or manipulate information from the database. A vulnerable web application creates dynamic queries with user input.\nThis can execute unintended queries and cause data leak.\nIn Node.js, using input values that do not use the Escaping query function of SQL modules, such as MySQL and PostgreSQL, for SQL queries creates dynamic queries without filtering and allows an attacker to inject a manipulated query to change the meaning.\nThis vulnerability allows an attacker to view or manipulate information from the database.\nTo prevent SQL injection, you can invoke PreparedStatement method to fetch data compiled to the database, or filter out special characters. MySQL provides the escaping query with the npm module, which adds special characters to the queries and eventually prevents the SQL injection as PreparedStatement does. This validates user inputs from urls or login pages and executes queries.", "issueLineNumber": 45, "entireCode": "const express = require('express');\nconst app = express();\nconst PORT = process.env.PORT;\nconst Cryptocurrency = require('./class/Cryptocurrency');\nconst {\n parseCommand,\n replyWithText,\n replyWithImage,\n} = require('./functions/lineHelper');\nrequire('dotenv').config({ path: 'src/.env' });\n\napp.use(express.json());\napp.use(require('cors')());\napp.use(require('morgan')('dev'));\n\napp.use('/static', express.static(__dirname + '/public/'));\n\nconst ChannelAccessToken = process.env.ChannelAccessToken;\n\nconst mysql = require('mysql');\nconst cron = require('node-cron');\n\nvar con = mysql.createConnection({\n host: 'db',\n user: 'root',\n password: ,\n database: 'Line',\n});\n\ncon.connect(function (err) {\n if (err) throw err;\n console.log('Connected!');\n});\n\ncron.schedule('*/10 * * * *', () => {\n con.query(\n 'UPDATE Person SET money = money*1.07 + 1000',\n function (err, result) {\n console.log(err || result);\n }\n );\n});\n\napp.post('/webhook', async (req, res) => {\n await con.query(\n `SELECT * FROM Person WHERE userID='${req.body.events[0].source.userId}'`,\n function (err, result) {\n if (!err) {\n if (result.length == 0) {\n con.query(\n `INSERT INTO Person value ('${req.body.events[0].source.userId}',10000)`\n );\n }\n } else {\n console.log(err);\n }\n }\n );\n const { command, args } = parseCommand(req.body);\n if (command) {\n if (command.toLowerCase() === 'price') {\n const crypto = new Cryptocurrency(args[0].toUpperCase());\n replyWithText(\n ChannelAccessToken,\n req.body.events[0].replyToken,\n await crypto.getPrice()\n );\n } else if (command.toLowerCase() === 'graph') {\n const crypto = new Cryptocurrency(args[0].toUpperCase());\n const imgURL = await crypto.generateGraph();\n replyWithImage(\n ChannelAccessToken,\n req.body.events[0].replyToken,\n imgURL\n );\n } else if (command.toLowerCase() === 'coin') {\n con.query(\n `SELECT money FROM Person WHERE userID='${req.body.events[0].source.userId}'`,\n function (err, result) {\n if (!err) {\n replyWithText(\n ChannelAccessToken,\n req.body.events[0].replyToken,\n result[0].money\n );\n }\n }\n );\n }\n }\n res.sendStatus(200);\n});\n\napp.get('/', (req, res) => {\n res.send({ msg: 'Hello World!' });\n});\n\napp.listen(PORT, () => {\n console.log(`Running at ${PORT}`);\n});", "dangerousExampleEn": "1. router.post('/login', function (req, res) {\n2. const id = req.body.input1;\n3. const pwd = req.body.input2;\n4. \n5. \tconst query = 'SELECT * FROM users WHERE id=' + id;\n6. \n7. db.connection.query(query,(err,result,field)=>{\n8. ...\n9. });\n10. });\nLine 7: This is insecure because a value received directly from an external source is used in the query.", "safeExampleEn": "1. router.post('/login', function (req, res) {\n2. const id = req.body.input1;\n3. const pwd = req.body.input2;\n4. \n5. \tconst query = 'SELECT * from info where Id = ? and pwd = ?';\n6. \n7. db.connection.query(query, [id, pwd], (err, result, field) => {\n8. \t...\n9. });\n10. });\nLine 7: This is secure because the external input is bound.", "contexts": [{"lineNo": 45, "eventType": "sink", "messageKey": "jschk.SQL_INJECTION_MYSQL.JS.defect.sink", "params": {}}, {"lineNo": 46, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "req__sparrow_node_js_url_request__.body__sparrow_node_js_url_request__.body.events"}}]}} {"id": "14bb5e8baa2a8634856aac49e22bddf810d38c494447d955713cf2d4a6f0500a", "license": {"spdx": ["MIT"], "repo": "attrix182/expressApiRestDB", "path": "user.js", "repo_head_hexsha": "02f3844aa437bb36b987b794976d66e517b82097", "stack_hexsha": "9b1cf2f7829b80538cc0a175857f4cf06a0513d5", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "SQL Injection (mySQL)", "issueDescriptionEn": "When code does not validate data entered on a web program and the program integrates with the database, an attacker can inject SQL statements in an input form or URL field to view or manipulate information from the database. A vulnerable web application creates dynamic queries with user input.\nThis can execute unintended queries and cause data leak.\nIn Node.js, using input values that do not use the Escaping query function of SQL modules, such as MySQL and PostgreSQL, for SQL queries creates dynamic queries without filtering and allows an attacker to inject a manipulated query to change the meaning.\nThis vulnerability allows an attacker to view or manipulate information from the database.\nTo prevent SQL injection, you can invoke PreparedStatement method to fetch data compiled to the database, or filter out special characters. MySQL provides the escaping query with the npm module, which adds special characters to the queries and eventually prevents the SQL injection as PreparedStatement does. This validates user inputs from urls or login pages and executes queries.", "issueLineNumber": 34, "entireCode": "const user = {};\n\nvar mysql = require('mysql');\n\nconst connection = mysql.createConnection({\n host: 'localhost',\n user: 'root',\n password: '',\n database: 'expressdb' //Name DB\n});\n\nuser.list = (req, res) => {\n\n const sql = 'SELECT * FROM usuarios'\n\n connection.query(sql, (error, results) => {\n if (error) throw error;\n if (results.length > 0) {\n res.json(results);\n } else {\n res.send('no results')\n }\n\n })\n\n};\n\nuser.listID = (req, res) => {\n\n\n const { id } = req.params;\n const sql = `SELECT * FROM usuarios WHERE ID = ${id}`\n\n connection.query(sql, (error, results) => {\n if (error) throw error;\n if (results.length > 0) {\n res.json(results);\n } else {\n res.send('no results')\n }\n\n })\n\n};\n\nuser.add = (req, res) => {\n\n const sql = 'INSERT INTO usuarios SET ?'\n\n const newUser = {\n\n correo: req.body.correo,\n clave: req.body.clave,\n nombre: req.body.nombre,\n apellido: req.body.apellido,\n\n }\n\n\n connection.query(sql, newUser, error => {\n if (error) throw error;\n\n if (results.length > 0) {\n\n newUsr = capitalize(results[0].nombre);\n \n res.send(\"Welcome: \" + newUsr);\n \n } else {\n\n res.send('Can not add user to database');\n }\n });\n\n\n};\n\nuser.deleteID = (req, res) => {\n\n\n const { id } = req.params;\n const sql = `DELETE FROM usuarios WHERE ID = ${id}`\n\n connection.query(sql, (error, results) => {\n if (error) throw error;\n\n res.send('Usuario eliminado')\n\n\n })\n\n};\n\nuser.modID = (req, res) => {\n\n\n const { id } = req.params;\n const { nombre, correo, apellido, clave } = req.body;\n const sql = `UPDATE usuarios SET correo = '${correo}', clave = '${clave}', nombre = '${nombre}', apellido = '${apellido}' WHERE id = '${id}'`\n\n connection.query(sql, (error, results) => {\n if (error) throw error;\n\n res.send('Usuario modificado')\n\n\n })\n\n};\n\n\nuser.login = (req, res) => {\n\n const { correo, clave } = req.body;\n const sql = `SELECT * FROM usuarios WHERE correo='${correo}' and clave='${clave}'`\n let user;\n\n connection.query(sql, (error, results) => {\n if (error) throw error;\n\n if (results.length > 0) {\n\n user = capitalize(results[0].nombre);\n\n res.send(\"Welcome: \" + user);\n\n } else {\n res.send('User invalid');\n }\n\n \n\n\n })\n\n};\n\n\nfunction capitalize(word) {\n return word[0].toUpperCase() + word.slice(1);\n }\n\n\n\n\n\nmodule.exports = user;", "dangerousExampleEn": "1. router.post('/login', function (req, res) {\n2. const id = req.body.input1;\n3. const pwd = req.body.input2;\n4. \n5. \tconst query = 'SELECT * FROM users WHERE id=' + id;\n6. \n7. db.connection.query(query,(err,result,field)=>{\n8. ...\n9. });\n10. });\nLine 7: This is insecure because a value received directly from an external source is used in the query.", "safeExampleEn": "1. router.post('/login', function (req, res) {\n2. const id = req.body.input1;\n3. const pwd = req.body.input2;\n4. \n5. \tconst query = 'SELECT * from info where Id = ? and pwd = ?';\n6. \n7. db.connection.query(query, [id, pwd], (err, result, field) => {\n8. \t...\n9. });\n10. });\nLine 7: This is secure because the external input is bound.", "contexts": [{"lineNo": 31, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "req"}}, {"lineNo": 31, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 32, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 34, "eventType": "sink", "messageKey": "jschk.SQL_INJECTION_MYSQL.JS.defect.sink", "params": {}}]}} {"id": "3e5cb8f5e50fabc985320723264c916ca8634063fab99a2fd7a210483a86bf6c", "license": {"spdx": ["MIT"], "repo": "hfucek/noclayer", "path": "public/assets/modules/monitoring/js/message.js", "repo_head_hexsha": "f31ae5bfd8094451d7aeae1e5afca13ab51133ec", "stack_hexsha": "5d283f6cfa0df596ca3b93a86c7b6a80ef7f9d94", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Code Injection", "issueDescriptionEn": "The security weakness allows an attacker to inject arbitrary code to change the intended behaviour of the software, causing it to behave abnormally.\nFunctions that can cause code injection attacks in Node.js include eval() and Function(). If the arguments of these functions are not carefully validated, the code passed by the attacker can be executed as is.\nAvoid using functions that can dynamically execute code.\nIf necessary, validate against external input values in a whitelist fashion, or filter user input values to include only valid characters.", "issueLineNumber": 55, "entireCode": "var MSG={\n\tinit:function(){\n\t\t\n\tthis.container=$('#messages')\t\n\tthis.id=0;\t\n\t\n\t},\n\t\n\tclose:function(id){\n\t\n\t//console.log('closing',id)\t\n\t\tm=$('#msg'+id).animate({\n\t'margin-top':'-=55'\t\n\t\t\n\t},\n\t200, //delay\n\tfunction(){\n\t\t//finished\n\t\t$(this).remove();\n\t})\t\n\t\t\n\t},\n\t\n\t\n\tcrit:function(e){\n\t\t\n\ttoday=new Date()\n\t\t\n\t\tthis.log(1,{'host':'NAGIOS','service':e[0],'status':e[1],'time':today.format(\"dd-m-yyyy HH:MM:ss\")})\n\t\t\n\t\t\n\t\tm=$('
').attr('id','msg'+this.id).css({'z-index':200,'margin-left':480+'px','background':'red','width':480+'px'}).addClass('msg').appendTo(this.container)\t\n\t\t$(m).html(\n\t\t\t'
SOURCE : Nagios error! code:'+e[1]+'
'+\n\t\t\t'
'+e[0]+'
'\n\t\t\t\n\t\t\t\t\n\t\t)\n\t\t\n\t\t$('#msg'+this.id).animate({\n\t'margin-left':'-=700'\t\n\t\t\n\t},\n\t200, //delay\n\tfunction(){\n\t\t//finished\n\t\t\n\t}).click(function(){\n\t\t\n\t\tWIN.show('#win_monitor_settings')\n\t\t$(this).remove()\n\t\t\n\t})\n\t\t\n\tsetTimeout('MSG.close('+this.id+')',20000)\n\t\n\t\tthis.id++;\n\t\t\t\n\t},\n\t\n\tlog:function(type,data){\n\t\t\n\t\tcol=(this.id%2!=0)?'even':'odd'; \n\t\t\n\t\tswitch(type){\n\t\tcase 1:\n\t\t\tli=$('
  • ').addClass('log').addClass(col).html(\n\t\t\t\t\t'
    '+data.host+'
    '+\n\t\t\t\t\t'
    '+data.service+'
    '+\n\t\t\t\t\t'
    '+data.status+'
    '+\n\t\t\t\t\t'
    '+data.time+'
    '\t\t\n\t\t\t\t\t);\n\t\t\t\n\t\t\t\n\t\t\t\n\t\tbreak;\n\t\tcase 2:\n\t\t\t\n\t\t\tli=$('
  • ').addClass('log').addClass(col).html(\n\t\t\t'
    '+data.text+'
    '+\n\t\t\t'
    '+data.time+'
    '\n\t\t\t)\n\t\t\t\n\t\t\tbreak;\n\t\t\n\t\t}\n\t\t\n\t\t$('#monitor_log').prepend(li);\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\n\t\t\n\t},\n\t\n\tadd:function(host,stat,service)\n\t{\n\t\t\n\t\t\n\t\tsetname={'OK':0,'UNKNOWN':'u','WARNING':'w','CRITICAL':'c'}\n\t\t\n\t\ttoday = new Date();\n\t\t\n\t\t\n\t\tthis.log(1,{'host':host,'service':service,'status':stat,'time':today.format(\"dd-m-yyyy HH:MM:ss\")})\n\t\t\n\t\t\n\t\t\n\t\tif(NAGIOS.sound[stat] && NOC.settings[MONITOR.getSettings()].value['sound'+setname[stat]]==1)\n\t\tNAGIOS.sound[stat].play()\n\t\t\n\t\t\n\t\tif(NOC.settings[MONITOR.getSettings()].value['icon'+setname[stat]]==1)\n\t\t$('#header div.not'+stat).parent().css('display','block');\n\t\n\t\tif(NOC.settings[MONITOR.getSettings()].value['osd'+setname[stat]]==1){\t\n\t\t\n\t\ttype=Math.floor(Math.random() * 4);\n\t\t\n\tm=$('
    ').attr('id','msg'+this.id).css('margin-left',220+'px').addClass('msg msg'+stat).appendTo(this.container)\t\n\t$(m).html(\n\t\t'
    '+host+'
    '+\n\t\t'
    '+service+'
    '\n\t\t\n\t\t\t\n\t)\n\t\n\t$('#msg'+this.id).animate({\n\t'margin-left':'-=220'\t\n\t\t\n\t},\n\t200, //delay\n\tfunction(){\n\t\t//finished\n\t\t\n\t})\t\n\t\t\n\t\n\tsetTimeout('MSG.close('+this.id+')',5000)\n\t\n\tthis.id++;\n\t\t}\n\t}\n\t\t\n\t\t\n}", "dangerousExampleEn": "1. const data = req.query\n2. \n3. const evaldata = eval(data);\n4. const funcdata = new Function(data);\nLine 3, 4: This dynamically creates an unverified value which may cause risk of executing unintended code.", "safeExampleEn": "1. const data = req.query\n2. \n3. //const evaldata = eval(data);\n4. var reg = /[&<>'\"()\\/]/gim;\n5. var cleandata = data.replace(reg, \"\");\n6. const funcdata = new Function(cleandata);\nLine 3: Do not use the function that dynamically execute code.\nLine 5: It is safe to use replace() to remove special characters from externally input values.", "contexts": [{"lineNo": 55, "eventType": "sink", "messageKey": "jschk.CODE_INJECTION.JS.defect.sink", "params": {"arg0": "setTimeout"}}]}} {"id": "272f147f5b92b742a3eb485bb4345a0cf470385111e0b4bed548441750b8edb6", "license": {"spdx": ["MIT"], "repo": "marquettecomputationalsocialscience/clusteredcrimemaps", "path": "individual_work/justin/static/euclidean.js", "repo_head_hexsha": "4fb4ad1ad2474f854dabc1a72fbefcbb700d601a", "stack_hexsha": "533eebcdfa7a29fbb9b75f6dc9c3c10385cdea8e", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Code Injection", "issueDescriptionEn": "The security weakness allows an attacker to inject arbitrary code to change the intended behaviour of the software, causing it to behave abnormally.\nFunctions that can cause code injection attacks in Node.js include eval() and Function(). If the arguments of these functions are not carefully validated, the code passed by the attacker can be executed as is.\nAvoid using functions that can dynamically execute code.\nIf necessary, validate against external input values in a whitelist fashion, or filter user input values to include only valid characters.", "issueLineNumber": 17, "entireCode": "function analyzeEuclidean() {\n\t\tvar demographic_div = document.getElementById('demographic_analysis');\n\t\tvar euclidean_div = document.getElementById('euclidean_analysis');\n \tvar bias_div = document.getElementById('bias_analysis');\n \tdemographic_div.style.display = 'none';\n\t\teuclidean_div.style.display = \"block\";\n \tbias_div.style.display = 'none';\n\n\t\tvar x = document.getElementById(\"myText\").value;\n\t\tvar num_clusters = parseInt(x);\n\n\t\tvar cluster_selected = 0;\n\n\t\tvar y = document.getElementById(\"monthID\").value;\n\t\tvar monthID = parseInt(y);\n\n\t\tvar geodesic_crime_data = eval(\"crimes_geodesic_\" + monthID + \"_\" + num_clusters);\n\t\tvar euclidean_crime_data = eval(\"crimes_euclidean_\" + monthID + \"_\" + num_clusters);\n\n\t\t//var cluster_data =\n\n\t var cluster_data = new Array(num_clusters);\n\t\tvar euclidean_data = new Array(num_clusters).fill(0);\n\n\t\t//initialize cluster data\n\t\tfor(var m=0; m < cluster_data.length; m++){\n\t\t cluster_data[m] = {'num_clusters': 0,\n\t\t\t\t\t\t\t 'clusters': new Array(num_clusters),\n\t\t\t\t\t\t\t 'num_points': 0\n\t\t\t\t\t\t\t }\n\t\t\tfor(var p = 0; p < num_clusters; p++){\n\t\t cluster = m.toString();\n\t\t cluster_data[m]['clusters'][p] = {'cluster': p,\n\t\t\t\t\t\t\t\t\t\t\t\t 'count': 0}\n\t\t\t}\n\t\t}\n\n\t\t//boolean for first run through euclid data\n\t\tvar euclid_bool = true;\n\t\tfor (var i=0; i <= geodesic_crime_data['features'].length - 1; i++){\n\t\t\tfor (var j=0; j <= euclidean_crime_data['features'].length - 1; j++) {\n\t\t\t var geo_crime = geodesic_crime_data['features'][i]['geometry']['coordinates'];\n\t\t\t var euclid_crime = euclidean_crime_data['features'][j]['geometry']['coordinates'];\n\n\t\t\t //if the geodesic coordinates match the euclidean coordinates\n\t\t\t if (geo_crime[0] == euclid_crime[0] && geo_crime[1] == euclid_crime[1]) {\n\t\t\t //clusters of respective points\n\t\t\t var euclid_cluster = euclidean_crime_data['features'][j]['properties']['cluster'];\n\t\t\t var geo_cluster = geodesic_crime_data['features'][i]['properties']['cluster'];\n\n\t\t\t if(cluster_data[geo_cluster]['clusters'][euclid_cluster]['count'] == 0)\n\t\t\t cluster_data[geo_cluster]['num_clusters'] += 1;\n\n\t\t\t\t\tcluster_data[geo_cluster]['clusters'][euclid_cluster]['count'] += 1;\n\t\t\t\t\tcluster_data[geo_cluster]['num_points'] += 1;\n\n\t\t\t \tif(euclid_bool = true)\n\t\t\t \teuclidean_data[euclid_cluster] += 1;\n\t\t\t }\n\t\t\t}\n\t\t\teuclid_bool = false;\n\t\t}\n\n\t\tvar data_string = \"\"\n\t\tdocument.getElementById(\"stats\").innerHTML = \"\";\n\n\t\t//build pie chart of euclidean clusters\n\t\tvar pie_data_values = new Array(num_clusters);\n\t\tvar remaining_values = new Array(num_clusters);\n\t\tvar pie_data_names = new Array(num_clusters);\n\t\tvar colors = ['red', 'orange', 'yellow', 'green', 'blue', 'purple', 'black', 'white', 'cyan', 'brown']\n\n\t\tfor (var i=0; i < pie_data_names.length; i++){\n\t\t\tif (cluster_data[cluster_selected]['clusters'][i]['count'] > 0){\n\t\t\t\tpie_data_values[i] = cluster_data[cluster_selected]['clusters'][i]['count'];\n\t\t\t\tremaining_values[i] = euclidean_data[i] - cluster_data[cluster_selected]['clusters'][i]['count'];\n\t\t \tpie_data_names[i] = \"Cluster \" + i.toString() + \" (\" + colors[i] + \")\";\n\t\t\t}\n\n\t\t}\n\n\t\tvar trace1 = {\n \t\t\tx: pie_data_names,\n \t\t\ty: pie_data_values,\n \t\t\tname: 'Matching cluster points',\n \t\t\ttype: 'bar',\n\t\t};\n\n\t\tvar trace2 = {\n \t\t\tx: pie_data_names,\n \t\t\ty: remaining_values,\n \t\t\tname: 'Different cluster points',\n \t\t\ttype: 'bar',\n\t\t};\n\nvar data = [trace1, trace2];\n\nvar layout = {barmode: 'stack'};\n\nPlotly.newPlot('myDiv', data, layout);\n\n\t\tdata_string += \"Percent of euclidean cluster points in this cluster:
    \"\n\t\tvar euclid_cluster_count = 0;\n\t\tvar sim_score = 0;\n\n\t\tfor(var i=0; i < num_clusters; i++){\n\t\t if(cluster_data[cluster_selected][\"clusters\"][i][\"count\"] != 0){\n\t\t euclid_cluster_count += 1;\n\t\t\t\tvar cluster_ratio = cluster_data[cluster_selected][\"clusters\"][i][\"count\"] / euclidean_data[i] * cluster_data[cluster_selected][\"clusters\"][i][\"count\"] / cluster_data[cluster_selected][\"num_points\"];\n\t\t \tsim_score += cluster_ratio;\n\t\t }\n\n\t\t var pct = Math.round(cluster_data[cluster_selected][\"clusters\"][i][\"count\"] / euclidean_data[i] * 100);\n\t\t if (pct > 0)\n\t\t \tdata_string += \"Cluster \" + i.toString() + \": \" + pct.toString() + \"%
    \";\n\t\t}\n\n\t\tdata_string += \"

    Simliarity Score: \" + sim_score.toString();\n\t\tdata_string += \"
    ***Similarity score is calculated by weighting the percentage of each euclidean cluster found in the geodesic cluster. Weight is based on number of euclidean points in the cluster vs total number of euclidean points for that cluster\";\n\n\t\tdocument.getElementById(\"stats\").innerHTML = data_string;\n\n\t}", "dangerousExampleEn": "1. const data = req.query\n2. \n3. const evaldata = eval(data);\n4. const funcdata = new Function(data);\nLine 3, 4: This dynamically creates an unverified value which may cause risk of executing unintended code.", "safeExampleEn": "1. const data = req.query\n2. \n3. //const evaldata = eval(data);\n4. var reg = /[&<>'\"()\\/]/gim;\n5. var cleandata = data.replace(reg, \"\");\n6. const funcdata = new Function(cleandata);\nLine 3: Do not use the function that dynamically execute code.\nLine 5: It is safe to use replace() to remove special characters from externally input values.", "contexts": [{"lineNo": 17, "eventType": "sink", "messageKey": "jschk.CODE_INJECTION.JS.defect.sink", "params": {"arg0": "eval"}}]}} {"id": "c40ea2710b647434172005dad9bf427406ea611a5f52cdf1be697a5d5fd861fa", "license": {"spdx": ["BSD-2-Clause"], "repo": "ynsingh/brihaspati2", "path": "scrpts/Scormjs/scormmain.js", "repo_head_hexsha": "c392bb650c3f5d738bfded56b1646f25ca3a9862", "stack_hexsha": "692bfb1512baba08ad64a1dbf6c1bcc2e8063401", "match": "repo_path"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Code Injection", "issueDescriptionEn": "The security weakness allows an attacker to inject arbitrary code to change the intended behaviour of the software, causing it to behave abnormally.\nFunctions that can cause code injection attacks in Node.js include eval() and Function(). If the arguments of these functions are not carefully validated, the code passed by the attacker can be executed as is.\nAvoid using functions that can dynamically execute code.\nIf necessary, validate against external input values in a whitelist fashion, or filter user input values to include only valid characters.", "issueLineNumber": 559, "entireCode": "/**\n*script file for the scorm gui all function related to the menu load refresh navigation defined in this file\n* @see template Launchcontentnew.vm\n* @author \">\n* @author \">\n* @Created Date: 18-01-2012\n\n*/\n//SCO NAVIGATION FUNCTION\nfunction goToSco(i) {\n frame_navigation.goToSco(i);\n // alert(\"frame_navigation.goToSco(i)\");\n}\nfunction getDHTMLObj(docName, objName) {return eval(docName + theBrowser.DHTMLRange + '.' + objName + theBrowser.DHTMLStyleObj);}\nfunction getDHTMLObjTop(theObj) {return (theBrowser.code == \"MSIE\") ? theObj.pixelTop : theObj.top;}\nfunction getDHTMLObjHeight(docName, objName) {return eval(docName + theBrowser.DHTMLRange + '.' + objName + theBrowser.DHTMLDivHeight);}\nfunction getDHTMLImg(docName, objName, imgName) {\n return (theBrowser.code == 'MSIE') ? eval(docName + '.all.' + imgName) : getDHTMLObj(docName, objName).document.images[imgName];\n}\nfunction URLLoadTextDocs(entryNo)\n{\n var str1 = theMenu.entry[entryNo].url.split('/');\n var item = (str1.length>1) ? str1[str1.length-1] : theMenu.entry[entryNo].url;\n parent.frame_content.location.href = item;\n parent.frame_content.location.reload();\n}\n\nfunction toggleChild(entryNo)\n{\n for (level=theMenu.entry[entryNo].parent; level>-1; )\n {\n if ( theMenu.entry[level].isopen == false )\n eval(theMenu.toggle(level));\n level = theMenu.entry[level].parent;\n }\n highlightFocus(entryNo);\n}\nfunction highlightFocus(entryNo)\n{\n var x = self.menu.document.links.length;\n var str1 = theMenu.entry[entryNo].url.split('/');\n var item = (str1.length>1) ? str1[str1.length-1] : theMenu.entry[entryNo].url;\n for ( xloc = 0; xloc';\n }\n return tag;\n}\n// The MenuItem object. This contains the data and functions for drawing each item.\nfunction MenuItem (owner, id, type, text, url, status, nItem, pItem, parent) {\n this.owner = owner;\n this.id = id;\n this.type = type;\n this.text = text;\n this.url = url;\n this.status = status;\n this.target = owner.defaultTarget;\n this.nextItem = nItem;\n this.prevItem = pItem;\n this.FirstChild = -1;\n this.parent = parent;\n this.isopen = false;\n this.isSelected = false;\n this.draw = MIDraw;\n this.PMIconName = MIGetPMIconName;\n this.docIconName = MIGetDocIconName;\n this.setImg = MISetImage;\n this.setIsOpen = MISetIsOpen;\n this.setSelected = MISetSelected;\n this.mouseOver = MIMouseOver;\n this.mouseOut = MIMouseOut;\n var i = (this.owner.imgStore) ? this.owner.imgStore.find(type) : -2;\n if (i == -1) {i = this.owner.imgStore.find('iconPlus');}\n this.height = (i > -1) ? this.owner.imgStore.img[i].h : 0;\n}\nfunction MIDraw (indentStr) {\n var o = this.owner;\n var mRef = '=\"return ' + o.reverseRef + \".\" + o.name;\n var tmp = mRef + '.entry[' + this.id + '].';\n var MOver = ' onMouseOver' + tmp + 'mouseOver(\\''\n var MOut = ' onMouseOut' + tmp + 'mouseOut(\\''\n var iconTag = o.imgStore.getTag(this.PMIconName(), 'plusMinusIcon' + this.id, '');\n var aLine = '' + indentStr;\n if (!this.noOutlineImg) {\n if (this.FirstChild != -1) {\n aLine += '' + iconTag + '';\n } else {\n aLine += iconTag;\n }\n }\n var tip = eval('this.' + o.tipText);\n var theEntry = o.imgStore.getTag(this.docIconName(), 'docIcon' + this.id, tip) + this.text;\n var theImg = o.imgStore.getTag(this.docIconName(), 'docIcon' + this.id, tip);\n var sTxt = '';\n var lTxt = '' : '>';\n aLine += sTxt + lTxt + theImg;\n if (this.multiLine) {\n aLine += '
    '\n + sTxt + lTxt + this.text + '
    ';\n } else {\n aLine += this.text + '';\n }\n aLine += '
    ';\n return aLine\n}\nfunction MIGetPMIconName() {\n var n = 'icon' + ((this.FirstChild != -1) ? ((this.isopen == true) ? 'Minus' : 'Plus') : 'Join');\n n += (this.id == this.owner.firstEntry) ? ((this.nextItem == -1) ? 'Only' : 'Top') : ((this.nextItem == -1) ? 'Bottom' : '');\n return n;\n}\nfunction MIGetDocIconName() {\n var is = this.owner.imgStore; var n = this.type;\n n += ((this.isopen) && (is.getSrc(n + 'Expanded') != '')) ? 'Expanded' : '';\n\n ////////////////////////add this to open the folder icon\n n += ((this.isopen) && (this.FirstChild != -1)) ? 'O' : '';\n //////////////////////\n n += ((this.isSelected) && (is.getSrc(n + 'Selected') != '')) ? 'Selected' : '';\n return n;\n}\nfunction MISetImage(imgID, imgName) {\n var o = this.owner; var imgSrc = o.imgStore.getSrc(imgName);\n if ((imgSrc != '') && (theBrowser.canCache) && (!o.amBusy)) {\n var img = (theBrowser.hasDHTML) ? getDHTMLImg(o.container + '.document', 'entryDIV' + this.id, imgID) : eval(o.container).document.images[imgID];\n if (img) {img.src = imgSrc;}\n }\n}\nfunction MISetIsOpen (isOpen) {\n if ((this.isopen != isOpen) && (this.FirstChild != -1)) {\n this.isopen = isOpen;\n this.setImg('plusMinusIcon' + this.id, this.PMIconName());\n this.setImg('docIcon' + this.id, this.docIconName(false));\n return true;\n } else {\n return false;\n }\n}\nfunction MISetSelected (isSelected) {\n this.isSelected = isSelected;\n this.setImg('docIcon' + this.id, this.docIconName(false));\n if ((this.parent >= 0) && this.owner.selectParents) {this.owner.entry[this.parent].setSelected(isSelected);}\n}\nfunction MIMouseOver(imgName, theURL) {\n eval(this.owner.container).status = ''; //Needed for setStatus to work on MSIE 3 - Go figure!?\n var newImg = '';\n var s = '';\n if (imgName == 'plusMinusIcon') {\n newImg = this.PMIconName();\n s = 'Click to ' + ((this.isopen == true) ? 'collapse.' : 'expand.');\n } else {\n if (imgName == 'docIcon') {\n newImg = this.docIconName();\n s = (this.status != null) ? this.status : theURL;\n }\n }\n setStatus(s);\n if (theBrowser.canOnMouseOut) {this.setImg(imgName + this.id, newImg + 'MouseOver');}\n if(this.onMouseOver) {var me=this;eval(me.onMouseOver);}\n return true;\n}\nfunction MIMouseOut(imgName) {\n clearStatus();\n var newImg = '';\n if (imgName == 'plusMinusIcon') {\n newImg = this.PMIconName();\n } else {\n if (imgName == 'docIcon') {newImg = this.docIconName();}\n }\n this.setImg(imgName + this.id, newImg);\n if(this.onMouseOut) {var me=this;eval(me.onMouseOut);}\n return true;\n}\n// The Menu object. This is basically an array object although the data in it is a tree.\nfunction Menu () {\n this.count = -1;\n this.version = '2.4 beta';\n this.firstEntry = -1;\n this.autoScrolling = false;\n this.modalFolders = false;\n this.linkOnExpand = false;\n this.toggleOnLink = false;\n this.showAllAsLinks = false;\n this.savePage = true;\n this.name = 'theMenu';\n this.container = 'menu';\n this.reverseRef = 'parent';\n this.contentFrame = 'frame_content';\n this.defaultTarget = 'frame_content';\n this.tipText = 'none';\n this.selectParents = false;\n this.lastPMClicked = -1;\n this.selectedEntry = -1;\n this.wizardInstalled = false;\n this.amBusy = true;\n this.maxHeight = 0;\n this.imgStore = new imgStoreObject;\n this.entry = new MenuItem(this, 0, '', '', '', '', -1, -1, -1);\n this.contentWin = MenuGetContentWin;\n this.getEmptyEntry = MenuGetEmptyEntry;\n this.addEntry = MenuAddEntry;\n this.addMenu = MenuAddEntry;\n this.addChild = MenuAddChild;\n this.rmvEntry = MenuRmvEntry;\n this.rmvChildren = MenuRmvChildren;\n this.draw = MenuDraw;\n this.drawALevel = MenuDrawALevel;\n this.refresh = MenuRefresh;\n this.reload = MenuReload;\n\tthis.refreshDHTML = MenuRefreshDHTML;\n this.scrollTo = MenuScrollTo;\n this.itemClicked = MenuItemClicked;\n this.selectEntry = MenuSelectEntry;\n this.setEntry = MenuSetEntry;\n this.setEntryByURL = MenuSetEntryByURL;\n this.setAllChildren = MenuSetAllChildren;\n this.setAll = MenuSetAll;\n this.openAll = MenuOpenAll;\n this.closeAll = MenuCloseAll;\n this.findEntry = MenuFindEntry;\n this.toggle = MenuToggle;\n}\nfunction MenuGetContentWin() {\n return eval(((myOpener != null) ? 'myOpener.' : 'self.') + this.contentFrame);\n}\nfunction MenuGetEmptyEntry() {\n for (var i = 0; i <= this.count; i++) {if (this.entry[i] == null) {break;}}\n if (i > this.count) {this.count = i};\n return i\n}\nfunction MenuAddEntry (addTo, type, text, url, status, insert) {\n if (!insert) {insert=false;}\n var theNI = -1;var theP = -1;var thePI = -1;\n if (addTo < 0) {\n var i = addTo = this.firstEntry;\n if (!insert) {while (i > -1) {addTo = i;i = this.entry[i].nextItem;}}\n }\n if (addTo >= 0) {\n var e = this.entry[addTo];\n if (!e) {return -1;}\n thePI = (insert)?e.prevItem:addTo;\n theNI = (insert)?addTo:e.nextItem;\n theP = e.parent;\n }\n var eNum = this.getEmptyEntry();\n if (thePI >= 0) {\n this.entry[thePI].nextItem = eNum;\n } else {\n if (theP >= 0) {\n this.entry[theP].FirstChild = eNum;\n } else {\n this.firstEntry = eNum;\n }\n }\n if (theNI >= 0) {this.entry[theNI].prevItem = eNum;}\n this.entry[eNum] = new MenuItem(this, eNum, type, text, url, status, theNI, thePI, theP);\n return eNum;\n}\nfunction MenuAddChild (addTo, type, text, url, status, insert) {\n if (!insert) {insert=false;}\n var eNum = -1;\n if ((this.count == -1) || (addTo < 0)) {\n eNum = this.addEntry(-1, type, text, url, status, false);\n } else {\n var e = this.entry[addTo];\n if (!e) {return -1;}\n var cID = e.FirstChild;\n if (cID < 0) {\n e.FirstChild = eNum = this.getEmptyEntry();\n this.entry[eNum] = new MenuItem(this, eNum, type, text, url, status, -1, -1, addTo);\n } else {\n while (!insert && (this.entry[cID].nextItem >= 0)) {cID = this.entry[cID].nextItem;}\n eNum = this.addEntry(cID, type, text, url, status, insert);\n }\n }\n return eNum;\n}\nfunction MenuRmvEntry (theEntry) {\n var e = this.entry[theEntry];\n if (e == null) {return;}\n var p = e.prevItem;\n var n = e.nextItem;\n if (e.FirstChild > -1) {this.rmvChildren(theEntry);}\n if (this.firstEntry == theEntry) {this.firstEntry = n}\n if (this.selectedEntry == theEntry) {this.selectedEntry = n}\n if (p > -1) {\n this.entry[p].nextItem = n;\n } else {\n if (e.parent > -1) {\n this.entry[e.parent].FirstChild = n;\n } else {\n if (this.firstEntry == theEntry) {this.firstEntry = n}\n }\n }\n if (n > -1) {this.entry[n].prevItem = p;}\n this.entry[theEntry] = null;\n}\nfunction MenuRmvChildren (theP) {\n var eNum;var e;var tmp;\n if (theP == -1) {\n eNum = this.firstEntry;\n this.firstEntry = -1;\n } else {\n eNum = this.entry[theP].FirstChild;\n this.entry[theP].FirstChild = -1;\n }\n while (eNum > -1) {\n e = this.entry[eNum];\n if (e.FirstChild > -1) {this.rmvChildren(eNum);}\n if (this.selectedEntry == eNum) {this.selectedEntry = e.parent;}\n tmp = eNum;\n eNum = e.nextItem;\n this.entry[tmp] = null;\n }\n}\nfunction MenuDraw() {\n this.maxHeight = 0;\n theDoc = eval(this.container + \".document\");\n eval(this.container).document.writeln(this.drawALevel(this.firstEntry, '', true, theDoc));\n if (theBrowser.hasDHTML) {\n for (var i = 0; i <= this.count; i++) {\n if (this.entry[i]) {\n this.maxHeight += getDHTMLObjHeight(this.container + '.document', 'entryDIV' + i);\n }\n }\n } else {\n if ((this.lastPMClicked > 0) && theBrowser.mustMoveAfterLoad && this.autoScrolling) {\n this.scrollTo(this.lastPMClicked);\n }\n }\n}\nfunction MenuDrawALevel(firstItem, indentStr, isVisible, theDoc) {\n var currEntry = firstItem;\n var padImg = \"\";\n var aLine = \"\";\n var theLevel = \"\";\n var e = null;\n while (currEntry > -1) {\n e = this.entry[currEntry];\n aLine = e.draw(indentStr);\n if (theBrowser.hasDHTML) {\n aLine = '
    ' + aLine + '
    ';\n } else {\n aLine += '
    ';\n }\n theBrowser.lineByLine = true;\n if (theBrowser.lineByLine) {theDoc.writeln(aLine);} else {theLevel += aLine;}\n if ((e.FirstChild > -1) && ((theBrowser.hasDHTML || (e.isopen && isVisible)))) {\n padImg = (e.noOutlineImg) ? '' : this.imgStore.getTag((e.nextItem == -1) ? 'iconBlank' : 'iconLine', '', '');\n theLevel += this.drawALevel(e.FirstChild, indentStr + padImg, (e.isopen && isVisible), theDoc);\n }\n currEntry = e.nextItem;\n }\n return theLevel;\n}\nfunction MenuRefresh() {\n if (theBrowser.hasDHTML) {\n if (!this.amBusy) {\n this.refreshDHTML();\n if (this.autoScrolling) {this.scrollTo(this.lastPMClicked);}\n }\n } else {\n this.reload();\n }\n}\nfunction MenuReload() {\n if (!this.amBusy) {\n this.amBusy = true;\n var l = eval(this.container).location;\n var rm = theBrowser.reloadMethod;\n var newLoc = fixPath(l.pathname);\n if (theBrowser.code == 'OP') {var d = new Date(); newLoc += '?' + d.getTime();}\n if (this.autoScrolling && (this.lastPMClicked > 0) && !theBrowser.mustMoveAfterLoad) {\n newLoc += \"#joustEntry\" + this.lastPMClicked;\n }\n if (rm == 'replace') {\n l.replace(newLoc);\n } else {\n if (rm == 'reload') {\n l.reload();\n } else {\n if (rm == 'timeout') {\n setTimeout(this.container + \".location.href ='\" + newLoc + \"';\", 100);\n } else {\n l.href = newLoc;\n }\n }\n }\n }\n}\nfunction MenuRefreshDHTML() {\n var nextItemArray = new simpleArray;\n var currEntry = this.firstEntry;\n var level = (currEntry == -1) ? 0 : 1;\n var isVisible = true;\n var lastVisibleLevel = 1;\n var co = eval(this.container);\n var yPos = co.menuStart;\n var d = this.container + '.document';\n var e = null;var s = null;\n while (level > 0) {\n e = this.entry[currEntry];\n s = getDHTMLObj(d, 'entryDIV' + currEntry);\n if (isVisible) {\n s.top = yPos;\n s.visibility = 'visible';\n yPos += getDHTMLObjHeight(d, 'entryDIV' + currEntry);\n lastVisibleLevel = level;\n } else {\n s.visibility = 'hidden';\n }\n if (e.FirstChild > -1) {\n isVisible = (e.isopen == true) && isVisible;\n nextItemArray[level++] = e.nextItem;\n currEntry = e.FirstChild;\n } else {\n if (e.nextItem != -1) {\n currEntry = e.nextItem;\n } else {\n while (level > 0) {\n if (nextItemArray[--level] != -1) {\n currEntry = nextItemArray[level];\n isVisible = (lastVisibleLevel >= level);\n break;\n }\n }\n }\n }\n }\n this.maxHeight = yPos;\n co.setMenuHeight(yPos);\n}\nfunction MenuScrollTo(entryNo) {\n if (theBrowser.hasDHTML) {\n var e = this.entry[entryNo];\n if (!e) {return;}\n var co = eval(this.container);\n var d = this.container + '.document';\n var srTop = getDHTMLObjTop(getDHTMLObj(d, 'entryDIV' + entryNo));\n var srBot = (e.nextItem > 0) ? getDHTMLObjTop(getDHTMLObj(d, 'entryDIV' + e.nextItem)) : this.maxHeight;\n if (theBrowser.code == 'MSIE') {\n var curTop = co.document.body.scrollTop;\n var curBot = curTop + co.document.body.clientHeight;\n } else {\n var curTop = co.pageYOffset;\n var curBot = curTop + co.innerHeight;\n }\n if ((srBot > curBot) || (srTop < curTop)) {\n var scrBy = srBot - curBot;\n if (srTop < (curTop + scrBy)) {scrBy = srTop - curTop;}\n co.setTimeout('self.scrollBy(0, ' + scrBy + ');', 100);\n }\n } else {\n var l = eval(this.container).location.pathname + '#joustEntry' + entryNo;\n setTimeout(this.container + '.location.href = \"' + l + '\";', 100);\n }\n}\nfunction MenuItemClicked(entryNo, fromToggle) {\n var r = true;\n var e = this.entry[entryNo];\n var w = this.contentWin();\n var b = theBrowser;\n this.selectEntry(entryNo);\n if (this.wizardInstalled) {w.menuItemClicked(entryNo);}\n if(e.onClickFunc) {e.onClick = e.onClickFunc;}\n if(e.onClick) {var me=e;if(eval(e.onClick) == false) {r = false;}}\n if (r) {\n if (((this.toggleOnLink) && (e.FirstChild != -1) && !(fromToggle)) || e.noOutlineImg) {\n if (b.hasDHTML) {\n this.toggle(entryNo, true);\n } else {\n setTimeout(this.name + '.toggle(' + entryNo + ', true);', 100);\n }\n }\n }\n return (r) ? r : (e.url != '');\n}\nfunction MenuSelectEntry(entryNo) {\n var e = this.entry[entryNo];\n if (e) {\n var oe = this.entry[this.selectedEntry];\n if (oe) {oe.setSelected(false);}\n this.selectedEntry = entryNo;\n e.setSelected(true);\n }\n}\nfunction MenuSetEntry(entryNo, state) {\n var cl = ',' + entryNo + ',';\n var e = this.entry[entryNo];\n this.lastPMClicked = entryNo;\n var mc = e.setIsOpen(state);\n var p = e.parent;\n while (p >= 0) {\n cl += p + ',';\n e = this.entry[p];\n mc |= (e.setIsOpen(true));\n p = e.parent;\n }\n if (this.modalFolders) {\n for (var i = 0; i <= this.count; i++) {\n e = this.entry[i];\n if ((cl.indexOf(',' + i + ',') < 0) && e) {mc |= e.setIsOpen(false);}\n }\n }\n return mc;\n}\nfunction MenuSetEntryByURL(theURL, state) {\n var i = this.findEntry(theURL, 'url', 'right', 0);\n return (i != -1) ? this.setEntry(i, state) : false;\n}\nfunction MenuSetAllChildren(state, parentID) {\n var hasChanged = false;\n var currEntry = (parentID > -1) ? this.entry[parentID].FirstChild : this.firstEntry;\n while (currEntry > -1) {\n var e = this.entry[currEntry];\n hasChanged |= e.setIsOpen(state);\n if (e.FirstChild > -1) {hasChanged |= this.setAllChildren(state, currEntry);}\n currEntry = e.nextItem;\n }\n return hasChanged;\n}\nfunction MenuSetAll(state, parentID) {\n if (theBrowser.version >= 4) {\n if (parentID == 'undefined') {parentID = -1;}\n } else {\n if (parentID == null) {parentID = -1;}\n }\n var hasChanged = false;\n if (parentID > -1) {hasChanged |= this.entry[parentID].setIsOpen(state);}\n hasChanged |= this.setAllChildren(state, parentID);\n if (hasChanged) {\n this.lastPMClicked = this.firstEntry;\n this.refresh();\n }\n}\nfunction MenuOpenAll() {this.setAll(true, -1);}\nfunction MenuCloseAll() {this.setAll(false, -1)}\nfunction MenuFindEntry(srchVal, srchProp, matchType, start) {\n if (srchVal == \"\") {return -1;}\n if (!srchProp) {srchProp = \"url\";}\n if (!matchType) {matchType = \"exact\";}\n if (!start) {start = 0;}\n if (srchProp == \"URL\") {srchProp = \"url\";}\n if (srchProp == \"title\") {srchProp = \"text\";}\n if (typeof(srchVal) != \"string\") {matchType = \"exact\";}\n if ((matchType != \"left\") && (matchType != \"right\")) {matchType = \"exact\";}\n var lm = srchVal.length;\n for (var i = start; i <= this.count; i++) {\n var e = this.entry[i];\n if (e) {\n var currVal = eval(\"e.\" + srchProp);\n if (currVal == srchVal) {return i;}\n if ((typeof(currVal) == \"string\") && (currVal != \"\")) {\n var lc = currVal.length;\n var l = Math.min(lm,lc);\n if (matchType == \"left\") {\n if (currVal.substring(1, l) == srchVal.substring(1, l)) {return i;}\n } else {\n if (matchType == \"right\") {\n if (currVal.substring(lc-l, lc) == srchVal.substring(lm-l, lm)) {return i;}\n }\n }\n }\n }\n }\n return -1;\n}\nfunction MenuToggle(entryNo, fromClicked) {\n var r = true;\n var e = this.entry[entryNo];\n if (e.onToggle) {var me=e;if(eval(e.onToggle) == false) {r = false;}}\n if (r) {\n var chg = this.setEntry(entryNo, e.isopen ^ 1);\n if (this.linkOnExpand && e.isopen) {\n if (e.url != '') {this.contentWin().location = e.url;}\n if (!fromClicked) {this.itemClicked(entryNo, true);}\n }\n if (chg) {this.refresh();}\n }\n return false;\n}\n// Other functions\nfunction DrawMenu(m) {\n m.draw();\n}\nfunction browserInfo() {\n this.code = 'unknown';\n this.version = 0;\n this.platform = 'Win';\n var ua = navigator.userAgent;\n var i = ua.indexOf('WebTV');\n if (i >= 0) {\n this.code = 'WebTV';\n i += 6;\n } else {\n i = ua.indexOf('MSIE');\n if (i >= 0) {\n this.code = 'MSIE';\n i += 5;\n } else {\n i = ua.indexOf('Opera');\n if (i >= 0) {\n this.code = 'OP';\n i = ua.indexOf(') ') + 2;\n } else {\n i = ua.indexOf('Mozilla/');\n if (i >= 0) {\n this.code = 'NS';\n i += 8;\n }\n }\n }\n }\n this.version = parseFloat(ua.substring(i, i+4));\n if (ua.indexOf('Mac') >= 0) {this.platform = 'Mac';}\n if (ua.indexOf('OS/2') >= 0) {this.platform = 'OS/2';}\n if (ua.indexOf('X11') >= 0) {this.platform = 'UNIX';}\n var v = this.version;\n var p = this.platform;\n var NS = (this.code == 'NS');\n var IE = (this.code == 'MSIE');\n var WTV = (this.code == 'WebTV');\n var OP = (this.code == 'OP');\n var OP32up = (OP && (v >= 3.2));\n var IE4up = (IE && (v >= 4));\n var NS3up = (NS && (v >= 3));\n this.canCache = NS3up || IE4up || OP32up || WTV;\n this.canOnMouseOut = this.canCache;\n this.canOnError = NS3up || IE4up || OP32up;\n this.canJSVoid = !((NS && !NS3up) || (IE && !IE4up) || (OP && (v < 3.5)));\n this.lineByLine = (v < 4);\n this.mustMoveAfterLoad = NS3up || (IE4up && (p != 'Mac')) || WTV;\n if (NS3up || IE4up || WTV) {\n this.reloadMethod = 'replace';\n } else {\n this.reloadMethod = (NS && (v == 2.01) && (p != 'Win')) ? 'timeout' : 'href';\n }\n this.canFloat = NS || (IE && !((p == 'Mac') && (v >= 4) && (v < 5)));\n this.hasDHTML = ((NS || IE) && (v >= 4)) && !(IE && (p == 'Mac') && (v < 4.5));\n this.needLM = NS || (IE && (p == 'Mac') && (v >= 4.5));\n this.DHTMLRange = IE ? '.all' : '';\n this.DHTMLStyleObj = IE ? '.style' : '';\n this.DHTMLDivHeight = IE ? '.offsetHeight' : '.clip.height';\n}\nfunction getWindow() {return (floatingMode) ? myOpener : self;}\nfunction setStatus(theText) {\n var theWindow = getWindow();\n if (theWindow) {\n theWindow.status = theText;\n if (!theBrowser.canOnMouseOut) {\n clearTimeout(statusTimeout);\n statusTimeout = setTimeout('clearStatus()', 5000);\n }\n }\n return true;\n}\nfunction clearStatus() {\n var theWindow = getWindow();\n if (theWindow) {theWindow.status = '';}\n}\nfunction unloadFloating() {\n if (myOpener) {\n if (myOpener.JoustFrameset) {myOpener.setTimeout('menuClosed();', 100);}\n }\n}\nfunction getMode() {\n var theMode = getParm(document.cookie, 'mode', ';');\n return ((theMode == \"Floating\") || (theMode == \"NoFrames\")) ? theMode : \"Frames\";\n}\nfunction smOnError (msg, url, lno) {\n smCallerWin.onerror = oldErrorHandler;\n if (confirm(smSecurityMsg)) {setTimeout('setMode(\"' + smNewMode + '\");', 100);}\n return true;\n}\nfunction smSetCookie(theMode) {\n document.cookie = 'mode=' + theMode + '; path=/';\n if (getMode() != theMode) {\n alert(smCookieMsg);\n return false;\n } else {\n return true;\n }\n}\nfunction setMode(theMode, callerWin) {\n smNewMode = theMode\n smCallerWin = (theBrowser.code == 'NS') ? callerWin : self;\n var okToGo = true;\n var currentMode = getMode();\n if (theMode != currentMode) {\n if (currentMode == 'Floating') {\n if (smSetCookie(theMode)) {self.close();}\n } else {\n var dest = '';\n if (theBrowser.canFloat) {\n if ((theMenu.savePage) && (callerWin)) {\n if (theBrowser.canOnError) {\n oldErrorHandler = smCallerWin.onerror;\n smCallerWin.onerror = smOnError;\n }\n var p = theMenu.contentWin().location.pathname;\n if (theBrowser.canOnError) {smCallerWin.onerror = oldErrorHandler;}\n if (p) {\n dest = fixPath(p);\n } else {\n if (!confirm(smSecurityMsg)) {okToGo = false;}\n }\n }\n } else {\n alert(smNoFloat);\n okToGo = false;\n }\n if (okToGo && smSetCookie(theMode)) {\n if (theMode == 'NoFrames') {\n location.href = (index3 == '') ? ((dest == '') ? '/' : dest) : index3;\n } else {\n location.href = index2 + '?page=' + escape(dest);\n }\n }\n }\n }\n}\nfunction fixPath(p) {\n return (p.substring(0,2) == '/:') ? p.substring(p.indexOf('/', 2), p.length) : p;\n}\nfunction getParm(theStr, parm, delim) {\n // returns value of parm from string\n if (theStr.length == 0) {return '';}\n var sPos = theStr.indexOf(parm + \"=\");\n if (sPos == -1) {return '';}\n sPos = sPos + parm.length + 1;\n var ePos = theStr.indexOf(delim, sPos);\n if (ePos == -1) {ePos = theStr.length;}\n return unescape(theStr.substring(sPos, ePos));\n}\nfunction pageFromSearch(def, m, selIt) {\n var s = self.location.search;\n\t//alert(\"search===s===\"+s);\n if ((s == null) || (s.length <= 1)) {return def;}\n var p = getParm(s, 'page', '&');\n\t//alert(\"search===p===\"+p);\n p = (p != '') ? fixPath(p) : fixPath(s.substring(1, s.length));\n\t//alert(\"search===pp===\"+p);\n if (m != null) {\n var e = m.findEntry(p, 'URL', 'exact');\n\t//alert(\"search===peeep===\"+e);\n if ((e != -1) && selIt) {\n m.setEntry(e, true);\n m.selectEntry(e);\n }\n }\n return p;\n\t//alert(\"search===p===\"+p);\n}\nfunction loadURLInTop(theURL) {\n var theWindow = getWindow();\n if (theWindow) {theWindow.top.location.href = theURL;}\n}\nfunction defOnError(msg, url, lno) {\n if (jsErrorMsg == '') {\n return false;\n } else {\n alert(jsErrorMsg + '.\\n\\nError: ' + msg + '\\nPage: ' + url + '\\nLine: ' + lno + '\\nBrowser: ' + navigator.userAgent);\n return true;\n }\n}\nfunction defaultResizeHandler() {\n if ((theBrowser.code == \"NS\") && theBrowser.hasDHTML) {\n if (!eval(theMenu.container + \".document.menuBottom\")) {\n theMenu.reload();\n }\n }\n}\n// Declare global variables\nvar theBrowser = new browserInfo;\n\nvar jsErrorMsg = 'A JavaScript error has occurred on this page! Please note down the ';\njsErrorMsg += 'following information and pass it on to the WebMaster.';\nif (theBrowser.canOnError) {self.onerror = defOnError;}\n\nvar theMenu = new Menu;\nvar JoustFrameset = true;\nvar statusTimeout = 0;\nvar index1 = 'index.htm';\nvar index2 = 'index2.htm';\nvar index3 = 'index3.htm';\nvar smCallerWin;\nvar smNewMode;\nvar oldErrorHandler;\nvar smNoFloat = 'Sorry, your browser does not support this feature!';\nvar smCookieMsg = 'You must have Cookies enabled to change the display mode!';\nvar smSecurityMsg = 'Due to security restrictions imposed by your browser, I cannot ';\nsmSecurityMsg += 'change modes while a page from another server is being displayed. ';\nsmSecurityMsg += 'The default home page for this site will be displayed instead.';\n\nvar floatingMode = (getMode() == 'Floating');\nvar myOpener = null;\nif (floatingMode == true) {\n if (self.opener) {\n myOpener = self.opener;\n if (myOpener.JoustFrameset) {myOpener.setTimeout('setGlobals();', 100);}\n } else {\n document.cookie = 'mode=Frames; path=/';\n floatingMode = false;\n }\n} else {\n if (getMode() != 'Frames') {document.cookie = 'mode=Frames; path=/';}\n}\n\n// ############################ End of Joust ############################\n\nfunction initOutlineIcons(imgStore) {\n\tvar ip = '/brihaspati2/images/menu/';\n\t//alert(\"ip=========\"+ip);\n ip += (theBrowser.platform == 'Mac') ? 'mac/' : ((theBrowser.platform == 'OS/2') ? 'os2/' : 'win/');\n\n imgStore.add('iconPlusTop', ip + 'plustop.gif', 18, 16);\n imgStore.add('iconPlus', ip + 'plus.gif', 18, 16);\n imgStore.add('iconPlusBottom', ip + 'plusbottom.gif', 18, 16);\n imgStore.add('iconPlusOnly', ip + 'plusonly.gif', 18, 16);\n imgStore.add('iconMinusTop', ip + 'minustop.gif', 18, 16);\n imgStore.add('iconMinus', ip + 'minus.gif', 18, 16);\n imgStore.add('iconMinusBottom', ip + 'minusbottom.gif', 18, 16);\n imgStore.add('iconMinusOnly', ip + 'minusonly.gif', 18, 16);\n imgStore.add('iconLine', ip + 'line.gif', 18, 16);\n imgStore.add('iconBlank', ip + 'blank.gif', 18, 16);\n imgStore.add('iconJoinTop', ip + 'jointop.gif', 18, 16);\n imgStore.add('iconJoin', ip + 'join.gif', 18, 16);\n imgStore.add('iconJoinBottom', ip + 'joinbottom.gif', 18, 16);\n\n //Add folder and document images to the imgStore.\n imgStore.add('Folder', ip + 'folderclosed.gif', 18, 16);\n //////////////////////// this is the open folder icon\n imgStore.add('FolderO', ip + 'folderopen.gif', 18, 16);\n ////////////////////////\n var di = '/brihaspati2/images/menu/win/';\n\t//alert(\"di========\"+di);\n if ((theBrowser.code == 'NS') || (theBrowser.code == 'MSIE')) {\n //di += theBrowser.code.toLowerCase(); // + '_doc';\n imgStore.add('Document', di + 'document.gif', 18, 16);\n imgStore.add('DocumentMouseOver', di + 'document_mo1.gif', 18, 16);\n imgStore.add('FolderMouseOver', di + 'folderclosed3.gif', 18, 16);\n imgStore.add('FolderOMouseOver', di + 'folderopen3.gif', 18, 16);\n imgStore.add('DocumentSelected', di + 'document3.gif', 18, 16);\n imgStore.add('FolderSelected', di + 'folderclosed2.gif', 18, 16);\n imgStore.add('FolderOSelected', di + 'folderopen2.gif', 18, 16);\n imgStore.add('ref01', di + 'ref01.gif', 18, 16);\n } else {\n imgStore.add('Document', di + 'document.gif', 18, 16);\n }\n}\n//This is where items are putted\nfunction initialise(API) {\n // Tell joust where to find the various index files it needs\n index1 = 'index.htm';\n index2 = 'index2.htm';\n index3 = 'index3.htm';\n\n // Set up parameters to control menu behaviour\n theMenu.autoScrolling = true;\n theMenu.modalFolders = false;\n theMenu.linkOnExpand = false;\n theMenu.toggleOnLink = false;\n theMenu.showAllAsLinks = false;\n theMenu.savePage = true;\n theMenu.tipText = \"status\";\n theMenu.selectParents = false;\n theMenu.name = \"theMenu\";\n theMenu.container = \"self.menu\";\n theMenu.reverseRef = \"parent\";\n theMenu.contentFrame = \"frame_content\";\n theMenu.defaultTarget = \"frame_content\";\n\n // Initialise all the icons\n initOutlineIcons(theMenu.imgStore);\n\n // Now set up the menu with a whole lot of addEntry and addChild function calls\n var level1ID = -1;\n var level2ID = -1;\n var level3ID = -1;\n var level4ID = -1;\n\n //TREE MENU HERE !!\n var menutype = \"Folder\";\n //level1ID = theMenu.addMenu(-1, menutype, title, \"\", \"\");\n //theMenu.entry[level1ID].isopen = true;\n var total = API.getTotalSco();\n\t//alert(\"total====\"+total);\nfor ( i = 0; i < total; i++ ) {\n var s = i + 1;\n var sectitle = API.getTitle(i);\n var level = API.getScoLevel(i);\n var nextLevel = level;\n if ( i < total - 1 ) {\n nextLevel = API.getScoLevel(i+1);\n }\n if ( nextLevel > level )\n menutype = \"Folder\";\n else\n menutype = \"Document\";\n\n if ( i == 0 ) {\n level1ID = theMenu.addMenu(-1, menutype, sectitle, \"javascript:parent.goToSco(\" + i + \")\", \"\");\n theMenu.entry[level1ID].isopen = true;\n } else {\n if ( level == 0 )\n level1ID = theMenu.addMenu(level1ID, menutype, sectitle, \"javascript:parent.goToSco(\" + i + \")\", \"\");\n else if ( level == 1 )\n level2ID = theMenu.addChild(level1ID, menutype, sectitle, \"javascript:parent.goToSco(\" + i + \")\", \"\");\n else if ( level == 2 )\n level3ID = theMenu.addChild(level2ID, menutype, sectitle, \"javascript:parent.goToSco(\" + i + \")\", \"\");\n else if ( level == 3 )\n level4ID = theMenu.addChild(level3ID, menutype, sectitle, \"javascript:parent.goToSco(\" + i + \")\", \"\");\n\n }\n }\n\n}\n\nself.defaultStatus = \"\";", "dangerousExampleEn": "1. const data = req.query\n2. \n3. const evaldata = eval(data);\n4. const funcdata = new Function(data);\nLine 3, 4: This dynamically creates an unverified value which may cause risk of executing unintended code.", "safeExampleEn": "1. const data = req.query\n2. \n3. //const evaldata = eval(data);\n4. var reg = /[&<>'\"()\\/]/gim;\n5. var cleandata = data.replace(reg, \"\");\n6. const funcdata = new Function(cleandata);\nLine 3: Do not use the function that dynamically execute code.\nLine 5: It is safe to use replace() to remove special characters from externally input values.", "contexts": [{"lineNo": 556, "eventType": "source", "messageKey": "synz.COMMON.branch.false.assumed", "params": {"arg0": "558"}}, {"lineNo": 559, "eventType": "sink", "messageKey": "jschk.CODE_INJECTION.JS.defect.sink", "params": {"arg0": "setTimeout"}}]}} {"id": "95fe9c39264eac0b970937be37fa750ded9db57a7df1e4c581520514b7958685", "license": {"spdx": ["Apache-2.0"], "repo": "raghits/jazz", "path": "core/jazz_create-serverless-service/components/validate-sls-yml.js", "repo_head_hexsha": "cafdfe70e91b653d66c3f2f9b29e84880da087ab", "stack_hexsha": "60627bd6773c0f396913f9974d39fab1999fb18d", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Deserialization of Untrusted Data", "issueDescriptionEn": "The Deserialization of Untrusted Data checker finds code that uses an insecure deserialization method.\nYou can serialize objects for storing or transmitting, and deserialize them when you need. However, if you deserialize untrusted data without separate protection, it can run malicious code by adding a tainted object or variable.\nIf needed, use safeLoad function instead of load function on js-yaml module 2.1.0 or later version.", "issueLineNumber": 56, "entireCode": "// =========================================================================\n// Copyright � 2017 T-Mobile USA, Inc.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n// =========================================================================\n\nconst yaml = require('js-yaml');\nconst fs = require('fs');\n\nconst content = fs.readFileSync('./components/whitelist.yml');\nconst doc = yaml.safeLoad(content, 'utf8');\n\nconst concat = (x,y) =>\n x.concat(y)\n\nconst flatMap = (f,xs) =>\n xs.map(f).reduce(concat, [])\n\n// If we use the version of JS that does not support flatMap\nif(!Array.prototype.flatMap) {\n Array.prototype.flatMap = function(f) {\n return flatMap(f,this)\n }\n}\n\n// Loading the list of all types allowed\nconst allowedResourceList = Object.keys(doc.resources).flatMap(key => doc.resources[key]).map(obj => obj.Type);\nconst allowedEventNameList = Object.keys(doc.events).filter(name => name != 'stream'); // everything but stream as stream depend on type\nconst allowedStreamTypeList = doc.events['stream'].map(obj => obj.type); // Enlisting all allowed stream types\nconst allowedActions = Object.keys(doc.actions).flatMap(key => doc.actions[key].map(value => `${key}:${value}`)) // All actions in the 'resource:action' form like 'kinesis:DescribeStream'\n\nconst getReducerFunction = function(allowed) {\n return function(acc, curr) {\n if(!allowed.includes(curr)) acc.push(curr);\n return acc;\n }\n}\n// Accumulating all values that are not present in the whitelist\nconst reducer = function(acc, curr) {\n if(!allowedResourceList.includes(curr)) acc.push(curr);\n return acc;\n}\n\n/* Validates a given yml file's resources against whitelist yml */\nconst validateResources = function validateResourcesAgaistWhitelist(deploymentDescriptor) {\n const deploymentDescriptorDoc = yaml.load(deploymentDescriptor);\n if(deploymentDescriptorDoc.resources && deploymentDescriptorDoc.resources.Resources) {\n const resourcesElem = deploymentDescriptorDoc.resources.Resources;\n // Extracting all elements of 'Type' from under resources.Resources\n const allTargetResourceTypes = Object.keys(resourcesElem).map(name => resourcesElem[name].Type);\n // target minus all in whitelist should give us all oustanding resource types that a developer used outside the whitelist defined\n const outstandingResources = allTargetResourceTypes.reduce(getReducerFunction(allowedResourceList), []);\n return outstandingResources;\n } else {\n return []; // If the targetFileDoc.resources.Resources is not present there is nothing to worry about as we are not trying to create anything\n }\n}\n\nconst validateEvents = function validateEventsAgaistWhitelist(deploymentDescriptor) {\n const deploymentDescriptorDoc = yaml.load(deploymentDescriptor);\n const functionElem = deploymentDescriptorDoc.functions;\n if(functionElem) {\n\n const outstandingEvents = Object.keys(functionElem).map(name => functionElem[name])\n .filter(eventElem => eventElem.events) // Only those with 'events' sub-element are interesting here\n .flatMap(functionContent => validateEventsElement(functionContent.events));\n return outstandingEvents;\n } else {\n return [];\n }\n}\n\n/* Validating all the events under functions/events\nfunctions:\n some-random-name:\n name: SomeRandomName\n ...\n events:\n - schedule:\n rate: 160\n name: some-name\n enabled: true\n - stream:\n type: dynamodb\n*/\nconst validateEventsElement = function validateEventsInsideFunction(element) {\n const allEventNames = element.flatMap(obj => Object.keys(obj))\n .filter(name => name != 'stream'); // Everything but 'stream' that we'll handle separatelly\n const outstandingEventNames = allEventNames.reduce(getReducerFunction(allowedEventNameList), []);\n\n const allStreamTypes = element.flatMap(obj => obj['stream'])\n .filter(stream => stream) // Removing all null entries where 'stream' element could not be resolved\n .map(stream => stream.type)\n .filter(typeName => typeName); // If stream does not have 'type' then filtering that out as well\n const outstandingStreamTypes = allStreamTypes.reduce(getReducerFunction(allowedStreamTypeList), [])\n .map(str => 'stream:'+str); // Attaching 'stream' word to make it different from event name\n\n return outstandingEventNames.concat(outstandingStreamTypes);\n}\n\n/* Validating all Actions under 'provider/iamManagedPolicies'\n Example:\nprovider:\n name: aws\n iamRoleStatements:\n - Effect: \"Allow\"\n Action:\n - \"s3:ListBucket\"\n*/\nconst validateActionsInProvider = function validateActionInProviderIamRoleStatements(deploymentDescriptor) {\n const deploymentDescriptorDoc = yaml.load(deploymentDescriptor);\n const providerElem = deploymentDescriptorDoc.provider;\n if(providerElem) {\n iamRoleElem = providerElem.iamRoleStatements;\n if(iamRoleElem) {\n return validatePolicyStatement(iamRoleElem); // Removing all the actions that are allowed thus not allowed will stay in\n } else {\n return [];\n }\n } else {\n return [];\n }\n}\n\n/* Validating all Actions at resource/Resources/role[Type='AWS:IAM:Role]/Policies/Statement\n Example:\nresources:\n Resources:\n myRole:\n Type: AWS::IAM::Role\n Properties:\n Path: /my/default/path/\n RoleName: MyRole\n Policies:\n - PolicyName: myPolicyName\n PolicyDocument:\n Version: '2017'\n Statement:\n - Effect:\n Action:\n - logs:CreateLogGroup\n - logs:CreateLogStream\n*/\nconst validateActionsInResources = function validateActionsInResourceRolePolicy(deploymentDescriptor) {\n const deploymentDescriptorDoc = yaml.load(deploymentDescriptor);\n const resourcesElem = deploymentDescriptorDoc.resources;\n if(resourcesElem) { // 'resources' top element is present\n const capitalResourcesElem = resourcesElem.Resources;\n if(capitalResourcesElem) { // 'resources.Resources' element is present\n resourceValues = Object.keys(capitalResourcesElem).map(key => capitalResourcesElem[key]); // Here we are not intersted in keys but only in values that we extract\n return resourceValues.filter(aResource => aResource.Type==='AWS::IAM::Role' && // Only IAM Role resources we are interested in here\n aResource.Properties &&\n aResource.Properties.Policies)\n .flatMap(aResource => aResource.Properties.Policies) // merging all policy arrays all together [[p1,p2], [p3,p4]] => [p1,p2,p3,p4]\n .filter(policy => policy.PolicyDocument) //Only those policies with document we are integersted in\n .map(policy => policy.PolicyDocument)\n .filter(doc => doc.Statement) // Only documents with Statement inside\n .flatMap(document => validatePolicyStatement(document.Statement));\n } else {\n return [];\n }\n } else {\n return [];\n }\n\n}\n\n// Inner function that is able to validate 'Statement' structure irrespecitve off place it is encountered\nfunction validatePolicyStatement(statementElem) {\n return statementElem.filter(item => item.Effect === 'Allow' && item.Action) // Where Effect is 'Allow' and the Action sub element is present\n .flatMap(elem => elem.Action) // Combining all action subarrays into one big flat list\n .reduce(getReducerFunction(allowedActions),[]);\n}\n\n/** Finding the oustanding actions that occured in either 'provider' or 'resources'\n top element\n @deploymentDescriptor is a string with a yml file inside that looks like\nprovider:\n name: aws\n iamRoleStatements:\n - Effect: \"Allow\"\n Action:\n - \"s3:ListBucket\"\nresources:\n Resources:\n myRole:\n Type: AWS::IAM::Role\n Properties:\n Path: /my/default/path/\n RoleName: MyRole\n Policies:\n - PolicyName: myPolicyName\n PolicyDocument:\n Version: '2017'\n Statement:\n - Effect:\n Action:\n - logs:CreateLogGroup\n - logs:CreateLogStream\n\n @returns the list of oustanding actions that are not listed at whitelist.yml.\n Like ['ec2:CreateLaunchTemplate', 'ec2:CopyImage', ...]\n*/\nconst validateActions = function validateActionsInProviderAndResources(deploymentDescriptor) {\n const outstandingActionsInProvider = validateActionsInProvider(deploymentDescriptor);\n const outstandingActionsInResources = validateActionsInResources(deploymentDescriptor);\n return outstandingActionsInProvider.concat(outstandingActionsInResources);\n}\n\nmodule.exports = {\n validateResources : validateResources,\n validateEvents : validateEvents,\n validateActions: validateActions}", "dangerousExampleEn": "1. const app = require(\"express\")(),\n2. jsyaml = require(\"js-yaml\");\n3. \n4. app.get(\"load\", function(req, res) {\n5. let data = jsyaml.load(req.params.data);\n6. // ...\n7. });\nLine 5: An insecure load function of js-yaml module is used.", "safeExampleEn": "1. const app = require(\"express\")(),\n2. jsyaml = require(\"js-yaml\");\n3. \n4. app.get(\"load\", function(req, res) {\n5. let data = jsyaml.safeLoad(req.params.data);\n6. // ...\n7. });\nLine 5: Replace the load function with safeLoad function of js-yaml module.", "contexts": [{"lineNo": 56, "eventType": "sink", "messageKey": "jschk.DESERIALIZATION_OF_UNTRUSTED_DATA.JS.defect", "params": {}}]}} {"id": "7a9ace5466f962c6b333df95a27f42e780bb4d4803025822021c2b564b0b65a9", "license": {"spdx": ["MIT"], "repo": "mrvautin/envz", "path": "lib/envz.js", "repo_head_hexsha": "9fa593bebde28a3d1ce971b157a5fade50efeecd", "stack_hexsha": "c3a6508b0dbe3a50858a3014e2e0e6c6b67b9893", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Deserialization of Untrusted Data", "issueDescriptionEn": "The Deserialization of Untrusted Data checker finds code that uses an insecure deserialization method.\nYou can serialize objects for storing or transmitting, and deserialize them when you need. However, if you deserialize untrusted data without separate protection, it can run malicious code by adding a tainted object or variable.\nIf needed, use safeLoad function instead of load function on js-yaml module 2.1.0 or later version.", "issueLineNumber": 36, "entireCode": "const yaml = require('js-yaml');\nconst merge = require('deepmerge');\nconst path = require('path');\n\n// Do this for backward compatibility\nconst util = require('util');\nconst fs = require('fs');\nconst readFile = util.promisify(fs.readFile);\nconst writeFile = util.promisify(fs.writeFile);\n\nconst envz = (envfile, opts) => {\n opts = Object.assign(process.env, opts || {});\n\n // Set the CWD\n opts.cwd = process.cwd();\n\n // Set the env or fallback to development\n opts.env = process.env.NODE_ENV || 'development';\n\n // If env is supplied, override the defaults\n if(opts.environment){\n opts.env = opts.environment;\n }\n\n // Read in the file\n envfile = path.resolve(opts.cwd, envfile || 'env.yaml');\n\n // Check file exists\n if(!fs.existsSync(envfile)){\n throw new Error('Env yaml file does not exist');\n }\n\n const contents = fs.readFileSync(envfile, 'utf8');\n\n // Parse the env contents\n const parsed = yaml.load(contents);\n\n // Setup objects to merge\n const mergeObjects = [];\n\n // If set, set the ENV first and override with env.yaml file\n if(opts.yamlFileOverride === true){\n mergeObjects.push(Object.assign({}, opts, { envFilePath: envfile }));\n }\n\n for(const environment in parsed){\n // If an env is set, break on that and don't cascade\n if(opts.env === environment){\n mergeObjects.push(parsed[environment]);\n break;\n }\n mergeObjects.push(parsed[environment]);\n }\n\n // If not set or false, override file with environment variables\n if(!opts.yamlFileOverride || opts.yamlFileOverride === false || opts.yamlFileOverride === 'false'){\n mergeObjects.push(Object.assign({}, opts, { envFilePath: envfile }));\n }\n\n const processed = merge.all(mergeObjects);\n return processed;\n};\n\nconst save = async (opts) => {\n let error = '';\n // Check the opts are ok\n if(!opts.envfile){\n return 'env file not supplied';\n }\n if(!opts.data){\n return 'env data not supplied';\n }\n\n // Get the config object\n opts.envfile = path.resolve(process.cwd(), opts.envfile || 'env.yaml');\n\n // Check file exists\n if(!fs.existsSync(opts.envfile)){\n throw new Error('Env yaml file does not exist');\n }\n\n const contents = await readFile(opts.envfile, 'utf8');\n\n // Parse the env contents\n const parsed = yaml.load(contents);\n\n // Merge supplied with current\n const processed = merge.all([parsed, opts.data]);\n\n // Process merged object to yaml string\n const yamlString = yaml.dump(processed, {});\n\n // Write yaml back to file\n try{\n await writeFile(opts.envfile, yamlString);\n }catch(ex){\n error = 'Failure to save the file';\n }\n\n return {\n data: processed,\n error\n };\n};\n\nmodule.exports = {\n envz,\n save\n};", "dangerousExampleEn": "1. const app = require(\"express\")(),\n2. jsyaml = require(\"js-yaml\");\n3. \n4. app.get(\"load\", function(req, res) {\n5. let data = jsyaml.load(req.params.data);\n6. // ...\n7. });\nLine 5: An insecure load function of js-yaml module is used.", "safeExampleEn": "1. const app = require(\"express\")(),\n2. jsyaml = require(\"js-yaml\");\n3. \n4. app.get(\"load\", function(req, res) {\n5. let data = jsyaml.safeLoad(req.params.data);\n6. // ...\n7. });\nLine 5: Replace the load function with safeLoad function of js-yaml module.", "contexts": [{"lineNo": 36, "eventType": "sink", "messageKey": "jschk.DESERIALIZATION_OF_UNTRUSTED_DATA.JS.defect", "params": {}}]}} {"id": "887716f3700442263e453821904655e256c6f6715cda7f672abdbda3686c819f", "license": {"spdx": ["Apache-2.0"], "repo": "dibend/blast_web_server", "path": "server.js", "repo_head_hexsha": "2f7d4e118ff38b00248c50ee8f2643ab89e6ed30", "stack_hexsha": "7df01bea3650be35811fe8152b131db730e2ffec", "match": "repo_path"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Log injection", "issueDescriptionEn": "The Log injection checker finds instances of printing out unvalidated user inputs in a log.\nIf unvalidated user inputs are printed out in a log, an attacker can insert arbitrary content in the log to confuse security personnel who consult the log. If a manipulated log successfully leads to making an inappropriate decision, the attacker can exploit the consequences.\nHave external inputs validated before they are logged. It is particularly recommended to delete newline characters.", "issueLineNumber": 63, "entireCode": "'use strict';\nvar fs = require('fs');\nvar express = require('express');\nvar cors = require('cors');\nvar http = require('http');\nvar https = require('https');\nvar compression = require('compression');\nvar path = require('path');\nvar crypto = require('crypto');\nvar emailValidator = require('email-validator');\nvar nodemailer = require('nodemailer');\nvar smtpTransport = require('nodemailer-smtp-transport');\nvar mysql = require('mysql');\nvar frameguard = require('frameguard');\nvar config = require('./config');\n\nvar mailer = nodemailer.createTransport(smtpTransport({\n host: config.ses_host,\n secureConnection: true,\n port: 465,\n auth: {\n user: config.ses_user,\n pass: config.\n }\n}));\n\nvar db = mysql.createPool({\n connectionLimit: 10,\n host: config.mysql_host,\n user: config.mysql_user,\n password: ,\n database: config.mysql_db\n});\n\nvar sslKey = fs.readFileSync('letsencrypt/privkey.pem', 'utf8');\nvar sslCert = fs.readFileSync('letsencrypt/cert.pem', 'utf8');\nvar ca = [\n fs.readFileSync('letsencrypt/chain.pem', 'utf8'), \n fs.readFileSync('letsencrypt/fullchain.pem', 'utf8')\n]; \n\nvar creds = {\n key: sslKey,\n cert: sslCert,\n ca: ca\n};\n\nvar app = express();\napp.use(cors());\napp.use(compression());\napp.use(frameguard({action: 'deny'}));\napp.use(express.static('public', {extensions: ['html']}));\n\nfunction getIP(request) {\n return (request.headers['x-forwarded-for'] ||\n request.connection.remoteAddress ||\n request.socket.remoteAddress ||\n request.connection.socket.remoteAddress).split(\",\")[0];\n}\n\napp.get('/view', function(request, response) {\n var ip = getIP(request);\n console.log(ip + ' loaded view ' + request.query.url + ' from ' + request.query.src + ' at ' + (new Date().toUTCString()));\n fs.readFile('public/view1.html', 'utf8', function(err, data) {\n if (err) throw err;\n var titleSplit = data.split('{{ title }}');\n if(request.query.title) {\n data = titleSplit[0] + request.query.title + titleSplit[1];\n } else {\n data = titleSplit[0] + 'Blast Notifications' + titleSplit[1];\n }\n var linkSplit = data.split('{{ link }}');\n if(request.query.url) {\n data = linkSplit[0] + 'https://blastnotifications.com/view?url=' + request.query.url + '&title=' + request.query.title + linkSplit[1];\n } else {\n data = linkSplit[0] + 'https://blastnotifications.com' + linkSplit[1];\n }\n response.send(data); \n });\n});\n\n\n\napp.get('/track.png', function(request, response) {\n var ip = getIP(request);\n console.log(ip + ' ' + request.query.email + ' loaded ' + request.query.blast + ' blast at ' + (new Date().toUTCString()));\n response.send();\n});\n\napp.get('/redir', function(request, response) {\n if(/globesold\\.com|robinhood\\.com|renaissancecapital\\.com|nasdaq\\.com|currenciesdirect\\.com|bittrex\\.com|yahoo\\.com|whitehouse\\.gov|worldstarhiphop\\.com|metacritic\\.com|cnn\\.com|cnet\\.com|theverge\\.com|zerohedge\\.com|thezenofinvesting\\.com/.test(request.query.url)) {\n var ip = getIP(request);\n console.log(ip + ' opened ' + request.query.url + ' at ' + (new Date().toUTCString()));\n response.redirect(request.query.url);\n } else {\n response.redirect('/');\n }\n});\n\nvar ws_confirmEmailQuery = {};\napp.get('/signup_ws', function(request, response) {\n var email = request.query.email;\n if (emailValidator.validate(email)) {\n var secret = crypto.randomBytes(64).toString('hex'); \n ws_confirmEmailQuery[secret] = email;\n \n var mailOptions = {\n from: config.from,\n to: email,\n subject: 'Confirm Worldstar Blast Notification',\n text: 'Visit https://blastnotifications.com/confirm_ws?secret=' + secret + ' to verify your subscription!'\n };\n\n mailer.sendMail(mailOptions, function(err, res) {\n if(err) {\n console.log(err);\n }\n mailer.close();\n });\n console.log(getIP(request) + ' ' + email + ' confirmation sent at ' + (new Date().toUTCString()));\n response.redirect('/confirm.html');\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\napp.get('/confirm_ws', function(request, response) {\n var secret = request.query.secret;\n if(secret in ws_confirmEmailQuery) {\n var email = ws_confirmEmailQuery[secret]; \n \n db.query('INSERT IGNORE INTO worldstar SET ?', {email: email}, function (error) {\n if (error) {\n console.log(error);\n }\n });\n \n response.redirect('/confirmed.html');\n console.log(getIP(request) + ' ' + email + ' confirmed at ' + (new Date().toUTCString()));\n delete ws_confirmEmailQuery[secret]; \n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n } \n});\n\nvar daily_funder_confirmEmailQuery = {};\napp.get('/signup_daily_funder', function(request, response) {\n var email = request.query.email;\n if (emailValidator.validate(email)) {\n var secret = crypto.randomBytes(64).toString('hex'); \n daily_funder_confirmEmailQuery[secret] = email;\n \n var mailOptions = {\n from: config.from,\n to: email,\n subject: 'Confirm Daily Funder Blast Notification',\n text: 'Visit https://blastnotifications.com/confirm_daily_funder?secret=' + secret + ' to verify your subscription!'\n };\n\n mailer.sendMail(mailOptions, function(err, res) {\n if(err) {\n console.log(err);\n }\n mailer.close();\n });\n console.log(getIP(request) + ' ' + email + ' confirmation sent at ' + (new Date().toUTCString()));\n response.redirect('/confirm.html');\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\napp.get('/confirm_daily_funder', function(request, response) {\n var secret = request.query.secret;\n if(secret in daily_funder_confirmEmailQuery) {\n var email = daily_funder_confirmEmailQuery[secret]; \n \n db.query('INSERT IGNORE INTO daily_funder SET ?', {email: email}, function (error) {\n if (error) {\n console.log(error);\n }\n });\n \n response.redirect('/confirmed.html');\n console.log(getIP(request) + ' ' + email + ' confirmed at ' + (new Date().toUTCString()));\n delete daily_funder_confirmEmailQuery[secret]; \n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n } \n});\n\nvar fedbiz_confirmEmailQuery = {};\napp.get('/signup_fedbiz', function(request, response) {\n var email = request.query.email;\n if (emailValidator.validate(email)) {\n var secret = crypto.randomBytes(64).toString('hex');\n fedbiz_confirmEmailQuery[secret] = email;\n\n var mailOptions = {\n from: config.from,\n to: email,\n subject: 'Confirm FedBizOpps Blast Notification',\n text: 'Visit https://blastnotifications.com/confirm_fedbiz?secret=' + secret + ' to verify your subscription!'\n };\n\n mailer.sendMail(mailOptions, function(err, res) {\n if(err) {\n console.log(err);\n }\n mailer.close();\n });\n console.log(getIP(request) + ' ' + email + ' confirmation sent at ' + (new Date().toUTCString()));\n response.redirect('/confirm.html');\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\napp.get('/confirm_fedbiz', function(request, response) {\n var secret = request.query.secret;\n if(secret in fedbiz_confirmEmailQuery) {\n var email = fedbiz_confirmEmailQuery[secret];\n\n db.query('INSERT IGNORE INTO fedbiz SET ?', {email: email}, function (error) {\n if (error) {\n console.log(error);\n }\n });\n\n response.redirect('/confirmed.html');\n console.log(getIP(request) + ' ' + email + ' confirmed at ' + (new Date().toUTCString()));\n delete fedbiz_confirmEmailQuery[secret];\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\nvar coin_removals_confirmEmailQuery = {};\napp.get('/signup_coin_removals', function(request, response) {\n var email = request.query.email;\n if (emailValidator.validate(email)) {\n var secret = crypto.randomBytes(64).toString('hex');\n coin_removals_confirmEmailQuery[secret] = email;\n\n var mailOptions = {\n from: config.from,\n to: email,\n subject: 'Confirm Bittrex Coin Removal Blast Notification',\n text: 'Visit https://blastnotifications.com/confirm_coin_removals?secret=' + secret + ' to verify your subscription!'\n };\n\n mailer.sendMail(mailOptions, function(err, res) {\n if(err) {\n console.log(err);\n }\n mailer.close();\n });\n console.log(getIP(request) + ' ' + email + ' confirmation sent at ' + (new Date().toUTCString()));\n response.redirect('/confirm.html');\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\napp.get('/confirm_coin_removals', function(request, response) {\n var secret = request.query.secret;\n if(secret in coin_removals_confirmEmailQuery) {\n var email = coin_removals_confirmEmailQuery[secret];\n\n db.query('INSERT IGNORE INTO coin_removals SET ?', {email: email}, function (error) {\n if (error) {\n console.log(error);\n }\n });\n\n response.redirect('/confirmed.html');\n console.log(getIP(request) + ' ' + email + ' confirmed at ' + (new Date().toUTCString()));\n delete coin_removals_confirmEmailQuery[secret];\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\nvar zerohedge_confirmEmailQuery = {};\napp.get('/signup_zerohedge', function(request, response) {\n var email = request.query.email;\n if (emailValidator.validate(email)) {\n var secret = crypto.randomBytes(64).toString('hex');\n zerohedge_confirmEmailQuery[secret] = email;\n\n var mailOptions = {\n from: config.from,\n to: email,\n subject: 'Confirm Zero Hedge News Blast Notification',\n text: 'Visit https://blastnotifications.com/confirm_zerohedge?secret=' + secret + ' to verify your subscription!'\n };\n\n mailer.sendMail(mailOptions, function(err, res) {\n if(err) {\n console.log(err);\n }\n mailer.close();\n });\n console.log(getIP(request) + ' ' + email + ' confirmation sent at ' + (new Date().toUTCString()));\n response.redirect('/confirm.html');\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\napp.get('/confirm_zerohedge', function(request, response) {\n var secret = request.query.secret;\n if(secret in zerohedge_confirmEmailQuery) {\n var email = zerohedge_confirmEmailQuery[secret];\n\n db.query('INSERT IGNORE INTO zerohedge SET ?', {email: email}, function (error) {\n if (error) {\n console.log(error);\n }\n });\n\n response.redirect('/confirmed.html');\n console.log(getIP(request) + ' ' + email + ' confirmed at ' + (new Date().toUTCString()));\n delete zerohedge_confirmEmailQuery[secret];\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\nvar bloomberg_stock_confirmEmailQuery = {};\napp.get('/signup_bloomberg_stock', function(request, response) {\n var email = request.query.email;\n if (emailValidator.validate(email)) {\n var secret = crypto.randomBytes(64).toString('hex'); \n bloomberg_stock_confirmEmailQuery[secret] = email;\n \n var mailOptions = {\n from: config.from,\n to: email,\n subject: 'Confirm Bloomberg Stocks Blast Notification',\n text: 'Visit https://blastnotifications.com/confirm_bloomberg_stock?secret=' + secret + ' to verify your subscription!'\n };\n\n mailer.sendMail(mailOptions, function(err, res) {\n if(err) {\n console.log(err);\n }\n mailer.close();\n });\n console.log(getIP(request) + ' ' + email + ' confirmation sent at ' + (new Date().toUTCString()));\n response.redirect('/confirm.html');\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\napp.get('/confirm_bloomberg_stock', function(request, response) {\n var secret = request.query.secret;\n if(secret in bloomberg_stock_confirmEmailQuery) {\n var email = bloomberg_stock_confirmEmailQuery[secret]; \n \n db.query('INSERT IGNORE INTO bloomberg_stock SET ?', {email: email}, function (error) {\n if (error) {\n console.log(error);\n }\n });\n \n response.redirect('/confirmed.html');\n console.log(getIP(request) + ' ' + email + ' confirmed at ' + (new Date().toUTCString()));\n delete bloomberg_stock_confirmEmailQuery[secret]; \n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n } \n});\n\nvar bloomberg_currency_confirmEmailQuery = {};\napp.get('/signup_bloomberg_currency', function(request, response) {\n var email = request.query.email;\n if (emailValidator.validate(email)) {\n var secret = crypto.randomBytes(64).toString('hex'); \n bloomberg_currency_confirmEmailQuery[secret] = email;\n \n var mailOptions = {\n from: config.from,\n to: email,\n subject: 'Confirm Bloomberg Currency Blast Notification',\n text: 'Visit https://blastnotifications.com/confirm_bloomberg_currency?secret=' + secret + ' to verify your subscription!'\n };\n\n mailer.sendMail(mailOptions, function(err, res) {\n if(err) {\n console.log(err);\n }\n mailer.close();\n });\n console.log(getIP(request) + ' ' + email + ' confirmation sent at ' + (new Date().toUTCString()));\n response.redirect('/confirm.html');\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\napp.get('/confirm_bloomberg_currency', function(request, response) {\n var secret = request.query.secret;\n if(secret in bloomberg_currency_confirmEmailQuery) {\n var email = bloomberg_currency_confirmEmailQuery[secret]; \n \n db.query('INSERT IGNORE INTO bloomberg_currency SET ?', {email: email}, function (error) {\n if (error) { \n console.log(error);\n }\n });\n \n response.redirect('/confirmed.html');\n console.log(getIP(request) + ' ' + email + ' confirmed at ' + (new Date().toUTCString()));\n delete bloomberg_currency_confirmEmailQuery[secret]; \n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n } \n});\n\nvar bloomberg_startup_confirmEmailQuery = {};\napp.get('/signup_bloomberg_startup', function(request, response) {\n var email = request.query.email;\n if (emailValidator.validate(email)) {\n var secret = crypto.randomBytes(64).toString('hex'); \n bloomberg_startup_confirmEmailQuery[secret] = email;\n \n var mailOptions = {\n from: config.from,\n to: email,\n subject: 'Confirm Bloomberg Startup Blast Notification',\n text: 'Visit https://blastnotifications.com/confirm_bloomberg_startup?secret=' + secret + ' to verify your subscription!'\n };\n\n mailer.sendMail(mailOptions, function(err, res) {\n if(err) {\n console.log(err);\n }\n mailer.close();\n });\n console.log(getIP(request) + ' ' + email + ' confirmation sent at ' + (new Date().toUTCString()));\n response.redirect('/confirm.html');\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\napp.get('/confirm_bloomberg_startup', function(request, response) {\n var secret = request.query.secret;\n if(secret in bloomberg_startup_confirmEmailQuery) {\n var email = bloomberg_startup_confirmEmailQuery[secret]; \n \n db.query('INSERT IGNORE INTO bloomberg_startup SET ?', {email: email}, function (error) {\n if (error) {\n console.log(error);\n }\n });\n \n response.redirect('/confirmed.html');\n console.log(getIP(request) + ' ' + email + ' confirmed at ' + (new Date().toUTCString()));\n delete bloomberg_startup_confirmEmailQuery[secret]; \n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n } \n});\n\nvar reuters_business_confirmEmailQuery = {};\napp.get('/signup_reuters_business', function(request, response) {\n var email = request.query.email;\n if (emailValidator.validate(email)) {\n var secret = crypto.randomBytes(64).toString('hex'); \n reuters_business_confirmEmailQuery[secret] = email;\n \n var mailOptions = {\n from: config.from,\n to: email,\n subject: 'Confirm Reuters Business Blast Notification',\n text: 'Visit https://blastnotifications.com/confirm_reuters_business?secret=' + secret + ' to verify your subscription!'\n };\n\n mailer.sendMail(mailOptions, function(err, res) {\n if(err) {\n console.log(err);\n }\n mailer.close();\n });\n console.log(getIP(request) + ' ' + email + ' confirmation sent at ' + (new Date().toUTCString()));\n response.redirect('/confirm.html');\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\napp.get('/confirm_reuters_business', function(request, response) {\n var secret = request.query.secret;\n if(secret in reuters_business_confirmEmailQuery) {\n var email = reuters_business_confirmEmailQuery[secret]; \n \n db.query('INSERT IGNORE INTO reuters_business SET ?', {email: email}, function (error) {\n if (error) {\n console.log(error);\n }\n });\n \n response.redirect('/confirmed.html');\n console.log(getIP(request) + ' ' + email + ' confirmed at ' + (new Date().toUTCString()));\n delete reuters_business_confirmEmailQuery[secret]; \n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n } \n});\n\nvar therealreal_chanel_bags_confirmEmailQuery = {};\napp.get('/signup_therealreal_chanel_bags', function(request, response) {\n var email = request.query.email;\n if (emailValidator.validate(email)) {\n var secret = crypto.randomBytes(64).toString('hex');\n therealreal_chanel_bags_confirmEmailQuery[secret] = email;\n\n var mailOptions = {\n from: config.from,\n to: email,\n subject: 'Confirm The RealReal Chanel Bags Blast Notification',\n text: 'Visit https://blastnotifications.com/confirm_therealreal_chanel_bags?secret=' + secret + ' to verify your subscription!'\n };\n\n mailer.sendMail(mailOptions, function(err, res) {\n if(err) {\n console.log(err);\n }\n mailer.close();\n });\n console.log(getIP(request) + ' ' + email + ' confirmation sent at ' + (new Date().toUTCString()));\n response.redirect('/confirm.html');\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\napp.get('/confirm_therealreal_chanel_bags', function(request, response) {\n var secret = request.query.secret;\n if(secret in therealreal_chanel_bags_confirmEmailQuery) {\n var email = therealreal_chanel_bags_confirmEmailQuery[secret];\n\n db.query('INSERT IGNORE INTO therealreal_chanel_bags SET ?', {email: email}, function (error) {\n if (error) {\n console.log(error);\n }\n });\n\n response.redirect('/confirmed.html');\n console.log(getIP(request) + ' ' + email + ' confirmed at ' + (new Date().toUTCString()));\n delete therealreal_chanel_bags_confirmEmailQuery[secret];\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\nvar gomovies_confirmEmailQuery = {};\napp.get('/signup_gomovies', function(request, response) {\n var email = request.query.email;\n if (emailValidator.validate(email)) {\n var secret = crypto.randomBytes(64).toString('hex');\n gomovies_confirmEmailQuery[secret] = email;\n\n var mailOptions = {\n from: config.from,\n to: email,\n subject: 'Confirm Go Movies Blast Notification',\n text: 'Visit https://blastnotifications.com/confirm_gomovies?secret=' + secret + ' to verify your subscription!'\n };\n\n mailer.sendMail(mailOptions, function(err, res) {\n if(err) {\n console.log(err);\n }\n mailer.close();\n });\n console.log(getIP(request) + ' ' + email + ' confirmation sent at ' + (new Date().toUTCString()));\n response.redirect('/confirm.html');\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\napp.get('/confirm_gomovies', function(request, response) {\n var secret = request.query.secret;\n if(secret in gomovies_confirmEmailQuery) {\n var email = gomovies_confirmEmailQuery[secret];\n\n db.query('INSERT IGNORE INTO gomovies SET ?', {email: email}, function (error) {\n if (error) {\n console.log(error);\n }\n });\n\n response.redirect('/confirmed.html');\n console.log(getIP(request) + ' ' + email + ' confirmed at ' + (new Date().toUTCString()));\n delete gomovies_confirmEmailQuery[secret];\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\nvar yahoo_nfl_confirmEmailQuery = {};\napp.get('/signup_yahoo_nfl', function(request, response) {\n var email = request.query.email;\n if (emailValidator.validate(email)) {\n var secret = crypto.randomBytes(64).toString('hex');\n yahoo_nfl_confirmEmailQuery[secret] = email;\n\n var mailOptions = {\n from: config.from,\n to: email,\n subject: 'Confirm Yahoo NFL Blast Notification',\n text: 'Visit https://blastnotifications.com/confirm_yahoo_nfl?secret=' + secret + ' to verify your subscription!'\n };\n\n mailer.sendMail(mailOptions, function(err, res) {\n if(err) {\n console.log(err);\n }\n mailer.close();\n });\n console.log(getIP(request) + ' ' + email + ' confirmation sent at ' + (new Date().toUTCString()));\n response.redirect('/confirm.html');\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\napp.get('/confirm_yahoo_nfl', function(request, response) {\n var secret = request.query.secret;\n if(secret in yahoo_nfl_confirmEmailQuery) {\n var email = yahoo_nfl_confirmEmailQuery[secret];\n\n db.query('INSERT IGNORE INTO yahoo_nfl SET ?', {email: email}, function (error) {\n if (error) {\n console.log(error);\n }\n });\n\n response.redirect('/confirmed.html');\n console.log(getIP(request) + ' ' + email + ' confirmed at ' + (new Date().toUTCString()));\n delete yahoo_nfl_confirmEmailQuery[secret];\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\nvar yahoo_nba_confirmEmailQuery = {};\napp.get('/signup_yahoo_nba', function(request, response) {\n var email = request.query.email;\n if (emailValidator.validate(email)) {\n var secret = crypto.randomBytes(64).toString('hex');\n yahoo_nba_confirmEmailQuery[secret] = email;\n\n var mailOptions = {\n from: config.from,\n to: email,\n subject: 'Confirm Yahoo NBA Blast Notification',\n text: 'Visit https://blastnotifications.com/confirm_yahoo_nba?secret=' + secret + ' to verify your subscription!'\n };\n\n mailer.sendMail(mailOptions, function(err, res) {\n if(err) {\n console.log(err);\n }\n mailer.close();\n });\n console.log(getIP(request) + ' ' + email + ' confirmation sent at ' + (new Date().toUTCString()));\n response.redirect('/confirm.html');\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\napp.get('/confirm_yahoo_nba', function(request, response) {\n var secret = request.query.secret;\n if(secret in yahoo_nba_confirmEmailQuery) {\n var email = yahoo_nba_confirmEmailQuery[secret];\n\n db.query('INSERT IGNORE INTO yahoo_nba SET ?', {email: email}, function (error) {\n if (error) {\n console.log(error);\n }\n });\n\n response.redirect('/confirmed.html');\n console.log(getIP(request) + ' ' + email + ' confirmed at ' + (new Date().toUTCString()));\n delete yahoo_nba_confirmEmailQuery[secret];\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\nvar monster_it_sales_confirmEmailQuery = {};\napp.get('/signup_monster_it_sales', function(request, response) {\n var email = request.query.email;\n if (emailValidator.validate(email)) {\n var secret = crypto.randomBytes(64).toString('hex');\n monster_it_sales_confirmEmailQuery[secret] = email;\n\n var mailOptions = {\n from: config.from,\n to: email,\n subject: 'Confirm Monster IT Sales Jobs Notifications',\n text: 'Visit https://blastnotifications.com/confirm_monster_it_sales?secret=' + secret + ' to verify your subscription!'\n };\n\n mailer.sendMail(mailOptions, function(err, res) {\n if(err) {\n console.log(err);\n }\n mailer.close();\n });\n console.log(getIP(request) + ' ' + email + ' confirmation sent at ' + (new Date().toUTCString()));\n response.redirect('/confirm.html');\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\napp.get('/confirm_monster_it_sales', function(request, response) {\n var secret = request.query.secret;\n if(secret in monster_it_sales_confirmEmailQuery) {\n var email = monster_it_sales_confirmEmailQuery[secret];\n\n db.query('INSERT IGNORE INTO monster_it_sales SET ?', {email: email}, function (error) {\n if (error) {\n console.log(error);\n }\n });\n\n response.redirect('/confirmed.html');\n console.log(getIP(request) + ' ' + email + ' confirmed at ' + (new Date().toUTCString()));\n delete monster_it_sales_confirmEmailQuery[secret];\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\nvar datpiff_confirmEmailQuery = {};\napp.get('/signup_datpiff', function(request, response) {\n var email = request.query.email;\n if (emailValidator.validate(email)) {\n var secret = crypto.randomBytes(64).toString('hex');\n datpiff_confirmEmailQuery[secret] = email;\n\n var mailOptions = {\n from: config.from,\n to: email,\n subject: 'Confirm DatPiff Mixtape Notifications',\n text: 'Visit https://blastnotifications.com/confirm_datpiff?secret=' + secret + ' to verify your subscription!'\n };\n\n mailer.sendMail(mailOptions, function(err, res) {\n if(err) {\n console.log(err);\n }\n mailer.close();\n });\n console.log(getIP(request) + ' ' + email + ' confirmation sent at ' + (new Date().toUTCString()));\n response.redirect('/confirm.html');\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\napp.get('/confirm_datpiff', function(request, response) {\n var secret = request.query.secret;\n if(secret in datpiff_confirmEmailQuery) {\n var email = datpiff_confirmEmailQuery[secret];\n\n db.query('INSERT IGNORE INTO datpiff SET ?', {email: email}, function (error) {\n if (error) {\n console.log(error);\n }\n });\n\n response.redirect('/confirmed.html');\n console.log(getIP(request) + ' ' + email + ' confirmed at ' + (new Date().toUTCString()));\n delete datpiff_confirmEmailQuery[secret];\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\nvar nasdaq_headlines_confirmEmailQuery = {};\napp.get('/signup_nasdaq_headlines', function(request, response) {\n var email = request.query.email;\n if (emailValidator.validate(email)) {\n var secret = crypto.randomBytes(64).toString('hex');\n nasdaq_headlines_confirmEmailQuery[secret] = email;\n\n var mailOptions = {\n from: config.from,\n to: email,\n subject: 'Confirm Nasdaq Market Headlines Blast Notification',\n text: 'Visit https://blastnotifications.com/confirm_nasdaq_headlines?secret=' + secret + ' to verify your subscription!'\n };\n\n mailer.sendMail(mailOptions, function(err, res) {\n if(err) {\n console.log(err);\n }\n mailer.close();\n });\n console.log(getIP(request) + ' ' + email + ' confirmation sent at ' + (new Date().toUTCString()));\n response.redirect('/confirm.html');\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\napp.get('/confirm_nasdaq_headlines', function(request, response) {\n var secret = request.query.secret;\n if(secret in nasdaq_headlines_confirmEmailQuery) {\n var email = nasdaq_headlines_confirmEmailQuery[secret];\n\n db.query('INSERT IGNORE INTO nasdaq_headlines SET ?', {email: email}, function (error) {\n if (error) {\n console.log(error);\n }\n });\n\n response.redirect('/confirmed.html');\n console.log(getIP(request) + ' ' + email + ' confirmed at ' + (new Date().toUTCString()));\n delete nasdaq_headlines_confirmEmailQuery[secret];\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\nvar nasdaq_earnings_surprise_confirmEmailQuery = {};\napp.get('/signup_nasdaq_earnings_surprise', function(request, response) {\n var email = request.query.email;\n if (emailValidator.validate(email)) {\n var secret = crypto.randomBytes(64).toString('hex');\n nasdaq_earnings_surprise_confirmEmailQuery[secret] = email;\n\n var mailOptions = {\n from: config.from,\n to: email,\n subject: 'Confirm Nasdaq Earnings Surprise Notifications',\n text: 'Visit https://blastnotifications.com/confirm_nasdaq_earnings_surprise?secret=' + secret + ' to verify your subscription!'\n };\n\n mailer.sendMail(mailOptions, function(err, res) {\n if(err) {\n console.log(err);\n }\n mailer.close();\n });\n console.log(getIP(request) + ' ' + email + ' confirmation sent at ' + (new Date().toUTCString()));\n response.redirect('/confirm.html');\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\napp.get('/confirm_nasdaq_earnings_surprise', function(request, response) {\n var secret = request.query.secret;\n if(secret in nasdaq_earnings_surprise_confirmEmailQuery) {\n var email = nasdaq_earnings_surprise_confirmEmailQuery[secret];\n\n db.query('INSERT IGNORE INTO nasdaq_earnings_surprise SET ?', {email: email}, function (error) {\n if (error) {\n console.log(error);\n }\n });\n\n response.redirect('/confirmed.html');\n console.log(getIP(request) + ' ' + email + ' confirmed at ' + (new Date().toUTCString()));\n delete nasdaq_earnings_surprise_confirmEmailQuery[secret];\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\nvar nasdaq_upcoming_ipo_confirmEmailQuery = {};\napp.get('/signup_nasdaq_upcoming_ipo', function(request, response) {\n var email = request.query.email;\n if (emailValidator.validate(email)) {\n var secret = crypto.randomBytes(64).toString('hex');\n nasdaq_upcoming_ipo_confirmEmailQuery[secret] = email;\n\n var mailOptions = {\n from: config.from,\n to: email,\n subject: 'Confirm Nasdaq Upcoming IPOs Blast Notification',\n text: 'Visit https://blastnotifications.com/confirm_nasdaq_upcoming_ipo?secret=' + secret + ' to verify your subscription!'\n };\n\n mailer.sendMail(mailOptions, function(err, res) {\n if(err) {\n console.log(err);\n }\n mailer.close();\n });\n console.log(getIP(request) + ' ' + email + ' confirmation sent at ' + (new Date().toUTCString()));\n response.redirect('/confirm.html');\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\napp.get('/confirm_nasdaq_upcoming_ipo', function(request, response) {\n var secret = request.query.secret;\n if(secret in nasdaq_upcoming_ipo_confirmEmailQuery) {\n var email = nasdaq_upcoming_ipo_confirmEmailQuery[secret];\n\n db.query('INSERT IGNORE INTO nasdaq_upcoming_ipo SET ?', {email: email}, function (error) {\n if (error) {\n console.log(error);\n }\n });\n\n response.redirect('/confirmed.html');\n console.log(getIP(request) + ' ' + email + ' confirmed at ' + (new Date().toUTCString()));\n delete nasdaq_upcoming_ipo_confirmEmailQuery[secret];\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\nvar eb_manhattan_parties_confirmEmailQuery = {};\napp.get('/signup_eb_manhattan_parties', function(request, response) {\n var email = request.query.email;\n if (emailValidator.validate(email)) {\n var secret = crypto.randomBytes(64).toString('hex');\n eb_manhattan_parties_confirmEmailQuery[secret] = email;\n\n var mailOptions = {\n from: config.from,\n to: email,\n subject: 'Confirm Eventbrite Manhattan Parties Blast Notification',\n text: 'Visit https://blastnotifications.com/confirm_eb_manhattan_parties?secret=' + secret + ' to verify your subscription!'\n };\n\n mailer.sendMail(mailOptions, function(err, res) {\n if(err) {\n console.log(err);\n }\n mailer.close();\n });\n console.log(getIP(request) + ' ' + email + ' confirmation sent at ' + (new Date().toUTCString()));\n response.redirect('/confirm.html');\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\napp.get('/confirm_eb_manhattan_parties', function(request, response) {\n var secret = request.query.secret;\n if(secret in eb_manhattan_parties_confirmEmailQuery) {\n var email = eb_manhattan_parties_confirmEmailQuery[secret];\n\n db.query('INSERT IGNORE INTO eb_manhattan_parties SET ?', {email: email}, function (error) {\n if (error) {\n console.log(error);\n }\n });\n\n response.redirect('/confirmed.html');\n console.log(getIP(request) + ' ' + email + ' confirmed at ' + (new Date().toUTCString()));\n delete eb_manhattan_parties_confirmEmailQuery[secret];\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\nvar executive_orders_confirmEmailQuery = {};\napp.get('/signup_executive_orders', function(request, response) {\n var email = request.query.email;\n if (emailValidator.validate(email)) {\n var secret = crypto.randomBytes(64).toString('hex');\n executive_orders_confirmEmailQuery[secret] = email;\n\n var mailOptions = {\n from: config.from,\n to: email,\n subject: 'Confirm White House Executive Orders Blast Notification',\n text: 'Visit https://blastnotifications.com/confirm_executive_orders?secret=' + secret + ' to verify your subscription!'\n };\n\n mailer.sendMail(mailOptions, function(err, res) {\n if(err) {\n console.log(err);\n }\n mailer.close();\n });\n console.log(getIP(request) + ' ' + email + ' confirmation sent at ' + (new Date().toUTCString()));\n response.redirect('/confirm.html');\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\napp.get('/confirm_executive_orders', function(request, response) {\n var secret = request.query.secret;\n if(secret in executive_orders_confirmEmailQuery) {\n var email = executive_orders_confirmEmailQuery[secret];\n\n db.query('INSERT IGNORE INTO executive_orders SET ?', {email: email}, function (error) {\n if (error) {\n console.log(error);\n }\n });\n\n response.redirect('/confirmed.html');\n console.log(getIP(request) + ' ' + email + ' confirmed at ' + (new Date().toUTCString()));\n delete executive_orders_confirmEmailQuery[secret];\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\nvar forex_factory_confirmEmailQuery = {};\napp.get('/signup_forex_factory', function(request, response) {\n var email = request.query.email;\n if (emailValidator.validate(email)) {\n var secret = crypto.randomBytes(64).toString('hex');\n forex_factory_confirmEmailQuery[secret] = email;\n\n var mailOptions = {\n from: config.from,\n to: email,\n subject: 'Confirm Forex Factory Blast Notification',\n text: 'Visit https://blastnotifications.com/confirm_forex_factory?secret=' + secret + ' to verify your subscription!'\n };\n\n mailer.sendMail(mailOptions, function(err, res) {\n if(err) {\n console.log(err);\n }\n mailer.close();\n });\n console.log(getIP(request) + ' ' + email + ' confirmation sent at ' + (new Date().toUTCString()));\n response.redirect('/confirm.html');\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\napp.get('/confirm_forex_factory', function(request, response) {\n var secret = request.query.secret;\n if(secret in forex_factory_confirmEmailQuery) {\n var email = forex_factory_confirmEmailQuery[secret];\n\n db.query('INSERT IGNORE INTO forex_factory SET ?', {email: email}, function (error) {\n if (error) {\n console.log(error);\n }\n });\n\n response.redirect('/confirmed.html');\n console.log(getIP(request) + ' ' + email + ' confirmed at ' + (new Date().toUTCString()));\n delete forex_factory_confirmEmailQuery[secret];\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\nvar eb_la_parties_confirmEmailQuery = {};\napp.get('/signup_eb_la_parties', function(request, response) {\n var email = request.query.email;\n if (emailValidator.validate(email)) {\n var secret = crypto.randomBytes(64).toString('hex');\n eb_la_parties_confirmEmailQuery[secret] = email;\n\n var mailOptions = {\n from: config.from,\n to: email,\n subject: 'Confirm Eventbrite LA Parties Blast Notification',\n text: 'Visit https://blastnotifications.com/confirm_eb_la_parties?secret=' + secret + ' to verify your subscription!'\n };\n\n mailer.sendMail(mailOptions, function(err, res) {\n if(err) {\n console.log(err);\n }\n mailer.close();\n });\n console.log(getIP(request) + ' ' + email + ' confirmation sent at ' + (new Date().toUTCString()));\n response.redirect('/confirm.html');\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\napp.get('/confirm_eb_la_parties', function(request, response) {\n var secret = request.query.secret;\n if(secret in eb_la_parties_confirmEmailQuery) {\n var email = eb_la_parties_confirmEmailQuery[secret];\n\n db.query('INSERT IGNORE INTO eb_la_parties SET ?', {email: email}, function (error) {\n if (error) {\n console.log(error);\n }\n });\n\n response.redirect('/confirmed.html');\n console.log(getIP(request) + ' ' + email + ' confirmed at ' + (new Date().toUTCString()));\n delete eb_la_parties_confirmEmailQuery[secret];\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\nvar metacritic_xboxone_confirmEmailQuery = {};\napp.get('/signup_metacritic_xboxone', function(request, response) {\n var email = request.query.email;\n if (emailValidator.validate(email)) {\n var secret = crypto.randomBytes(64).toString('hex');\n metacritic_xboxone_confirmEmailQuery[secret] = email;\n\n var mailOptions = {\n from: config.from,\n to: email,\n subject: 'Confirm Metacritic Xbox One Games Blast Notification',\n text: 'Visit https://blastnotifications.com/confirm_metacritic_xboxone?secret=' + secret + ' to verify your subscription!'\n };\n\n mailer.sendMail(mailOptions, function(err, res) {\n if(err) {\n console.log(err);\n }\n mailer.close();\n });\n console.log(getIP(request) + ' ' + email + ' confirmation sent at ' + (new Date().toUTCString()));\n response.redirect('/confirm.html');\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\napp.get('/confirm_metacritic_xboxone', function(request, response) {\n var secret = request.query.secret;\n if(secret in metacritic_xboxone_confirmEmailQuery) {\n var email = metacritic_xboxone_confirmEmailQuery[secret];\n\n db.query('INSERT IGNORE INTO metacritic_xboxone SET ?', {email: email}, function (error) {\n if (error) {\n console.log(error);\n }\n });\n\n response.redirect('/confirmed.html');\n console.log(getIP(request) + ' ' + email + ' confirmed at ' + (new Date().toUTCString()));\n delete metacritic_xboxone_confirmEmailQuery[secret];\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\nvar metacritic_ps4_confirmEmailQuery = {}; \napp.get('/signup_metacritic_ps4', function(request, response) {\n var email = request.query.email;\n if (emailValidator.validate(email)) {\n var secret = crypto.randomBytes(64).toString('hex');\n metacritic_ps4_confirmEmailQuery[secret] = email;\n\n var mailOptions = {\n from: config.from,\n to: email,\n subject: 'Confirm Metacritic PS4 Games Blast Notification',\n text: 'Visit https://blastnotifications.com/confirm_metacritic_ps4?secret=' + secret + ' to verify your subscription!'\n };\n\n mailer.sendMail(mailOptions, function(err, res) {\n if(err) {\n console.log(err);\n }\n mailer.close();\n });\n console.log(getIP(request) + ' ' + email + ' confirmation sent at ' + (new Date().toUTCString()));\n response.redirect('/confirm.html');\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\napp.get('/confirm_metacritic_ps4', function(request, response) {\n var secret = request.query.secret;\n if(secret in metacritic_ps4_confirmEmailQuery) {\n var email = metacritic_ps4_confirmEmailQuery[secret];\n\n db.query('INSERT IGNORE INTO metacritic_ps4 SET ?', {email: email}, function (error) {\n if (error) {\n console.log(error);\n }\n });\n\n response.redirect('/confirmed.html');\n console.log(getIP(request) + ' ' + email + ' confirmed at ' + (new Date().toUTCString()));\n delete metacritic_ps4_confirmEmailQuery[secret];\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\nvar fox_news_videos_confirmEmailQuery = {};\napp.get('/signup_fox_news_videos', function(request, response) {\n var email = request.query.email;\n if (emailValidator.validate(email)) {\n var secret = crypto.randomBytes(64).toString('hex');\n fox_news_videos_confirmEmailQuery[secret] = email;\n\n var mailOptions = {\n from: config.from,\n to: email,\n subject: 'Confirm Fox News Videos Blast Notification',\n text: 'Visit https://blastnotifications.com/confirm_fox_news_videos?secret=' + secret + ' to verify your subscription!'\n };\n\n mailer.sendMail(mailOptions, function(err, res) {\n if(err) {\n console.log(err);\n }\n mailer.close();\n });\n console.log(getIP(request) + ' ' + email + ' confirmation sent at ' + (new Date().toUTCString()));\n response.redirect('/confirm.html');\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\napp.get('/confirm_fox_news_videos', function(request, response) {\n var secret = request.query.secret;\n if(secret in fox_news_videos_confirmEmailQuery) {\n var email = fox_news_videos_confirmEmailQuery[secret];\n\n db.query('INSERT IGNORE INTO fox_news_videos SET ?', {email: email}, function (error) {\n if (error) {\n console.log(error);\n }\n });\n\n response.redirect('/confirmed.html');\n console.log(getIP(request) + ' ' + email + ' confirmed at ' + (new Date().toUTCString()));\n delete fox_news_videos_confirmEmailQuery[secret];\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\nvar metacritic_movies_confirmEmailQuery = {};\napp.get('/signup_metacritic_movies', function(request, response) {\n var email = request.query.email;\n if (emailValidator.validate(email)) {\n var secret = crypto.randomBytes(64).toString('hex');\n metacritic_movies_confirmEmailQuery[secret] = email;\n\n var mailOptions = {\n from: config.from,\n to: email,\n subject: 'Confirm Metacritic Movie Releases Blast Notification',\n text: 'Visit https://blastnotifications.com/confirm_metacritic_movies?secret=' + secret + ' to verify your subscription!'\n };\n\n mailer.sendMail(mailOptions, function(err, res) {\n if(err) {\n console.log(err);\n }\n mailer.close();\n });\n console.log(getIP(request) + ' ' + email + ' confirmation sent at ' + (new Date().toUTCString()));\n response.redirect('/confirm.html');\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\napp.get('/confirm_metacritic_movies', function(request, response) {\n var secret = request.query.secret;\n if(secret in metacritic_movies_confirmEmailQuery) {\n var email = metacritic_movies_confirmEmailQuery[secret];\n\n db.query('INSERT IGNORE INTO metacritic_movies SET ?', {email: email}, function (error) {\n if (error) {\n console.log(error);\n }\n });\n\n response.redirect('/confirmed.html');\n console.log(getIP(request) + ' ' + email + ' confirmed at ' + (new Date().toUTCString()));\n delete metacritic_movies_confirmEmailQuery[secret];\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\nvar cnn_news_videos_confirmEmailQuery = {};\napp.get('/signup_cnn_news_videos', function(request, response) {\n var email = request.query.email;\n if (emailValidator.validate(email)) {\n var secret = crypto.randomBytes(64).toString('hex');\n cnn_news_videos_confirmEmailQuery[secret] = email;\n\n var mailOptions = {\n from: config.from,\n to: email,\n subject: 'Confirm CNN News Videos Blast Notification',\n text: 'Visit https://blastnotifications.com/confirm_cnn_news_videos?secret=' + secret + ' to verify your subscription!'\n };\n\n mailer.sendMail(mailOptions, function(err, res) {\n if(err) {\n console.log(err);\n }\n mailer.close();\n });\n console.log(getIP(request) + ' ' + email + ' confirmation sent at ' + (new Date().toUTCString()));\n response.redirect('/confirm.html');\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\napp.get('/confirm_cnn_news_videos', function(request, response) {\n var secret = request.query.secret;\n if(secret in cnn_news_videos_confirmEmailQuery) {\n var email = cnn_news_videos_confirmEmailQuery[secret];\n\n db.query('INSERT IGNORE INTO cnn_news_videos SET ?', {email: email}, function (error) {\n if (error) {\n console.log(error);\n }\n });\n\n response.redirect('/confirmed.html');\n console.log(getIP(request) + ' ' + email + ' confirmed at ' + (new Date().toUTCString()));\n delete cnn_news_videos_confirmEmailQuery[secret];\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\nvar msnbc_news_videos_confirmEmailQuery = {};\napp.get('/signup_msnbc_news_videos', function(request, response) {\n var email = request.query.email;\n if (emailValidator.validate(email)) {\n var secret = crypto.randomBytes(64).toString('hex');\n msnbc_news_videos_confirmEmailQuery[secret] = email;\n\n var mailOptions = {\n from: config.from,\n to: email,\n subject: 'Confirm MSNBC News Videos Blast Notification',\n text: 'Visit https://blastnotifications.com/confirm_msnbc_news_videos?secret=' + secret + ' to verify your subscription!'\n };\n\n mailer.sendMail(mailOptions, function(err, res) {\n if(err) {\n console.log(err);\n }\n mailer.close();\n });\n console.log(getIP(request) + ' ' + email + ' confirmation sent at ' + (new Date().toUTCString()));\n response.redirect('/confirm.html');\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\napp.get('/confirm_msnbc_news_videos', function(request, response) {\n var secret = request.query.secret;\n if(secret in msnbc_news_videos_confirmEmailQuery) {\n var email = msnbc_news_videos_confirmEmailQuery[secret];\n\n db.query('INSERT IGNORE INTO msnbc_news_videos SET ?', {email: email}, function (error) {\n if (error) {\n console.log(error);\n }\n });\n\n response.redirect('/confirmed.html');\n console.log(getIP(request) + ' ' + email + ' confirmed at ' + (new Date().toUTCString()));\n delete msnbc_news_videos_confirmEmailQuery[secret];\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\nvar reuters_tech_confirmEmailQuery = {};\napp.get('/signup_reuters_tech', function(request, response) {\n var email = request.query.email;\n if (emailValidator.validate(email)) {\n var secret = crypto.randomBytes(64).toString('hex');\n reuters_tech_confirmEmailQuery[secret] = email;\n\n var mailOptions = {\n from: config.from,\n to: email,\n subject: 'Confirm Reuters Tech News Blast Notification',\n text: 'Visit https://blastnotifications.com/confirm_reuters_tech?secret=' + secret + ' to verify your subscription!'\n };\n\n mailer.sendMail(mailOptions, function(err, res) {\n if(err) {\n console.log(err);\n }\n mailer.close();\n });\n console.log(getIP(request) + ' ' + email + ' confirmation sent at ' + (new Date().toUTCString()));\n response.redirect('/confirm.html');\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\napp.get('/confirm_reuters_tech', function(request, response) {\n var secret = request.query.secret;\n if(secret in reuters_tech_confirmEmailQuery) {\n var email = reuters_tech_confirmEmailQuery[secret];\n\n db.query('INSERT IGNORE INTO reuters_tech SET ?', {email: email}, function (error) {\n if (error) {\n console.log(error);\n }\n });\n\n response.redirect('/confirmed.html');\n console.log(getIP(request) + ' ' + email + ' confirmed at ' + (new Date().toUTCString()));\n delete reuters_tech_confirmEmailQuery[secret];\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\nvar cnet_confirmEmailQuery = {};\napp.get('/signup_cnet', function(request, response) {\n var email = request.query.email;\n if (emailValidator.validate(email)) {\n var secret = crypto.randomBytes(64).toString('hex');\n cnet_confirmEmailQuery[secret] = email;\n\n var mailOptions = {\n from: config.from,\n to: email,\n subject: 'Confirm CNET News Blast Notification',\n text: 'Visit https://blastnotifications.com/confirm_cnet?secret=' + secret + ' to verify your subscription!'\n };\n\n mailer.sendMail(mailOptions, function(err, res) {\n if(err) {\n console.log(err);\n }\n mailer.close();\n });\n console.log(getIP(request) + ' ' + email + ' confirmation sent at ' + (new Date().toUTCString()));\n response.redirect('/confirm.html');\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\napp.get('/confirm_cnet', function(request, response) {\n var secret = request.query.secret;\n if(secret in cnet_confirmEmailQuery) {\n var email = cnet_confirmEmailQuery[secret];\n\n db.query('INSERT IGNORE INTO cnet SET ?', {email: email}, function (error) {\n if (error) {\n console.log(error);\n }\n });\n\n response.redirect('/confirmed.html');\n console.log(getIP(request) + ' ' + email + ' confirmed at ' + (new Date().toUTCString()));\n delete cnet_confirmEmailQuery[secret];\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\nvar the_verge_confirmEmailQuery = {};\napp.get('/signup_the_verge', function(request, response) {\n var email = request.query.email;\n if (emailValidator.validate(email)) {\n var secret = crypto.randomBytes(64).toString('hex');\n the_verge_confirmEmailQuery[secret] = email;\n\n var mailOptions = {\n from: config.from,\n to: email,\n subject: 'Confirm The Verge Articles Blast Notification',\n text: 'Visit https://blastnotifications.com/confirm_the_verge?secret=' + secret + ' to verify your subscription!'\n };\n\n mailer.sendMail(mailOptions, function(err, res) {\n if(err) {\n console.log(err);\n }\n mailer.close();\n });\n console.log(getIP(request) + ' ' + email + ' confirmation sent at ' + (new Date().toUTCString()));\n response.redirect('/confirm.html');\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\napp.get('/confirm_the_verge', function(request, response) {\n var secret = request.query.secret;\n if(secret in the_verge_confirmEmailQuery) {\n var email = the_verge_confirmEmailQuery[secret];\n\n db.query('INSERT IGNORE INTO the_verge SET ?', {email: email}, function (error) {\n if (error) {\n console.log(error);\n }\n });\n\n response.redirect('/confirmed.html');\n console.log(getIP(request) + ' ' + email + ' confirmed at ' + (new Date().toUTCString()));\n delete the_verge_confirmEmailQuery[secret];\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\nvar currency_direct_confirmEmailQuery = {};\napp.get('/signup_currency_direct', function(request, response) {\n var email = request.query.email;\n if (emailValidator.validate(email)) {\n var secret = crypto.randomBytes(64).toString('hex');\n currency_direct_confirmEmailQuery[secret] = email;\n\n var mailOptions = {\n from: config.from,\n to: email,\n subject: 'Confirm Currencies Direct News Blast Notification',\n text: 'Visit https://blastnotifications.com/confirm_currency_direct?secret=' + secret + ' to verify your subscription!'\n };\n\n mailer.sendMail(mailOptions, function(err, res) {\n if(err) {\n console.log(err);\n }\n mailer.close();\n });\n console.log(getIP(request) + ' ' + email + ' confirmation sent at ' + (new Date().toUTCString()));\n response.redirect('/confirm.html');\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\napp.get('/confirm_currency_direct', function(request, response) {\n var secret = request.query.secret;\n if(secret in currency_direct_confirmEmailQuery) {\n var email = currency_direct_confirmEmailQuery[secret];\n\n db.query('INSERT IGNORE INTO currency_direct SET ?', {email: email}, function (error) {\n if (error) {\n console.log(error);\n }\n });\n\n response.redirect('/confirmed.html');\n console.log(getIP(request) + ' ' + email + ' confirmed at ' + (new Date().toUTCString()));\n delete currency_direct_confirmEmailQuery[secret];\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\nvar itunes_songs_confirmEmailQuery = {};\napp.get('/signup_itunes_songs', function(request, response) {\n var email = request.query.email;\n if (emailValidator.validate(email)) {\n var secret = crypto.randomBytes(64).toString('hex');\n itunes_songs_confirmEmailQuery[secret] = email;\n\n var mailOptions = {\n from: config.from,\n to: email,\n subject: 'Confirm iTunes Songs Blast Notification',\n text: 'Visit https://blastnotifications.com/confirm_itunes_songs?secret=' + secret + ' to verify your subscription!'\n };\n\n mailer.sendMail(mailOptions, function(err, res) {\n if(err) {\n console.log(err);\n }\n mailer.close();\n });\n console.log(getIP(request) + ' ' + email + ' confirmation sent at ' + (new Date().toUTCString()));\n response.redirect('/confirm.html');\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\napp.get('/confirm_itunes_songs', function(request, response) {\n var secret = request.query.secret;\n if(secret in itunes_songs_confirmEmailQuery) {\n var email = itunes_songs_confirmEmailQuery[secret];\n\n db.query('INSERT IGNORE INTO itunes_songs SET ?', {email: email}, function (error) {\n if (error) {\n console.log(error);\n }\n });\n\n response.redirect('/confirmed.html');\n console.log(getIP(request) + ' ' + email + ' confirmed at ' + (new Date().toUTCString()));\n delete itunes_songs_confirmEmailQuery[secret];\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\nvar itunes_albums_confirmEmailQuery = {};\napp.get('/signup_itunes_albums', function(request, response) {\n var email = request.query.email;\n if (emailValidator.validate(email)) {\n var secret = crypto.randomBytes(64).toString('hex');\n itunes_albums_confirmEmailQuery[secret] = email;\n\n var mailOptions = {\n from: config.from,\n to: email,\n subject: 'Confirm iTunes Albums Blast Notification',\n text: 'Visit https://blastnotifications.com/confirm_itunes_albums?secret=' + secret + ' to verify your subscription!'\n };\n\n mailer.sendMail(mailOptions, function(err, res) {\n if(err) {\n console.log(err);\n }\n mailer.close();\n });\n console.log(getIP(request) + ' ' + email + ' confirmation sent at ' + (new Date().toUTCString()));\n response.redirect('/confirm.html');\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\napp.get('/confirm_itunes_albums', function(request, response) {\n var secret = request.query.secret;\n if(secret in itunes_albums_confirmEmailQuery) {\n var email = itunes_albums_confirmEmailQuery[secret];\n\n db.query('INSERT IGNORE INTO itunes_albums SET ?', {email: email}, function (error) {\n if (error) {\n console.log(error);\n }\n });\n\n response.redirect('/confirmed.html');\n console.log(getIP(request) + ' ' + email + ' confirmed at ' + (new Date().toUTCString()));\n delete itunes_albums_confirmEmailQuery[secret];\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\nvar itunes_free_apps_confirmEmailQuery = {};\napp.get('/signup_itunes_free_apps', function(request, response) {\n var email = request.query.email;\n if (emailValidator.validate(email)) {\n var secret = crypto.randomBytes(64).toString('hex');\n itunes_free_apps_confirmEmailQuery[secret] = email;\n\n var mailOptions = {\n from: config.from,\n to: email,\n subject: 'Confirm iTunes Free Apps Blast Notification',\n text: 'Visit https://blastnotifications.com/confirm_itunes_free_apps?secret=' + secret + ' to verify your subscription!'\n };\n\n mailer.sendMail(mailOptions, function(err, res) {\n if(err) {\n console.log(err);\n }\n mailer.close();\n });\n console.log(getIP(request) + ' ' + email + ' confirmation sent at ' + (new Date().toUTCString()));\n response.redirect('/confirm.html');\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\napp.get('/confirm_itunes_free_apps', function(request, response) {\n var secret = request.query.secret;\n if(secret in itunes_free_apps_confirmEmailQuery) {\n var email = itunes_free_apps_confirmEmailQuery[secret];\n\n db.query('INSERT IGNORE INTO itunes_free_apps SET ?', {email: email}, function (error) {\n if (error) {\n console.log(error);\n }\n });\n\n response.redirect('/confirmed.html');\n console.log(getIP(request) + ' ' + email + ' confirmed at ' + (new Date().toUTCString()));\n delete itunes_free_apps_confirmEmailQuery[secret];\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\nvar itunes_paid_apps_confirmEmailQuery = {};\napp.get('/signup_itunes_paid_apps', function(request, response) {\n var email = request.query.email;\n if (emailValidator.validate(email)) {\n var secret = crypto.randomBytes(64).toString('hex');\n itunes_paid_apps_confirmEmailQuery[secret] = email;\n\n var mailOptions = {\n from: config.from,\n to: email,\n subject: 'Confirm iTunes Paid Apps Blast Notification',\n text: 'Visit https://blastnotifications.com/confirm_itunes_paid_apps?secret=' + secret + ' to verify your subscription!'\n };\n\n mailer.sendMail(mailOptions, function(err, res) {\n if(err) {\n console.log(err);\n }\n mailer.close();\n });\n console.log(getIP(request) + ' ' + email + ' confirmation sent at ' + (new Date().toUTCString()));\n response.redirect('/confirm.html');\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\napp.get('/confirm_itunes_paid_apps', function(request, response) {\n var secret = request.query.secret;\n if(secret in itunes_paid_apps_confirmEmailQuery) {\n var email = itunes_paid_apps_confirmEmailQuery[secret];\n\n db.query('INSERT IGNORE INTO itunes_paid_apps SET ?', {email: email}, function (error) {\n if (error) {\n console.log(error);\n }\n });\n\n response.redirect('/confirmed.html');\n console.log(getIP(request) + ' ' + email + ' confirmed at ' + (new Date().toUTCString()));\n delete itunes_paid_apps_confirmEmailQuery[secret];\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\nvar spinoffs_confirmEmailQuery = {};\napp.get('/signup_spinoffs', function(request, response) {\n var email = request.query.email;\n if (emailValidator.validate(email)) {\n var secret = crypto.randomBytes(64).toString('hex');\n spinoffs_confirmEmailQuery[secret] = email;\n\n var mailOptions = {\n from: config.from,\n to: email,\n subject: 'Confirm Upcoming Spinoffs Blast Notification',\n text: 'Visit https://blastnotifications.com/confirm_spinoffs?secret=' + secret + ' to verify your subscription!'\n };\n\n mailer.sendMail(mailOptions, function(err, res) {\n if(err) {\n console.log(err);\n }\n mailer.close();\n });\n console.log(getIP(request) + ' ' + email + ' confirmation sent at ' + (new Date().toUTCString()));\n response.redirect('/confirm.html');\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\napp.get('/confirm_spinoffs', function(request, response) {\n var secret = request.query.secret;\n if(secret in spinoffs_confirmEmailQuery) {\n var email = spinoffs_confirmEmailQuery[secret];\n\n db.query('INSERT IGNORE INTO spinoffs SET ?', {email: email}, function (error) {\n if (error) {\n console.log(error);\n }\n });\n\n response.redirect('/confirmed.html');\n console.log(getIP(request) + ' ' + email + ' confirmed at ' + (new Date().toUTCString()));\n delete spinoffs_confirmEmailQuery[secret];\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\nvar pc_games_confirmEmailQuery = {};\napp.get('/signup_pc_games', function(request, response) {\n var email = request.query.email;\n if (emailValidator.validate(email)) {\n var secret = crypto.randomBytes(64).toString('hex');\n pc_games_confirmEmailQuery[secret] = email;\n\n var mailOptions = {\n from: config.from,\n to: email,\n subject: 'Confirm New PC Games Blast Notification',\n text: 'Visit https://blastnotifications.com/confirm_pc_games?secret=' + secret + ' to verify your subscription!'\n };\n\n mailer.sendMail(mailOptions, function(err, res) {\n if(err) {\n console.log(err);\n }\n mailer.close();\n });\n console.log(getIP(request) + ' PC Games ' + email + ' confirmation sent at ' + (new Date().toUTCString()));\n response.redirect('/confirm.html');\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\napp.get('/confirm_pc_games', function(request, response) {\n var secret = request.query.secret;\n if(secret in pc_games_confirmEmailQuery) {\n var email = pc_games_confirmEmailQuery[secret];\n\n db.query('INSERT IGNORE INTO pc_games SET ?', {email: email}, function (error) {\n if (error) {\n console.log(error);\n }\n });\n\n response.redirect('/confirmed.html');\n console.log(getIP(request) + ' PC Games ' + email + ' confirmed at ' + (new Date().toUTCString()));\n delete pc_games_confirmEmailQuery[secret];\n } else {\n response.status(404);\n response.sendFile(path.join(__dirname+'/public/404.html'));\n }\n});\n\napp.get('/signup_np_real_estate', function(request, response) {\n var email = request.query.email;\n if (emailValidator.validate(email)) {\n var mailOptions = {\n from: config.from,\n to: '',\n subject: 'New Providence Real Estate Lead',\n text: email\n };\n\n mailer.sendMail(mailOptions, function(err, res) {\n if(err) {\n console.log(err);\n }\n mailer.close();\n });\n };\n response.redirect('https://np.micheled.com/new-providence-real-estate-market-report.pdf');\n});\n\napp.get('*', function(request, response) {\n response.redirect('/');\n});\n\nhttp.createServer(function (req, res) {\n res.writeHead(301, { 'Location': 'https://' + req.headers['host'] + req.url });\n res.end();\n}).listen(8080);\n\nhttps.createServer(creds, app).listen(8443);", "dangerousExampleEn": "1. //in node.js\n2. app.post('/test', function(req, res) {\n3. console.log(req.query.url);\n4. });\nLine 3: An unvalidated external input is printed out to a log.", "safeExampleEn": "1. ...\nLine 3: Filter out the external input.", "contexts": [{"lineNo": 63, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "log"}}]}} {"id": "635bac5a2e464e7009afc5adb5edbd014f96e2d943168d3f4bc49f84b6c9f403", "license": {"spdx": ["MIT"], "repo": "laura3arual/smarttools", "path": "videoStreamingServer.js", "repo_head_hexsha": "2e38125858d40b0738d416d638147291f898665d", "stack_hexsha": "e136d3e235168358331c8e54a96f7397f5d04e33", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Log injection", "issueDescriptionEn": "The Log injection checker finds instances of printing out unvalidated user inputs in a log.\nIf unvalidated user inputs are printed out in a log, an attacker can insert arbitrary content in the log to confuse security personnel who consult the log. If a manipulated log successfully leads to making an inappropriate decision, the attacker can exploit the consequences.\nHave external inputs validated before they are logged. It is particularly recommended to delete newline characters.", "issueLineNumber": 8, "entireCode": "var fs = require('fs'),\n http = require('http'),\n url = require('url'),\n path = require('path');\n\nhttp.createServer( function(req, res){\n console.log(\"=================\");\n console.log('convertedVideos' + req.url);\n console.log(\"=================\");\n console.log(path.resolve('convertedVideos' + req.url));\n var file = path.resolve('convertedVideos' + req.url);\n if(file){\n var range = req.headers.range;\n var positions = range.replace(/bytes=/, '').split('-');\n var start = parseInt(positions[0], 10);\n\n fs.stat(file, function(err, stats){\n console.log(stats);\n var total = stats.size;\n var end = positions[1] ? parseInt(positions[1], 10) : total - 1;\n var chunkSize = (end - start) + 1;\n\n res.writeHead(206, {\n 'Content-Range': 'bytes ' + start + '-' + end + '/' + total,\n 'Accept-Ranges': 'bytes',\n 'Content-Length': chunkSize,\n 'Content-Type': 'video/mp4'\n });\n\n var stream = fs.createReadStream(file, { start: start, end: end })\n .on('open', function(){\n stream.pipe(res);\n }).on('error', function(err){\n res.end(err);\n });\n\n res.on('close', function(){\n // close or destroy stream\n stream = null;\n });\n });\n }\n\n}).listen(9000);", "dangerousExampleEn": "1. //in node.js\n2. app.post('/test', function(req, res) {\n3. console.log(req.query.url);\n4. });\nLine 3: An unvalidated external input is printed out to a log.", "safeExampleEn": "1. ...\nLine 3: Filter out the external input.", "contexts": [{"lineNo": 8, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "log"}}]}} {"id": "73f88ff811c75b8ff0f847d24bcd485cb03612a5405c77ddef52ef925031f930", "license": {"spdx": ["Apache-2.0"], "repo": "nalancer08/Dipper", "path": "edited/framework/server.js", "repo_head_hexsha": "a0020536a31ebac9a97ed4ffd977de6de57c6b6d", "stack_hexsha": "c991d1d47f7dfb35b160e9001d81afa5fbc63835", "match": "repo_path"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Log injection", "issueDescriptionEn": "The Log injection checker finds instances of printing out unvalidated user inputs in a log.\nIf unvalidated user inputs are printed out in a log, an attacker can insert arbitrary content in the log to confuse security personnel who consult the log. If a manipulated log successfully leads to making an inappropriate decision, the attacker can exploit the consequences.\nHave external inputs validated before they are logged. It is particularly recommended to delete newline characters.", "issueLineNumber": 73, "entireCode": "/**\n\tVersion 3.5\n\tCreated by: biohzrd \n\tRevised by: nalancer08 \n\tLast revision: 25/07/2017\n**/\n\nvar _ = require('underscore');\nvar http = require('http');\nvar https = require('https');\nvar url = require('url') ;\nvar crypto = require('crypto');\nvar fs = require('fs');\nvar nunjucks = require('nunjucks');\nvar path = require('path');\n\nvar Request = require('./request.js');\nvar Response = require('./response.js');\nvar Router = require('./router.js');\nvar Database = require('./database.js');\nvar Dipper = require('./dipper.js');\nvar Functions = require('../external/functions.js');\n\nfunction Server(options) {\n\n\tthis.http = null;\n\tthis.verbose = true;\n\tthis.router = null;\n\tthis.functions = null;\n\tthis.dipper = null;\n\tthis.dbh = null;\n\t// Call initialization callback\n\tthis.init(options);\n}\n\nServer.prototype.init = function(options) {\n\n\tvar obj = this,\n\t\tsettings = options.settings,\n\t\topts = settings[options.profile] || {},\n\t\tshared = settings['shared'] || {},\n\t\tsecurity = settings['security'] || {};\n\n\t_.defaults(opts, {\n\t\tbase_url: '',\n\t\tsite_url: '',\n\t\twsServer: false,\n\t\tonNotFound: obj.onNotFound\n\t});\n\tobj.options = opts;\n\n\t_.defaults(security, {\n\t\tpass_salt: '',\n\t\ttoken_salt: '',\n\t\tversion: '1.0'\n\t});\n\tobj.security = security;\n\n\t// Render\n\tglobal.render = nunjucks.configure(path.join(process.cwd(), 'assets'), { autoescape: false, noCache: true, async : true });\n\n\t// Setting Dipper instance\n\tglobal.dipper = new Dipper(opts, shared);\n\n\t// Cheking for http or https\n\tif (/^((http):\\/\\/)/.test(obj.options.site_url) || /^((localhost))/.test(obj.options.site_url)) {\n\n\t\t// Create the base HTTP server and bind the request handler\n\t\tobj.httpx = http.createServer(function(req, res) {\n\n\t\t\tvar hostname = req.headers.host; // hostname = 'localhost:8080'\n\t \t\tvar pathname = url.parse(req.url).pathname; // pathname = '/MyApp'\n\t \t\tconsole.log('http://' + hostname + pathname);\n\t\t\tobj.router.onRequest.call(obj.router, req, res);\n\t\t});\n\t} else if (/^((https):\\/\\/)/.test(obj.options.site_url)) {\n\n\t\t// Setting options for https server\n\t\tcerts = {\n\t\t\tkey: fs.readFileSync('./external/certs/' + obj.security.key),\n\t\t\tcert: fs.readFileSync('./external/certs/' + obj.security.cert)\n\t\t};\n\n\t\t// Creating HTTPS server\n\t\tobj.httpx = https.createServer(certs, (req, res) => {\n\t\t\tvar hostname = req.headers.host; // hostname = 'localhost:8080'\n\t \t\tvar pathname = url.parse(req.url).pathname; // pathname = '/MyApp'\n\t \t\tconsole.log('https://' + hostname + pathname);\n\t\t\tobj.router.onRequest.call(obj.router, req, res);\n\t\t});\n\t}\n\n\tobj.onNotFound = opts.onNotFound;\n\n\t// Initialize router\n\tobj.router = new Router(obj);\n\n\t// Initialize database\n\tobj.dbh = new Database(obj.options['database']);\n\n\t// Setting endpoints\n\tobj.functions = new Functions(obj);\n}\n\nServer.prototype.start = function() {\n\n\tvar obj = this;\n\tvar port = (obj.options.port && obj.options.port != '') ? obj.options.port : 8080;\n\n\t// Listen on the specified port\n\tobj.httpx.listen(port);\n\n\t// Logging\n\tobj.log('__________________ Dragonfly server started ___________________');\n\tobj.log(' > Listening on ' + obj.options.site_url + ':' + obj.options.port + obj.options.base_url + ' < ');\n\tobj.log('-----------------------------------------------------------------');\n}\n\nServer.prototype.log = function(value) {\n\n\tvar obj = this;\n\tif (obj.verbose) {\n\t\tconsole.log(value);\n\t}\n}\n\nServer.prototype.onNotFound = function(request, response) {\n\n\tresponse.setStatus(404);\n\tresponse.respond(); // response.res.end();\n\t//return true;\n}\n\nServer.prototype.hashToken = function(value) {\n\n\tvar obj = this,\n\t\tsecurity = obj.security;\n\n\treturn crypto.createHash('md5').update(security.token_salt + value).digest('hex');\n}\n\nServer.prototype.shaToken = function(value) {\n\n\tvar obj = this,\n\t\tsecurity = obj.security;\n\n\treturn crypto.createHash('sha512').update(security.token_salt + value).digest('hex');\n}\n\nServer.prototype.hashPassword = function(value) {\n\n\tvar obj = this,\n\t\tsecurity = obj.security;\n\n\treturn crypto.createHash('md5').update(security.pass_salt + value).digest('hex');\n}\n\nServer.prototype.shaPassword = function(value) {\n\n\tvar obj = this,\n\t\tsecurity = obj.security;\n\n\treturn crypto.createHash('sha512').update(security.pass_salt + value).digest('hex');\n}\n\nServer.prototype.validateToken = function(token, value) {\n\n\tvar obj = this,\n\t\tsecurity = obj.security,\n\t\tcheck = obj.hashToken(value);\n\t\t\t\n\treturn (token == check);\n}\n\nServer.prototype.validateShaToken = function(token, value) {\n\n\tvar obj = this,\n\t\tsecurity = obj.security,\n\t\tcheck = obj.shaToken(value);\n\n\treturn (token == check);\n}\n\nServer.prototype.getDbh = function() {\n\n\tvar obj = this;\n\tif (obj.dbh != null) {\n\n\t\treturn new Promise(function(resolve, reject) {\n\t\t\tobj.dbh.dbh.getConnection(function(err, connection) {\n\n\t\t\t\tif (err) {\n\t\t\t\t\treject(Error('No connection'));\n\t\t\t\t} else if (connection) {\n\t\t\t\t\tresolve(connection);\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\n\t}\n}\n\nServer.prototype.getPoolDbh = function() {\n\n\tvar obj = this;\n\tif (obj.dbh != null && obj.dbh.connection != undefined) {\n\t\treturn obj.dbh.connection;\n\t}\n}\n\nmodule.exports = Server;", "dangerousExampleEn": "1. //in node.js\n2. app.post('/test', function(req, res) {\n3. console.log(req.query.url);\n4. });\nLine 3: An unvalidated external input is printed out to a log.", "safeExampleEn": "1. ...\nLine 3: Filter out the external input.", "contexts": [{"lineNo": 73, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "log"}}]}} {"id": "e1694952b128d0cedab883f192a35f71d01312782c9b6a611bc07b50e43f2c9a", "license": {"spdx": ["MIT"], "repo": "mpkluft/SkillBranch", "path": "src/lesson2/task2x.js", "repo_head_hexsha": "7a7b0602f925cd65ff537172cf9802eb99727462", "stack_hexsha": "3a7490bbd10880ca7b36bb617f657e0a76268966", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Log injection", "issueDescriptionEn": "The Log injection checker finds instances of printing out unvalidated user inputs in a log.\nIf unvalidated user inputs are printed out in a log, an attacker can insert arbitrary content in the log to confuse security personnel who consult the log. If a manipulated log successfully leads to making an inappropriate decision, the attacker can exploit the consequences.\nHave external inputs validated before they are logged. It is particularly recommended to delete newline characters.", "issueLineNumber": 25, "entireCode": "//внешние библиотеки\nimport express from 'express';\nimport cors from 'cors';\nimport fetch from 'isomorphic-fetch';\nimport Promise from 'bluebird';\nimport _ from 'lodash';\nimport bodyParser from 'body-parser';\nimport mongoose from 'mongoose';\nconst { Schema } = mongoose;\n\n\n\n\n\nconst app = express();\napp.use(bodyParser.json());\napp.use(cors());\n\n\n\napp.get('/task2x', (req, res) => {\n let result;\n\n console.log(req.query);\n console.log(req.url);\n\n switch(req.query.i){\n case '0': {\n result = '1';\n break;\n }\n case '1': {\n result = '18';\n break;\n }\n case '2': {\n result = '243';\n break;\n }\n case '3': {\n result = '3240';\n break;\n }\n case '4': {\n result = '43254';\n break;\n }\n case '5': {\n result = '577368';\n break;\n }\n case '6': {\n result = '7706988';\n break;\n }\n case '7': {\n result = '102876480';\n break;\n }\n case '8': {\n result = '1373243544';\n break;\n }\n case '9': {\n result = '18330699168';\n break;\n }\n case '10': {\n result = '244686773808';\n break;\n }\n case '11': {\n result = '3266193870720';\n break;\n }\n case '12': {\n result = '43598688377184';\n break;\n }\n case '13': {\n result = '581975750199168';\n break;\n }\n case '14': {\n result = '7768485393179328';\n break;\n } \n case '15': {\n result = '103697388221736960';\n break;\n }\n case '16': {\n result = '1384201395738071424';\n break;\n }\n case '17': {\n result = '18476969736848122368';\n break;\n } \n case '18': {\n result = '246639261965462754048';\n break;\n } \n\n }\n\n \n\n res.send(result);\n\n});\n\n\n\n\n//--------------------------------------------------\n//слушаем порт 3000\napp.listen(3000, () => {\n console.log('Your app listening on port 3000');\n});\n\n/*\nКраткое описание задачи\n\nВоссоздать черный ящик\nПолное описание задачи\n\nBlackbox - Черный ящик. На практике во время реального решения задач вам скорее всего придется столкнутся с решением задач связанных с черным ящиком.\n\n Чёрный я́щик — термин, используемый для обозначения системы, внутреннее устройство и механизм работы которой очень сложны, неизвестны или неважны в рамках данной задачи.\n\n «Метод чёрного ящика» — метод исследования таких систем, когда вместо свойств и взаимосвязей составных частей системы, изучается реакция системы, как целого, на изменяющиеся условия.\n\nЧерный ящик\n\nПредположим, что есть сервис, на вход которому приходит целое число от 0 до 18, этот сервис производит какие-то расчеты, и в ответ возвращет другое число.\n\nСервис с закрытым кодом, аглоритм работы вы не знаете, вычисления производит долго.\n\nВаша задача сделать копию этого, сервиса.\nПримеры\n\nПример 1\n\n?i=0\n-\n1\n\nПример 2\n\n?i=1\n-\n18\n\n\n*/", "dangerousExampleEn": "1. //in node.js\n2. app.post('/test', function(req, res) {\n3. console.log(req.query.url);\n4. });\nLine 3: An unvalidated external input is printed out to a log.", "safeExampleEn": "1. ...\nLine 3: Filter out the external input.", "contexts": [{"lineNo": 25, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "log"}}]}} {"id": "af4cf87dd654d98fc5209789617ee0658b219ec600cddb31dccae03eaa1a5aea", "license": {"spdx": ["MIT"], "repo": "makeitrealcamp/top-v11", "path": "workshops/1-node-intro/server.js", "repo_head_hexsha": "17fb6aaf882a04f485fc5677af0c8dd7f9986daf", "stack_hexsha": "ee93101db1261d2ee0aa03c8bcb5f4295991f801", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Log injection", "issueDescriptionEn": "The Log injection checker finds instances of printing out unvalidated user inputs in a log.\nIf unvalidated user inputs are printed out in a log, an attacker can insert arbitrary content in the log to confuse security personnel who consult the log. If a manipulated log successfully leads to making an inappropriate decision, the attacker can exploit the consequences.\nHave external inputs validated before they are logged. It is particularly recommended to delete newline characters.", "issueLineNumber": 8, "entireCode": "const http = require('http');\nconst url = require('url');\n\nconst PORT = 4200;\n\nmakeServer = (request, response) => {\n let path = url.parse(request.url).pathname;\n console.log(path);\n if (path === '/') {\n response.writeHead(200, {'Content-Type': 'text/plain'});\n response.write(`Hello Topv11!`);\n } else if (path === '/about') {\n response.writeHead(200, {'Content-Type': 'text/plain'});\n response.write('Know more about us!');\n } else if (path === '/blog') {\n response.writeHead(200, {'Content-Type': 'text/plain'});\n response.write('Read our blog posts!');\n } else if (path === '/contact') {\n response.writeHead(200, {'Content-Type': 'text/plain'});\n response.write('Get in touch with us!');\n } else {\n response.writeHead(404, {'Content-Type': 'text/plain'});\n response.write('Not Found');\n }\n response.end();\n};\n \nconst server = http.createServer(makeServer);\n \nserver.listen(PORT, () => {\n console.log(`Basic node server running on port ${PORT}`);\n});", "dangerousExampleEn": "1. //in node.js\n2. app.post('/test', function(req, res) {\n3. console.log(req.query.url);\n4. });\nLine 3: An unvalidated external input is printed out to a log.", "safeExampleEn": "1. ...\nLine 3: Filter out the external input.", "contexts": [{"lineNo": 8, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "log"}}]}} {"id": "1730b6984974c52d516fbf26d0a23d2643eede6883e8fdd29bb7f01e16355da0", "license": {"spdx": ["MIT"], "repo": "juanpex/paymentjs-integration-nodejs", "path": "server.js", "repo_head_hexsha": "e277490b64a30c51064122ac324cb712dcfbdf07", "stack_hexsha": "8595efca35ab6b3b3abdf15fc4abea415e2480b1", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Log injection", "issueDescriptionEn": "The Log injection checker finds instances of printing out unvalidated user inputs in a log.\nIf unvalidated user inputs are printed out in a log, an attacker can insert arbitrary content in the log to confuse security personnel who consult the log. If a manipulated log successfully leads to making an inappropriate decision, the attacker can exploit the consequences.\nHave external inputs validated before they are logged. It is particularly recommended to delete newline characters.", "issueLineNumber": 203, "entireCode": "const crypto = require('crypto');\nconst https = require('https');\nconst http = require('http');\nconst fs = require('fs');\nconst path = require('path');\nconst PaymentJsConfig = require('./paymentjs.config');\n\nconst sendResponse = (response, status, headers, data) => {\n response.writeHead(status, headers);\n if (data) {\n response.end(data, 'utf-8');\n }\n console.log('[info] [server] sent response with status ' + status);\n};\n\nconst authorizeSession = (config, nonce, callback) => {\n const timestamp = new Date().getTime()\n\n const requestBody = JSON.stringify(config.gatewayConfig);\n\n const msgToSign = [\n config.credentials.apiKey,\n nonce,\n timestamp,\n requestBody,\n ].join('');\n\n const msgSignature = crypto\n .createHmac(\"sha256\", config.credentials.apiSecret)\n .update(msgToSign)\n .digest(\"base64\");\n\n const requestOptions = {\n hostname: config.hostname,\n port: 443,\n path: '/paymentjs/v2/merchant/authorize-session',\n method: 'POST',\n headers: {\n 'Api-Key': config.credentials.apiKey,\n 'Content-Type': 'application/json',\n 'Content-Length': requestBody.length,\n 'Message-Signature': msgSignature,\n 'Nonce': nonce,\n 'Timestamp': timestamp,\n }\n };\n\n console.log('[info] [authorizeSession] sending request');\n const request = https.request(requestOptions, (response) => {\n console.log('[info] [authorizeSession] received response with status ' + response.statusCode);\n if (response.statusCode === 200) {\n const responseNonce = response.headers['nonce'];\n\n // nonce should match what we used to authorize the session\n if (responseNonce === nonce) {\n\n // read response body\n response.setEncoding('utf8');\n response.on('data', (bodyStr) => {\n const clientToken = response.headers['client-token'];\n const publicKeyBase64 = JSON.parse(bodyStr).publicKeyBase64;\n callback(undefined, { clientToken, publicKeyBase64 });\n });\n response.on('error', (e) => {\n callback(e, undefined);\n });\n\n } else {\n // the nonce did not match\n callback(new Error('nonce validation failed for nonce \"' + nonce + '\"'));\n }\n } else {\n // unsuccessful or otherwise unexpected response status code\n callback(new Error('received HTTP ' + response.statusCode), undefined);\n };\n });\n\n // write the payload to the request object\n request.write(requestBody);\n request.end();\n};\n\nconst nonceCache = new Map();\n\nconst readFiles = (filePaths) => {\n const files = new Map();\n for (let i = 0; i < filePaths.length; i++) {\n files.set(filePaths[i], fs.readFileSync(filePaths[i], 'utf8'));\n }\n return files;\n};\n\n\nconst FileName = {\n JS: './client.js',\n HTML: './index.html',\n CSS: './styles.css',\n};\n\nconst Mime = {\n CSS: 'text/css',\n HTML: 'text/html',\n JS: 'text/javascript',\n};\n\nconst fileCache = readFiles([\n FileName.HTML,\n FileName.CSS,\n FileName.JS,\n]);\n\nconst sendFile = (response, filePath, contentType) => {\n if (!fileCache.has(filePath)) {\n sendResponse(response, 500);\n return;\n }\n\n sendResponse(response, 200, { 'Content-Type': contentType }, fileCache.get(filePath));\n};\n\nconst routes = {\n '/client.js': {\n GET: (request, response) => sendFile(response, FileName.JS, Mime.JS),\n },\n\n '/styles.css': {\n GET: (request, response) => sendFile(response, FileName.CSS, Mime.CSS),\n },\n\n '/': {\n GET: (request, response) => sendFile(response, FileName.HTML, Mime.HTML),\n },\n\n '/api/authorize-session': {\n POST: (request, response) => {\n const nonce = `${(new Date().getTime() + Math.random())}`;\n authorizeSession(PaymentJsConfig, nonce, (error, data) => {\n if (error) {\n sendResponse(response, 500);\n console.error('[error] [authorizeSession] ' + error.message);\n return;\n }\n\n nonceCache.set(data.clientToken, nonce);\n sendResponse(response, 200, { 'Content-Type': 'application/json' }, JSON.stringify(data));\n });\n },\n },\n\n '/api/webhook': {\n POST: (request, response) => {\n const clientToken = request.headers['client-token'];\n const nonce = request.headers['nonce'];\n\n const isNonceStored = nonceCache.has(clientToken);\n let requestNonce = '';\n if (isNonceStored) {\n requestNonce = nonceCache.get(clientToken);\n nonceCache.delete(clientToken);\n }\n\n const nonceValidated = isNonceStored && requestNonce === responseNonce;\n\n if (!nonceValidated) {\n sendResponse(response, 401);\n\n console.error(`[error] [webhook] clientToken/nonce validation failed`);\n return;\n }\n\n let bodyStr = '';\n\n request.on('data', (chunk) => {\n bodyStr += chunk.toString();\n });\n\n request.on('end', () => {\n tokenizeData = JSON.parse(bodyStr);\n\n sendResponse(response, 200);\n\n console.log('[info] [webhook] success\\n' + JSON.stringify({\n clientToken,\n nonce: requestNonce,\n body: tokenizeData,\n }, null, 2));\n });\n },\n },\n};\n\nconst port = 3000;\n\nhttp.createServer((request, response) => {\n const method = request.method;\n const route = request.url;\n\n if (!routes[route] || !routes[route][method]) {\n sendResponse(response, 404);\n return;\n }\n\n console.log('[info] [server] received request ' + method + ':' + route);\n\n try {\n routes[route][method](request, response);\n } catch (error) {\n sendResponse(response, 500);\n console.error(\"[fatal] [server] \" + error.message);\n }\n}).listen(port);\n\nconsole.log('[info] [server] listening on port ' + port);", "dangerousExampleEn": "1. //in node.js\n2. app.post('/test', function(req, res) {\n3. console.log(req.query.url);\n4. });\nLine 3: An unvalidated external input is printed out to a log.", "safeExampleEn": "1. ...\nLine 3: Filter out the external input.", "contexts": [{"lineNo": 203, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "log"}}]}} {"id": "f6361337e98d64ccddc2479134ea44bd094451e0ee3d2612aa297e6bc2970c26", "license": {"spdx": ["MIT"], "repo": "seattleacademy/30winter", "path": "apps/drone/droneserver.js", "repo_head_hexsha": "f9381703f22772aa2764cacb9a8154b6d02c1349", "stack_hexsha": "8994edab0eb4b374484b0d2c7360cddcfe0cbf9a", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Log injection", "issueDescriptionEn": "The Log injection checker finds instances of printing out unvalidated user inputs in a log.\nIf unvalidated user inputs are printed out in a log, an attacker can insert arbitrary content in the log to confuse security personnel who consult the log. If a manipulated log successfully leads to making an inappropriate decision, the attacker can exploit the consequences.\nHave external inputs validated before they are logged. It is particularly recommended to delete newline characters.", "issueLineNumber": 5, "entireCode": "var http = require('http');\nport = 1535;\nconsole.log(\"listening on port \", port)\nhttp.createServer(function(req, res) {\n console.dir(req.url);\n\n res.writeHead(200, { 'Content-Type': 'text/html' });\n\n res.end('ok ' + req.url);\n}).listen(1535);", "dangerousExampleEn": "1. //in node.js\n2. app.post('/test', function(req, res) {\n3. console.log(req.query.url);\n4. });\nLine 3: An unvalidated external input is printed out to a log.", "safeExampleEn": "1. ...\nLine 3: Filter out the external input.", "contexts": [{"lineNo": 5, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "dir"}}]}} {"id": "fcdf230d0aeba528ccd86b6fc6ef3233d0fb1bba47181a403bd53ec86d128db7", "license": {"spdx": ["Apache-2.0"], "repo": "garyhu1/node", "path": "http/testserver.js", "repo_head_hexsha": "263863a4e0d8c91009f0e157d38d3a25aea066b9", "stack_hexsha": "5259a12af97e1bba16623a1935675b62ad7ee294", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Log injection", "issueDescriptionEn": "The Log injection checker finds instances of printing out unvalidated user inputs in a log.\nIf unvalidated user inputs are printed out in a log, an attacker can insert arbitrary content in the log to confuse security personnel who consult the log. If a manipulated log successfully leads to making an inappropriate decision, the attacker can exploit the consequences.\nHave external inputs validated before they are logged. It is particularly recommended to delete newline characters.", "issueLineNumber": 36, "entireCode": "// var url = require(\"url\");\n\n// console.log(url.parse('http://www.baidu.com'));\n/**\n * 输出结果为:\n * Url {\n * protocol: 'http:',\n * slashes: true,\n * auth: 'user:pass',\n * host: 'host.com:8080',\n * port: '8080',\n * hostname: 'host.com',\n * hash: '#hash',\n * search: '?query=string',\n * query: 'query=string',\n * pathname: '/path/to/file',\n * path: '/path/to/file?query=string',\n * href: 'http://user:pass@host.com:8080/path/to/file?query=string#hash' }\n */\n\nvar http = require(\"http\");\nvar url = require(\"url\");\nvar fs = require(\"fs\");\n\nvar path = require(\"path\");\n//获取当前目录\n// var workDir = path.resolve(\".\");\n//获取当前目录\nvar workDir = path.resolve(process.argv[2]||\".\");\nconsole.log(workDir);\nvar server = http.createServer(function(request,response){\n var pathname = url.parse(request.url).pathname;\n var file = path.join(workDir,pathname);\n fs.stat(file,function(err,stat){\n if(err){\n console.log(\"404\"+ request.url);\n response.writeHead(404);\n response.write(\"404 Not Found\");\n response.end();\n }else if(stat.isDirectory()){\n fs.readdir(file,function(err,files){\n if(err){\n return console.error(err);\n }else{\n files.forEach(function(f) {\n if(f===\"index.html\"){\n console.log(\"200\"+request.url);\n response.writeHead(200);\n fs.createReadStream(f).pipe(response);\n }\n });\n }\n });\n }else if(stat.isFile()){\n console.log(\"200\"+request.url);\n response.writeHead(200);\n fs.createReadStream(file).pipe(response);\n }\n });\n});\nserver.listen(8080);\nconsole.log('Server is running at http://127.0.0.1:8080/');", "dangerousExampleEn": "1. //in node.js\n2. app.post('/test', function(req, res) {\n3. console.log(req.query.url);\n4. });\nLine 3: An unvalidated external input is printed out to a log.", "safeExampleEn": "1. ...\nLine 3: Filter out the external input.", "contexts": [{"lineNo": 35, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "35"}}, {"lineNo": 36, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "log"}}]}} {"id": "2b1066942da62043d315fa5e39f551980f0ad3bec23d40fdfa3fb4df4ea89dae", "license": {"spdx": ["MIT"], "repo": "Adalab/modulo-2-evaluacion-final-PaulaPSoto", "path": "src/js/main.js", "repo_head_hexsha": "bdf0579aa0775ace5f311f69d56ec52440bde8ff", "stack_hexsha": "5e6006ab249036bb54900bdfcc5a1676d376e592", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Cross-site scripting", "issueDescriptionEn": "The Cross-site scripting checker finds instances in which unvalidated data is sent to a web browser.\nlocalStorage can be manipulated by other applications. Therefore, if unvalidated data of localStorage is allowed for page generation, attackers can inject malicious scripts into pages.\nThis vulnerability lets attackers take over a user's cookie, session, or other information or execute an abnormal function. You can optionally specify functions that perform the respective roles of receiving, using, warning of, and filtering external inputs.\nMake sure that data is filtered if needed.", "issueLineNumber": 73, "entireCode": "/* eslint-disable quotes */\n/* eslint-disable no-console */\n/* eslint-disable indent */\n'use strict';\n\nconst showList = document.querySelector(\".showlist\");\nconst searchButton = document.querySelector(\".js-button\");\nconst showfav = document.querySelector(\".showfav\");\n\n\nlet allShow = [];\nlet favoriteShow = [];\n\n//Función para coger del Api\nfunction getDataApi() {\n const nameShowInput = document.querySelector(\".js-input\");\n const inputWord = nameShowInput.value;\n fetch(\"http://api.tvmaze.com/search/shows?q=\"+inputWord)\n .then( response => response.json())\n .then(data =>{\n allShow = data;\n renderShow();\n });\n}\n//Para recorrer el array de allShow y añadirle el html\nfunction renderShow(){\n let htmlShowList = \"\";\n let myimage = \"\";\n for (let index = 0; index < allShow.length; index++) {\n htmlShowList += \"
  • \";\n if (allShow[index].show.image !== null) {\n myimage = allShow[index].show.image.medium;\n } else{\n myimage = \"./assets/images/photodefault.png\";\n }\n htmlShowList += `\"Imagen`;\n htmlShowList += allShow[index].show.name;\n htmlShowList+= \"
  • \";\n }\n showList.innerHTML = htmlShowList;\n\n\n //fav\n const getLis = document.querySelectorAll(\".item\");\n //a cada li le añadimos un evento\n for (const getli of getLis) {\n getli.addEventListener('click', handleFav);\n console.log(getLis.length);\n }\n}\n\n//el evento debe ir completando mi array de favoritos\nfunction handleFav(ev) {\n const livalue = ev.target.innerHTML;\n favoriteShow.push(livalue);\n renderFav();\n}\n\nfunction renderFav() {\n let html =\"\";\n for (let index = 0; index < favoriteShow.length; index++) {\n html += \"
  • \";\n html += favoriteShow[index];\n html += \"
  • \";\n }\n showfav.innerHTML = html;\n setLocalStorarage(html);\n}\n\n//me traigo lo que me guarda y se lo añado a la ul\nfunction renderFavlocal() {\n let favoriteLocal = getLocalStorage();\n showfav.innerHTML = favoriteLocal;\n}\n\n//local Storage coger lo guardado y pasarlo a JSON//\nfunction getLocalStorage(){\n const favLocal = JSON.parse(localStorage.getItem(\"favorite\"));\n return favLocal;\n}\n//local Storage guardarlo y convertirlo en cadena\nfunction setLocalStorarage(html){\n localStorage.setItem (\"favorite\",JSON.stringify(html));\n}\n\nsearchButton.addEventListener(\"click\",getDataApi);\nrenderFavlocal();\n", "dangerousExampleEn": "1. var danger = localStorage.getItem(\"some\");\n2. \n3. eval(danger);\nLine 2: Unvalidated data is sent to a web browser.", "safeExampleEn": "1. var danger = localStorage.getItem(\"some\");\n2. var safe = filter(danger);\n3. eval(safe);\nLine 2: Filter the data, and then, send it to the browser.", "contexts": [{"lineNo": 73, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "="}}]}} {"id": "448eabf16567859ce0807aee5b0eafcd56f39440dbc120dbe5a578e9eeeb8c33", "license": {"spdx": ["MIT"], "repo": "LucasGaldinno/quiz-lima", "path": "assets/js/ranking.js", "repo_head_hexsha": "3e4de1a75b8ab9d06db816a4419a6897071a4d3a", "stack_hexsha": "c70e079338217e79c95afe74dd8c12db5269828c", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Cross-site scripting", "issueDescriptionEn": "The Cross-site scripting checker finds instances in which unvalidated data is sent to a web browser.\nlocalStorage can be manipulated by other applications. Therefore, if unvalidated data of localStorage is allowed for page generation, attackers can inject malicious scripts into pages.\nThis vulnerability lets attackers take over a user's cookie, session, or other information or execute an abnormal function. You can optionally specify functions that perform the respective roles of receiving, using, warning of, and filtering external inputs.\nMake sure that data is filtered if needed.", "issueLineNumber": 6, "entireCode": "function loadRecord() {\n let campoRecord = document.getElementById(\"record\")\n campoRecord.innerHTML = ''\n if (localStorage.getItem(\"record\") != null &&\n localStorage.getItem(\"record\") != undefined) {\n campoRecord.innerHTML = `${localStorage.getItem(\"record\")}`\n }\n}\n\nfunction saveRecord() {\n let nome = prompt(\"Digite seu Nome:\");\n console.log(nome);\n localStorage.setItem(\"record\", pontuacaoAtual)\n loadRecord()\n}\n\nloadRecord()", "dangerousExampleEn": "1. var danger = localStorage.getItem(\"some\");\n2. \n3. eval(danger);\nLine 2: Unvalidated data is sent to a web browser.", "safeExampleEn": "1. var danger = localStorage.getItem(\"some\");\n2. var safe = filter(danger);\n3. eval(safe);\nLine 2: Filter the data, and then, send it to the browser.", "contexts": [{"lineNo": 4, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "5"}}, {"lineNo": 6, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "getItem"}}, {"lineNo": 6, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "="}}]}} {"id": "dfc1f02d28051bae1b0206efe9c08a83be6022821fc4857fc02bbf33bc2d8e6f", "license": {"spdx": ["MIT"], "repo": "Adalab/modulo-2-evaluacion-final-JuditAldeguer", "path": "src/js/main.js", "repo_head_hexsha": "3a255cb6a515beb80926e4225a4eb6a722082518", "stack_hexsha": "ec718d9b493fcae46adacbecd5c81e04aab8a8fc", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Cross-site scripting", "issueDescriptionEn": "The Cross-site scripting checker finds instances in which unvalidated data is sent to a web browser.\nlocalStorage can be manipulated by other applications. Therefore, if unvalidated data of localStorage is allowed for page generation, attackers can inject malicious scripts into pages.\nThis vulnerability lets attackers take over a user's cookie, session, or other information or execute an abnormal function. You can optionally specify functions that perform the respective roles of receiving, using, warning of, and filtering external inputs.\nMake sure that data is filtered if needed.", "issueLineNumber": 96, "entireCode": "'use strict';\n\n//VARIABLES---------------------------------------------------------------------------------------\n//filter\nconst input = document.querySelector('.js_input');\nconst searchBtn = document.querySelector('.js_search_btn');\n//favorites\nconst favoritesResults = document.querySelector('.js_results_favorites');\nconst resetBtn = document.querySelector('.js_reset_btn');\n//results\nconst resultsSection = document.querySelector('.js_results');\n//global arrays / variables\nlet favorites = [];\nlet series = [];\nlet classFav;\nlet serieImage;\nlet favoriteImage;\nlet languages = ['English', 'Spanish', 'Portuguese'];\n\n//FUNCTIONS---------------------------------------------------------------------------------------\n//requests to the server API\nfunction getFromAPI() {\n let url;\n if (input.value === '') {\n url = '//api.tvmaze.com/shows?page=1';\n } else {\n url = `//api.tvmaze.com/search/shows?q=${input.value}`;\n }\n fetch(url)\n .then((response) => {\n if (!response.ok) {\n throw response;\n } else {\n return response.json();\n }\n })\n .then((all) => arrayConverter(all))\n .then(() => paintSeries())\n .catch((err) => console.error(err));\n}\n//function conver array from API\nfunction arrayConverter(all) {\n let object;\n if (all.length > 10) {\n const newAll = all.slice(0, 11);\n series = newAll.map((serieEl) => {\n object = {\n name: serieEl.name,\n id: serieEl.id,\n image: serieEl.image,\n language: serieEl.language,\n };\n return object;\n });\n } else {\n series = all.map((serieEl) => {\n object = {\n name: serieEl.show.name,\n id: serieEl.show.id,\n image: serieEl.show.image,\n language: serieEl.show.language,\n };\n return object;\n });\n }\n setInLocalStorage();\n}\n//set in LocalStorage\nfunction setInLocalStorage() {\n if (input.value !== '') {\n const stringSeries = JSON.stringify(series);\n localStorage.setItem(`series${input.value}`, stringSeries);\n }\n const stringFavorites = JSON.stringify(favorites);\n localStorage.setItem('fav', stringFavorites);\n}\n//LocalStorage CONTROL\nfunction controlLocalStorage() {\n const localStorageSeries = localStorage.getItem(`series${input.value}`);\n const storagedSeries = JSON.parse(localStorageSeries);\n if (storagedSeries !== null) {\n series = storagedSeries;\n } else {\n getFromAPI();\n }\n paintSeries();\n favoritesControl();\n}\n//control Favorites\nfunction favoritesControl() {\n const localStorageFavorites = localStorage.getItem('fav');\n if (localStorageFavorites !== null) {\n const StoragedFavorites = JSON.parse(localStorageFavorites);\n favorites = StoragedFavorites;\n }\n paintFavorites();\n}\n//FAVORITES----------------\n//handleFavorite\nfunction handleFavorite(ev) {\n const selectedSerie = parseInt(ev.currentTarget.id);\n const selectedSerieHTML = ev.currentTarget;\n const seriesHTML = document.querySelectorAll('.series--container');\n for (const serie of series) {\n classFav;\n if (serie.id === selectedSerie) {\n classFav = 'series--favorite';\n arrayFavUpdate(selectedSerie);\n for (const serieHtml of seriesHTML) {\n if (serieHtml.innerHTML === selectedSerieHTML.innerHTML) {\n serieHtml.classList.toggle(classFav);\n }\n }\n } else {\n classFav = '';\n }\n }\n paintFavorites();\n}\n\n//update Favorites array\nfunction arrayFavUpdate(selectedSerie) {\n const objetClicked = series.find((serie) => {\n return serie.id === selectedSerie;\n });\n const favoritesFound = favorites.findIndex((fav) => {\n return fav.id === selectedSerie;\n });\n if (favoritesFound === -1) {\n favorites.push(objetClicked);\n } else {\n favorites.splice(favoritesFound, 1);\n }\n}\n//PaintFavorites\nfunction paintFavorites() {\n let favHtml = '';\n if (favorites.length !== 0) {\n for (const favorite of favorites) {\n const isRecomended = languageRecomenderFav(favorite);\n getImageUrlFav(favorite);\n favHtml += `\n
  • \n \n
    \n \"${favorite.name}\"\n

    ${favorite.name}

    \n Language: ${favorite.language}. ${isRecomended}\n
    \n
  • `;\n }\n }\n favoritesResults.innerHTML = favHtml;\n setInLocalStorage();\n xBtnfavListener();\n const numFavText = document.querySelector('.js_num_fav_text');\n numFavText.innerHTML = `Tienes ${favorites.length} series marcadas como favoritas`;\n}\n//isFavorite\nfunction isFavorite(serie) {\n if (favorites.length !== 0) {\n const found = favorites.findIndex((favorite) => favorite.id === serie.id);\n if (found !== -1) {\n classFav = 'series--favorite';\n } else {\n classFav = '';\n }\n }\n}\n//get Fav image url\nfunction getImageUrlFav(favorite) {\n if (favorite.image === null) {\n favoriteImage = `https://via.placeholder.com/210x295/7C7E29/ffff/?text=${favorite.name}`;\n } else {\n favoriteImage = favorite.image.medium;\n }\n}\n\n// fav recomendation language\nfunction languageRecomenderFav(favorite) {\n let isRecomended;\n const findRecomend = languages.find((lang) => favorite.language === lang);\n if (findRecomend) {\n isRecomended = 'Serie recomendada';\n } else {\n isRecomended = '';\n }\n return isRecomended;\n}\n//Fav reset\nfunction handleResetFavorites(ev) {\n ev.preventDefault();\n favorites = [];\n localStorage.removeItem('fav');\n paintFavorites();\n paintSeries();\n}\n//Fav Button X\nfunction handleXButtonFavorites(ev) {\n ev.preventDefault();\n const selectedXButton = ev.currentTarget;\n const selectedFavorite = parseInt(selectedXButton.parentElement.id);\n const favoritesFound = favorites.findIndex((fav) => {\n return fav.id === selectedFavorite;\n });\n if (favoritesFound !== -1) {\n favorites.splice(favoritesFound, 1);\n }\n paintFavorites();\n paintSeries();\n}\n\n//SERIES------------\n//get image url\nfunction getImageUrl(serie) {\n if (serie.image === null) {\n serieImage = `https://via.placeholder.com/210x295/7C7E29/ffff/?text=${serie.name}`;\n } else {\n serieImage = serie.image.medium;\n }\n}\n//recomendation language\nfunction languageRecomender(serie) {\n let isRecomended;\n const findRecomend = languages.find((lang) => serie.language === lang);\n if (findRecomend) {\n isRecomended = 'Serie recomendada';\n } else {\n isRecomended = '';\n }\n return isRecomended;\n}\n//paint series\nfunction paintSeries() {\n let htmlText = '

    Search result

    ';\n for (const serie of series) {\n getImageUrl(serie);\n isFavorite(serie);\n const isRecomended = languageRecomender(serie);\n htmlText += `\n
    \n \"${serie.name}\"\n

    ${serie.name}

    \n Language: ${serie.language}. ${isRecomended}\n
    `;\n }\n resultsSection.innerHTML = htmlText;\n favListener();\n}\n//for search buton Event\nfunction handleGetSeries(ev) {\n ev.preventDefault();\n controlLocalStorage();\n}\n//Initial functions used on loading webpage ------------------------------------------------------\nwindow.addEventListener('load', favoritesControl);\n\n//LISTENERS---------------------------------------------------------------------------------------\nsearchBtn.addEventListener('click', handleGetSeries);\ndocument\n .querySelector('.js_form')\n .addEventListener('submit', (ev) => ev.preventDefault()); //para evitar que se genere un 'submit' por defecto al dar al intro, puesto que si solo hay un input y un button dentro de un form, este se envia automáticamente al darle al intro.\nfunction favListener() {\n const seriesHTML = document.querySelectorAll('.series--container');\n for (const serieHTML of seriesHTML) {\n serieHTML.addEventListener('click', handleFavorite);\n }\n}\nresetBtn.addEventListener('click', handleResetFavorites);\nfunction xBtnfavListener() {\n const xBtns = document.querySelectorAll('.js__Xbutton');\n for (const xBtn of xBtns) {\n xBtn.addEventListener('click', handleXButtonFavorites);\n }\n}", "dangerousExampleEn": "1. var danger = localStorage.getItem(\"some\");\n2. \n3. eval(danger);\nLine 2: Unvalidated data is sent to a web browser.", "safeExampleEn": "1. var danger = localStorage.getItem(\"some\");\n2. var safe = filter(danger);\n3. eval(safe);\nLine 2: Filter the data, and then, send it to the browser.", "contexts": [{"lineNo": 96, "eventType": "source", "messageKey": "synz.COMMON.called", "params": {"arg0": "paintFavorites"}}, {"lineNo": 96, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "="}}]}} {"id": "96c3c822baaa17f6ebbca50ef8d6eac1853aca1771c5036d7e60e630e27a1502", "license": {"spdx": ["MIT"], "repo": "ckswhd7774/polaroid_project", "path": "js/app.js", "repo_head_hexsha": "f50002b8c152f580e8025b7f2e7136197525b257", "stack_hexsha": "8bc4bec944cc6e7e59486d70a5e8fd3bd78f0579", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Cross-site scripting", "issueDescriptionEn": "The Cross-site scripting checker finds instances in which unvalidated data is sent to a web browser.\nlocalStorage can be manipulated by other applications. Therefore, if unvalidated data of localStorage is allowed for page generation, attackers can inject malicious scripts into pages.\nThis vulnerability lets attackers take over a user's cookie, session, or other information or execute an abnormal function. You can optionally specify functions that perform the respective roles of receiving, using, warning of, and filtering external inputs.\nMake sure that data is filtered if needed.", "issueLineNumber": 44, "entireCode": "const $imageInput1 = document.querySelector('.image-input1');\nconst $imageInput2 = document.querySelector('.image-input2');\nconst $imageInput3 = document.querySelector('.image-input3');\nconst $imageInput4 = document.querySelector('.image-input4');\nconst $imageInput5 = document.querySelector('.image-input5');\nconst $imageInput6 = document.querySelector('.image-input6');\n\nconst $imageView1 = document.querySelector('.image-view1'); \nconst $imageView2 = document.querySelector('.image-view2'); \nconst $imageView3 = document.querySelector('.image-view3'); \nconst $imageView4 = document.querySelector('.image-view4'); \nconst $imageView5 = document.querySelector('.image-view5'); \nconst $imageView6 = document.querySelector('.image-view6'); \n\nconst $imageViewer1 = document.querySelector('.image1');\nconst $imageViewer2 = document.querySelector('.image2');\nconst $imageViewer3 = document.querySelector('.image3');\nconst $imageViewer4 = document.querySelector('.image4');\nconst $imageViewer5 = document.querySelector('.image5');\nconst $imageViewer6 = document.querySelector('.image6');\n\n/* localStorage에서 이미지 경로 읽어와서 보여주는 함수 */\n/* localStorage에서 recentImage의 value값을 가져와 이미지 경로를 다시 지정해줌 */\n// const localStorageImage = () => {\n// const recentImageDataUrl = localStorage.getItem('recentImage'); // key가 recentImage인 value값을 읽어옴\n// if (recentImageDataUrl) $imageView.setAttribute('src', recentImageDataUrl)\n// };\n\n// const viewImage = () => { \n// const reader = new FileReader(); // 비동기적으로 유저 컴퓨터에 저장된 파일을 읽어옴\n// reader.onload = () => localStorage.setItem('recentImage', reader.result); // recentImage value에 reader가 읽어온 result를 지정함. localStorage에 이미지 저장하는 함수 \n// reader.readAsDataURL('$imageInput1'.files[0]); // readAsDataURL가 file에서 이미지를 읽어온 후 image-view에서 보여줌\n// };\n\n/* 이벤트 핸들러 부분*/\n\n$imageInput1.onchange = () => {\n console.log('image uploaded');\n const reader = new FileReader(); // 비동기적으로 유저 컴퓨터에 저장된 파일을 읽어옴\n \n reader.onload = () => {\n localStorage.setItem('recentImage1', reader.result); // recentImage value에 reader가 읽어온 result를 지정함. localStorage에 이미지 저장하는 함수 \n const recentImageDataUrl = localStorage.getItem('recentImage1'); // key가 recentImage인 value값을 읽어옴\n $imageViewer1.innerHTML = `\"image1\"`; \n };\n \n reader.readAsDataURL($imageInput1.files[0]); // readAsDataURL가 file에서 이미지를 읽어온 후 image-view에서 보여줌\n $imageInput1.style.display = 'none';\n};\n\n$imageInput2.onchange = () => {\n console.log('image uploaded');\n const reader = new FileReader(); \n \n reader.onload = () => {\n localStorage.setItem('recentImage2', reader.result); \n const recentImageDataUrl = localStorage.getItem('recentImage2'); \n $imageViewer2.innerHTML = `\"image2\"`; \n };\n \n reader.readAsDataURL($imageInput2.files[0]); \n $imageInput2.style.display = 'none';\n};\n\n$imageInput3.onchange = () => {\n console.log('image uploaded');\n const reader = new FileReader(); \n\n reader.onload = () => {\n localStorage.setItem('recentImage3', reader.result); \n const recentImageDataUrl = localStorage.getItem('recentImage3'); \n $imageViewer3.innerHTML = `\"image3\"`; \n }; \n \n reader.readAsDataURL($imageInput3.files[0]); \n $imageInput3.style.display = 'none';\n};\n\n$imageInput4.onchange = () => {\n console.log('image uploaded');\n const reader = new FileReader(); \n \n reader.onload = () => {\n localStorage.setItem('recentImage4', reader.result); \n const recentImageDataUrl = localStorage.getItem('recentImage4'); \n $imageViewer4.innerHTML = `\"image4\"`; \n };\n \n reader.readAsDataURL($imageInput4.files[0]); \n $imageInput4.style.display = 'none';\n};\n\n$imageInput5.onchange = () => {\n console.log('image uploaded');\n const reader = new FileReader(); \n \n reader.onload = () => {\n localStorage.setItem('recentImage5', reader.result); \n const recentImageDataUrl = localStorage.getItem('recentImage5'); \n $imageViewer5.innerHTML = `\"image5\"`; \n };\n \n reader.readAsDataURL($imageInput5.files[0]); \n $imageInput5.style.display = 'none';\n};\n\n$imageInput6.onchange = () => {\n console.log('image uploaded');\n const reader = new FileReader(); \n \n reader.onload = () => {\n localStorage.setItem('recentImage6', reader.result); \n const recentImageDataUrl = localStorage.getItem('recentImage6'); \n $imageViewer6.innerHTML = `\"image6\"`; \n };\n \n reader.readAsDataURL($imageInput6.files[0]); \n $imageInput6.style.display = 'none';\n};\n\n//document.addEventListener('DOMContentLoaded', localStorageImage);", "dangerousExampleEn": "1. var danger = localStorage.getItem(\"some\");\n2. \n3. eval(danger);\nLine 2: Unvalidated data is sent to a web browser.", "safeExampleEn": "1. var danger = localStorage.getItem(\"some\");\n2. var safe = filter(danger);\n3. eval(safe);\nLine 2: Filter the data, and then, send it to the browser.", "contexts": [{"lineNo": 43, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "getItem"}}, {"lineNo": 43, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 44, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "="}}]}} {"id": "90b91a4decd3fc5565dd3c28c9611fab577567e64e49a8bdd9b381b01caa61e1", "license": {"spdx": ["BSD-2-Clause"], "repo": "374992659/My-project", "path": "htdocs/js/flockChat.js", "repo_head_hexsha": "f39af7c6aa74cf0f1e83eb05e7a4098ff39a1ab0", "stack_hexsha": "54be88cf02a493d4fd297bc1eccede88e93f5e6e", "match": "repo_path"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Cross-site scripting", "issueDescriptionEn": "The Cross-site scripting checker finds instances in which unvalidated data is sent to a web browser.\nlocalStorage can be manipulated by other applications. Therefore, if unvalidated data of localStorage is allowed for page generation, attackers can inject malicious scripts into pages.\nThis vulnerability lets attackers take over a user's cookie, session, or other information or execute an abnormal function. You can optionally specify functions that perform the respective roles of receiving, using, warning of, and filtering external inputs.\nMake sure that data is filtered if needed.", "issueLineNumber": 707, "entireCode": "$(document).ready(function(){\n var apptoken = localStorage.getItem('apptoken');\n var group_name=localStorage.getItem(\"group_name\");\n document.title=group_name;\n // 时间戳的转换\n function getLocalTime(nS) {\n return new Date(parseInt(nS) * 1000).toLocaleString().replace(/:\\d{1,2}$/,' ');\n }\n if(!apptoken)alert('请重新登录');\n var ws = new WebSocket('ws://192.168.127.12:8282');//发起绑定\n ws.onmessage = function (e){\n var result = JSON.parse(e.data); //服务器返回结果\n console.log(result);\n switch(parseInt(result.type)){\n case 1: //1 .在线好友、好友未读消息、群未读消息\n if(parseInt(result.errcode) === 0){\n var data = (result.data);\n var arr=[];\n arr.push(data.online_friends);\n localStorage.setItem('online_friends',JSON.stringify(arr)); //本地保存在线好友列表\n var friends_new_message = data.friends_new_message;\n if(friends_new_message){ //好友新消息 已按用户分组 时间倒序排列\n\n }\n var group_new_message = data.group_new_message;\n if(group_new_message){ //群组新消息 已按群分组 时间倒序排列\n console.log(group_new_message);\n var html=\"\";\n //群组新消息 已按群分组 时间倒序排列\n $.each(group_new_message,function(i,item){\n var group_num=item.group_num;\n var group_code=item.group_code;\n var group_portrait=item.group_portrait;\n if(item.content){\n $.each(item.content,function(i,item){\n var httP=item.sender_portrait.split(\":\")[0];\n var sender_portrait=\"\";\n if(httP===\"http\"){\n sender_portrait=item.sender_portrait;\n }else{\n sender_portrait=\"http://wx.junxiang.ren/project/\"+item.sender_portrait\n }\n if(parseInt(item.type)===3){//图片、文件\n var contentHttp=item.content.split(\":\")[0];\n var contentPic=\"\";\n if(contentHttp===\"http\"){\n contentPic=item.content;\n }else{\n contentPic=\"http://wx.junxiang.ren/project/\"+item.content;\n }\n html+=`\n

    ${getLocalTime(item.send_time)}

    \n
    \n
    \n \"\"\n
    \n
    \n
    ${item.sender_nickname}
    \n \n \"\"\n \n
    \n
    `\n } else if(parseInt(item.type)===2){//语音\n html+=`\n

    ${getLocalTime(item.send_time)}

    \n
    \n
    \n \"\"\n
    \n
    \n
    ${item.sender_nickname}
    \n \n 播放语音\n \n \n
    \n
    \n \n `\n }else{//文字\n html+=`\n

    ${getLocalTime(item.send_time)}

    \n
    \n
    \n \"\"\n
    \n
    \n
    ${item.sender_nickname}
    \n \n ${item.content}\n \n \n
    \n
    \n \n `\n }\n // 本地未读聊天记录保存\n (function(){\n var json_str = \"{'sender_code':'\"+item.sender_code+\"','type':'\"+item.type+\"','send_time':'\"+item.send_time+\"','content':'\"+item.content+\"','nickname':'\"+item.sender_nickname+\"','portrait':'\"+sender_portrait+\"'}\";\n\n var history_chats = localStorage.getItem('history_'+group_code);\n if(!history_chats){\n history_chats = new Array();\n history_chats=[json_str];\n localStorage.setItem('history_'+group_code,JSON.stringify(history_chats));\n }else{\n history_chats = JSON.parse(history_chats);\n history_chats[history_chats.length] = json_str;\n if(history_chats.length>20){\n history_chats.shift();\n }\n localStorage.setItem('history_'+group_code,JSON.stringify(history_chats));\n }\n })();\n //保存聊天的好友资料\n })\n }\n });\n //向页面添加元素\n var chatPage=$(\"#chatPage\");\n chatPage.append(html);\n document.body.scrollTop=chatPage.height()+100;\n }\n var friends_new_apply = data.friends_new_apply;\n if(friends_new_apply){ //用户添加好友的申请\n\n }\n }\n break;\n case 2: //2.好友上线通知 更新本地在线好友列表\n if(parseInt(result.errcode) === 0){\n var data = (result.data);\n var friend_code = data.user_code;\n var online_friends = localStorage.getItem('online_friends');\n if(!contains(online_friends,friend_code)){\n // online_friends.push(friend_code);\n }\n localStorage.setItem('online_friends',online_friends);\n }\n break;\n case 3: //3.好友下线通知 更新本地在线好友列表\n if(parseInt(result.errcode) === 0){\n var data = (result.data);\n var friend_code = data.user_code;\n var online_friends = localStorage.getItem('online_friends');\n if(contains(online_friends,friend_code)){\n var i = online_friends.length;\n while (i--){\n if (arr[i] === obj) {\n online_friends.splice(i,1);\n }\n }\n localStorage.setItem('online_friends',online_friends);\n }\n }\n break;\n case 4: //4.接收到好友消息\n if(parseInt(result.errcode) === 0){\n var data =(result.data);\n var pathname = window.location.pathname;\n var patharr = pathname.split('/');\n var html = patharr[parseInt(patharr.length-1)];\n if(html ==='***.html'){ //如果当前页面在好友聊天界面 ***.html为好友聊天页面\n var current_code = $(\".elements\").val('user_code'); //获取当前聊天好友code\n if(current_code === data.sender_code){ //为同一个人 直接将聊天信息展示在页面内 向服务器读取了该消息的通知\n //展示好友发送的聊天信息\n\n //发送通知给服务器\n var sendMessage = JSON.stringify({'apptoken':apptoken,'type':6,'account_code':current_code});\n ws.send(sendMessage);\n }\n }else{ //其他页面 暂不处理\n\n }\n }\n break;\n case 5: //接收到群消息\n if(parseInt(result.errcode) === 0){\n var data =(result.data);\n var pathname = window.location.pathname;\n var patharr = pathname.split('/');\n var html = patharr[parseInt(patharr.length-1)];\n // 获取自己code\n var my_code=localStorage.getItem(\"my_code\");\n console.log(data);\n if(html ==='flockChat.html'){ //如果当前页面在群聊天界面 ***.html为群聊天页面\n var current_code = localStorage.getItem(\"group_code\"); //获取当前聊天群的群code\n if(current_code === data.group){ //为同一个人 直接将聊天信息展示在页面内 向服务器读取了该消息的通知\n // 本地存储聊天记录\n var json_str = \"{'sender_code':'\"+data.sender_code+\"','type':'\"+data.type+\"','send_time':'\"+data.send_time+\"','content':'\"+data.content+\"','nickname':'\"+data.send_nickname+\"','portrait':'\"+data.send_portrait+\"'}\";\n\n var history_chats = localStorage.getItem('history_'+data.group);\n if(!history_chats){\n history_chats = new Array();\n history_chats=[json_str];\n localStorage.setItem('history_'+data.group,JSON.stringify(history_chats));\n }else{\n history_chats = JSON.parse(history_chats);\n history_chats[history_chats.length] = json_str;\n if(history_chats.length>20){\n history_chats.shift();\n }\n localStorage.setItem('history_'+data.group,JSON.stringify(history_chats));\n }\n //展示好友发送的聊天信息\n var html=\"\";\n if(my_code===data.sender_code){//我自己的信息\n var httP=data.send_portrait.split(\":\")[0];\n var send_portrait=\"\";\n if(httP===\"http\"){\n send_portrait=data.send_portrait\n }else{\n send_portrait=\"http://wx.junxiang.ren/project/\"+data.send_portrait\n }\n if(data.type===3){//图片、文件\n var contentHttp=data.content.split(\":\")[0];\n var contentPIC=\"\";\n if(contentHttp===\"http\"){\n contentPIC=data.content;\n }else{\n contentPIC=\"http://wx.junxiang.ren/project/\"+data.content\n }\n html=`\n

    ${getLocalTime(data.send_time)}

    \n
    \n
    \n \n \"\"/\n \n
    \n
    \n \"\"\n
    \n
    \n `\n } else if(data.type===2){//语音\n html=`\n

    ${getLocalTime(data.send_time)}

    \n
    \n
    \n \n 播放语音\n \n
    \n \n
    \n \"\"\n
    \n
    \n \n `\n }else{//文字\n html=`\n

    ${getLocalTime(data.send_time)}

    \n
    \n
    \n ${data.content}\n
    \n \n
    \n \"\"\n
    \n
    \n \n `\n }\n }else{//群里其他人发的信息\n var httPs=data.send_portrait.split(\":\")[0];\n var send_portraits=\"\";\n if(httPs===\"http\"){\n send_portraits=data.send_portrait\n }else{\n send_portraits=\"http://wx.junxiang.ren/project/\"+data.send_portrait\n }\n if(data.type===3){//图片、文件\n var otherHttp=data.content.split(\":\")[0];\n var otherPic=\"\";\n if(otherHttp===\"http\"){\n otherPic=data.content;\n }else{\n otherPic=\"http://wx.junxiang.ren/project/\"+data.content;\n }\n html=`\n

    ${getLocalTime(data.send_time)}

    \n
    \n
    \n \"\"\n
    \n
    \n
    ${data.send_nickname}
    \n \n \"\"\n \n
    \n
    `\n } else if(data.type===2){//语音\n html=`\n

    ${getLocalTime(data.send_time)}

    \n
    \n
    \n \"\"\n
    \n
    \n
    ${data.send_nickname}
    \n \n 播放语音\n \n \n
    \n
    \n \n `\n }else{//文字\n html=`\n

    ${getLocalTime(data.send_time)}

    \n
    \n
    \n \"\"\n
    \n
    \n
    ${data.send_nickname}
    \n \n ${data.content}\n \n \n
    \n
    \n \n `\n }\n }\n var chatPage=$(\"#chatPage\");\n chatPage.append(html);\n document.body.scrollTop=chatPage.height()+100;\n //发送通知给服务器\n var sendMessage=JSON.stringify({'apptoken':apptoken,'type':7,'group_code':current_code});\n ws.send(sendMessage);\n //播放语音\n var num=0;\n chatPage.on(\"click\",\".weui-media-box .weui-media-box__bd .playVoice\",function(){\n //从微信服务器下载因为返回的服务器id在存本地id\n //获取服务器id\n num++;\n var id=$(this).attr(\"title\");\n wx.downloadVoice({\n serverId: id, // 需要下载的音频的服务器端ID,由uploadVoice接口获得\n isShowProgressTips: 1, // 默认为1,显示进度提示\n success: function (res){\n console.log(\"下载语音成功\");\n var localId=res.localId; // 返回音频的本地ID\n if(num%2===1){\n wx.playVoice({\n localId:localId, // 需要播放的音频的本地ID,由stopRecord接口获得\n success: function(){\n console.log(\"播放语音成功\");\n },\n fail:function () {\n console.log(\"播放语音失败\");\n }\n });\n }else{\n wx.pauseVoice({\n localId: localId, // 需要暂停的音频的本地ID,由stopRecord接口获得\n success:function () {\n console.log(\"暂停成功\");\n },\n fail:function(){\n console.log(\"暂停失败\");\n }\n });\n }\n\n },\n fail:function () {\n console.log(\"下载语音失败\");\n }\n });\n });\n }\n }else{ //其他页面 暂不处理\n }\n }\n break;\n case 8:\n console.log(result);\n if(result.errmsg===\"该群已被禁言\"){\n showHide(result.errmsg);\n }\n break;\n case 10://历史消息\n console.log(result);\n if(parseInt(result.errcode)===0){\n var group=localStorage.getItem(\"group_code\");\n var history_chat = localStorage.getItem('history_'+group);\n var my_code=localStorage.getItem(\"my_code\");\n console.log(\"获取本地历史记录\");\n if(history_chat){\n var history= $.parseJSON(history_chat);\n var jsonObj = eval('(' + history + ')');\n console.log(jsonObj);\n data=[];\n $.each(history,function(i,item){\n var jsonObj = eval('(' + item + ')');\n data[i]=jsonObj;\n })\n }\n var html=\"\";\n console.log(data.length);\n console.log(result.data.length);\n result.data.splice(parseInt(result.data.length)-parseInt(data.length));\n console.log(result.data.length);\n $.each(result.data,function(i,item){\n console.log(item);\n if(item.sender_code===my_code){//我的自己的聊天记录\n var httP=item.send_portrait.split(\":\")[0]\n console.log(\"聊天记录\");\n if(parseInt(item.type)===3){//内容为图片、文件\n var historyHttp=item.content.split(\":\")[0];\n var historyPic=\"\";\n if(historyHttp===\"http\"){\n historyPic=item.content;\n }else{\n historyPic=\"http://wx.junxiang.ren/project/\"+item.content\n }\n if(httP===\"http\"){//完整路径\n html+=`\n

    ${getLocalTime(item.send_time)}

    \n
    \n
    \n \n \"\"/\n \n
    \n
    \n \"\"\n
    \n
    \n `\n }else{//相对路径\n html+=`\n

    ${getLocalTime(item.send_time)}

    \n
    \n
    \n \n \"\"/\n \n
    \n
    \n \"\"\n
    \n
    \n `\n }\n } else if(parseInt(item.type)===2){//内容为语音\n if(httP===\"http\"){//绝对路径\n html+=`\n

    ${getLocalTime(item.send_time)}

    \n
    \n
    \n \n 语音播放\n \n
    \n
    \n \"\"\n
    \n
    \n `\n }else{//相对路径\n html+=`\n

    ${getLocalTime(item.send_time)}

    \n
    \n
    \n \n 语音播放\n \n
    \n
    \n \"\"\n
    \n
    \n `\n }\n\n }else{//内容为文字\n if(httP===\"http\"){//绝对路径\n html+=`\n

    ${getLocalTime(item.send_time)}

    \n
    \n
    \n ${item.content}\n
    \n
    \n \"\"\n
    \n
    \n `\n }else{//相对路径\n html+=`\n

    ${getLocalTime(item.send_time)}

    \n
    \n
    \n ${item.content}\n
    \n
    \n \"\"\n
    \n
    \n `\n }\n\n }\n }else{//好友的聊天记录\n var httP=item.send_portrait.split(\":\")[0];\n if(parseInt(item.type)===3){//内容为图片、文件\n var friendHttp=item.content.split(\":\")[0];\n var friendPic=\"\";\n if(friendHttp===\"http\"){\n friendPic=item.content;\n }else{\n friendPic=\"http://wx.junxiang.ren/project/\"+item.content;\n }\n if(httP===\"http\"){\n html+=`\n

    ${getLocalTime(item.send_time)}

    \n
    \n
    \n \"\"\n
    \n \n
    \n
    ${item.send_nickname}
    \n \n \"\"\n \n
    \n
    `\n }else{\n html+=`\n

    ${getLocalTime(item.send_time)}

    \n
    \n
    \n \"\"\n
    \n \n
    \n
    ${item.send_nickname}
    \n \n \"\"\n \n
    \n
    `\n }\n\n } else if(parseInt(item.type)===2){//内容为语音\n if(httP===\"http\"){\n html+=`\n

    ${getLocalTime(item.send_time)}

    \n
    \n
    \n \"\"\n
    \n \n \n
    \n
    ${item.send_nickname}
    \n \n 播放语音 \n \n
    \n
    \n \n `\n }else{\n html+=`\n

    ${getLocalTime(item.send_time)}

    \n
    \n
    \n \"\"\n
    \n
    \n
    ${item.send_nickname}
    \n \n 播放语音 \n \n
    \n
    \n \n `\n }\n }else{//内容为文字\n if(httP===\"http\"){\n html+=`\n

    ${getLocalTime(item.send_time)}

    \n
    \n
    \n \"\"\n
    \n \n \n
    \n
    ${item.send_nickname}
    \n \n ${item.content} \n \n
    \n
    \n \n `\n }else{\n html+=`\n

    ${getLocalTime(item.send_time)}

    \n
    \n
    \n \"\"\n
    \n \n \n
    \n
    ${item.send_nickname}
    \n \n ${item.content} \n \n
    \n
    \n \n `\n }\n }\n }\n });\n var chatPage=$(\"#chatPage\");\n chatPage.prepend(html);\n document.body.scrollTop=chatPage.height()+100;\n //播放语音\n var number=0;\n chatPage.on(\"click\",\".weui-media-box .weui-media-box__bd .playVoice\",function(){\n //从微信服务器下载因为返回的服务器id在存本地id\n //获取服务器id\n number++;\n var id=$(this).attr(\"title\");\n console.log(id);\n wx.downloadVoice({\n serverId: id, // 需要下载的音频的服务器端ID,由uploadVoice接口获得\n isShowProgressTips: 1, // 默认为1,显示进度提示\n success: function (res){\n console.log(\"下载语音成功\");\n var localId=res.localId; // 返回音频的本地ID\n if(number%2===1){\n wx.playVoice({\n localId:localId, // 需要播放的音频的本地ID,由stopRecord接口获得\n success: function(){\n console.log(\"播放语音成功\");\n },\n fail:function () {\n console.log(\"播放语音失败\");\n }\n });\n }else{\n wx.pauseVoice({\n localId: localId, // 需要暂停的音频的本地ID,由stopRecord接口获得\n success:function () {\n console.log(\"暂停成功\");\n },\n fail:function(){\n console.log(\"暂停失败\");\n }\n });\n }\n\n },\n fail:function () {\n console.log(\"下载语音失败\");\n }\n });\n });\n\n }\n break;\n\n }\n };\n ws.onopen=function(e){\n ws.send(JSON.stringify({'type' : 1,'apptoken' :apptoken}));\n (function(){\n var group=localStorage.getItem(\"group_code\");\n console.log(typeof group);\n var pathname = window.location.pathname;\n var patharr = pathname.split('/');\n var html = patharr[parseInt(patharr.length-1)];\n if(html===\"flockChat.html\"){\n var sendMessage = JSON.stringify({'apptoken':apptoken,'type':7,'group_code':group});\n ws.send(sendMessage);\n }\n })();\n };\n //获取本地聊天记录\n (function(){\n var group=localStorage.getItem(\"group_code\");\n var history_chat = localStorage.getItem('history_'+group);\n var my_code=localStorage.getItem(\"my_code\");\n console.log(\"获取本地历史记录\");\n if(history_chat){\n var history= $.parseJSON(history_chat);\n var jsonObj = eval('(' + history + ')');\n console.log(jsonObj);\n data=[];\n $.each(history,function(i,item){\n var jsonObj = eval('(' + item + ')');\n data[i]=jsonObj;\n });\n var html=\"\";\n $.each(data,function(i,item){\n var httP=item.portrait.split(\":\")[0];\n if(item.sender_code===my_code){//我的自己的聊天记录\n console.log(\"聊天记录\");\n if(parseInt(item.type)===3){//内容为图片、文件\n var historyHttp=item.content.split(\":\")[0];\n var historyPic=\"\";\n if(historyHttp===\"http\"){\n historyPic=item.content;\n }else{\n historyPic=\"http://wx.junxiang.ren/project/\"+item.content\n }\n if(httP===\"http\"){//完整路径\n html+=`\n

    ${getLocalTime(item.send_time)}

    \n
    \n
    \n \n \"\"/\n \n
    \n
    \n \"\"\n
    \n
    \n `\n }else{//相对路径\n html+=`\n

    ${getLocalTime(item.send_time)}

    \n
    \n
    \n \n \"\"/\n \n
    \n
    \n \"\"\n
    \n
    \n `\n }\n } else if(parseInt(item.type)===2){//内容为语音\n if(httP===\"http\"){//绝对路径\n html+=`\n

    ${getLocalTime(item.send_time)}

    \n
    \n
    \n \n 语音播放\n \n
    \n
    \n \"\"\n
    \n
    \n `\n }else{//相对路径\n html+=`\n

    ${getLocalTime(item.send_time)}

    \n
    \n
    \n \n 语音播放\n \n
    \n
    \n \"\"\n
    \n
    \n `\n }\n\n }else{//内容为文字\n if(httP===\"http\"){//绝对路径\n html+=`\n

    ${getLocalTime(item.send_time)}

    \n
    \n
    \n ${item.content}\n
    \n
    \n \"\"\n
    \n
    \n `\n }else{//相对路径\n html+=`\n

    ${getLocalTime(item.send_time)}

    \n
    \n
    \n ${item.content}\n
    \n
    \n \"\"\n
    \n
    \n `\n }\n\n }\n }else{//好友的聊天记录\n if(parseInt(item.type)===3){//内容为图片、文件\n var friendHttp=item.content.split(\":\")[0];\n var friendPic=\"\";\n if(friendHttp===\"http\"){\n friendPic=item.content;\n }else{\n friendPic=\"http://wx.junxiang.ren/project/\"+item.content;\n }\n if(httP===\"http\"){\n html+=`\n

    ${getLocalTime(item.send_time)}

    \n
    \n
    \n \"\"\n
    \n \n
    \n
    ${item.nickname}
    \n \n \"\"\n \n
    \n
    `\n }else{\n html+=`\n

    ${getLocalTime(item.send_time)}

    \n
    \n
    \n \"\"\n
    \n \n
    \n
    ${item.nickname}
    \n \n \"\"\n \n
    \n
    `\n }\n\n } else if(parseInt(item.type)===2){//内容为语音\n if(httP===\"http\"){\n html+=`\n

    ${getLocalTime(item.send_time)}

    \n
    \n
    \n \"\"\n
    \n \n \n
    \n
    ${item.nickname}
    \n \n 播放语音 \n \n
    \n
    \n \n `\n }else{\n html+=`\n

    ${getLocalTime(item.send_time)}

    \n
    \n
    \n \"\"\n
    \n
    \n
    ${item.nickname}
    \n \n 播放语音 \n \n
    \n
    \n \n `\n }\n }else{//内容为文字\n if(httP===\"http\"){\n html+=`\n

    ${getLocalTime(item.send_time)}

    \n
    \n
    \n \"\"\n
    \n \n \n
    \n
    ${item.nickname}
    \n \n ${item.content} \n \n
    \n
    \n \n `\n }else{\n html+=`\n

    ${getLocalTime(item.send_time)}

    \n
    \n
    \n \"\"\n
    \n \n \n
    \n
    ${item.nickname}
    \n \n ${item.content} \n \n
    \n
    \n \n `\n }\n\n }\n }\n });\n var chatPage=$(\"#chatPage\");\n chatPage.html(html);\n document.body.scrollTop=chatPage.height()+100;\n //播放语音\n var number=0;\n chatPage.on(\"click\",\".weui-media-box .weui-media-box__bd .playVoice\",function(){\n //从微信服务器下载因为返回的服务器id在存本地id\n //获取服务器id\n number++;\n var id=$(this).attr(\"title\");\n console.log(id);\n wx.downloadVoice({\n serverId: id, // 需要下载的音频的服务器端ID,由uploadVoice接口获得\n isShowProgressTips: 1, // 默认为1,显示进度提示\n success: function (res){\n console.log(\"下载语音成功\");\n var localId=res.localId; // 返回音频的本地ID\n if(number%2===1){\n wx.playVoice({\n localId:localId, // 需要播放的音频的本地ID,由stopRecord接口获得\n success: function(){\n console.log(\"播放语音成功\");\n },\n fail:function () {\n console.log(\"播放语音失败\");\n }\n });\n }else{\n wx.pauseVoice({\n localId: localId, // 需要暂停的音频的本地ID,由stopRecord接口获得\n success:function () {\n console.log(\"暂停成功\");\n },\n fail:function(){\n console.log(\"暂停失败\");\n }\n });\n }\n\n },\n fail:function () {\n console.log(\"下载语音失败\");\n }\n });\n });\n }\n })();\n // 聊天历史记录\n $(\".historyNews\").click(function(){\n var group=localStorage.getItem(\"group_code\");\n console.log(group);\n ws.send(JSON.stringify({'type':10,'apptoken' : apptoken,'group_code':group}));\n $(this).hide();\n });\n //群聊点击发送\n $(\".pushBtn\").click(function(){\n var chatContent=$(\".chatContent\");\n var content=chatContent.val(); //获取页面发送内容\n var group =localStorage.getItem(\"group_code\"); //获取发送好友的群code\n var message_type=1; //消息类型 1:文字消息 2:语音消息 3:文件消息\n ws.send(JSON.stringify({\"group\":group,'type' : 3,'content':content,'apptoken':apptoken,'message_type':message_type}));\n // 添加本地页面\n chatContent.val(\"\");\n var sendMessage = JSON.stringify({'apptoken':apptoken,'type':7,'group_code':group});\n ws.send(sendMessage);\n });\n //发送消息给好友\n $(\".elements\").click(function(){\n var elements=$(\".elements\");\n var content=elements.val('content'); //获取页面发送内容\n var account_code =elements.val('user_code'); //获取发送好友的code\n var message_type = 1; //消息类型 1:文字消息 2:语音消息 3:文件消息\n ws.send(JSON.stringify({'type' : 2, 'content' : content,'apptoken' : apptoken,'account_code':account_code,'message_type':message_type}));\n });\n // 发送图片\n $(\"#uploaderInputPic\").change(function(){\n var formData= new FormData();\n var apptoken=localStorage.getItem(\"apptoken\");\n formData.append(\"file\",$(\"#uploaderInputPic\")[0].files[0]);\n var data=[\"\",JSON.stringify({\"apptoken\":apptoken})];\n var json=jsEncryptData(data);\n formData.append(\"data\",json);\n\n $.ajax({\n type:\"POST\",\n url:url+\"ChatMessage_uploadGroupFile\",\n fileElementId:'uploaderInput',\n data:formData,\n processData : false,\n contentType : false,\n secureuri:false,\n success : function(data){\n // 解密\n data=jsDecodeData(data);\n console.log(data);\n if(data.errcode===0){\n localStorage.setItem(\"apptoken\",data.apptoken);\n console.log(data.data[0]);\n localStorage.setItem(\"friendPic\",\"http://wx.junxiang.ren/project/\"+data.data[0]);\n $(\".chatContent\").val(\"\");\n var content=localStorage.getItem(\"friendPic\");\n var group =localStorage.getItem(\"group_code\"); //获取发送好友的群code\n console.log(content);\n var message_type =3;\n ws.send(JSON.stringify({\"group\":group,'type' : 3,'content':content,'apptoken':apptoken,'message_type':message_type}));\n }\n },\n error:function (data) {\n }\n });\n\n }\n );\n // 上传文件\n $(\"#uploaderInputFile\").change(function(){\n var formData= new FormData();\n var apptoken=localStorage.getItem(\"apptoken\");\n formData.append(\"file\",$(\"#uploaderInputFile\")[0].files[0]);\n var data=[\"\",JSON.stringify({\"apptoken\":apptoken})];\n var json=jsEncryptData(data);\n formData.append(\"data\",json);\n console.log(formData);\n $.ajax({\n type:\"POST\",\n url:url+\"ChatMessage_uploadGroupFile\",\n fileElementId:'uploaderInput',\n data:formData,\n processData : false,\n contentType : false,\n secureuri:false,\n success : function(data){\n // 解密\n data=jsDecodeData(data);\n if(data.errcode===0){\n localStorage.setItem(\"apptoken\",data.apptoken);\n console.log(data.data[0]);\n localStorage.setItem(\"friendPic\",\"http://wx.junxiang.ren/project/\"+data.data[0]);\n $(\".chatContent\").val(\"\");\n var content=localStorage.getItem(\"friendPic\");\n var group =localStorage.getItem(\"group_code\"); //获取发送好友的群code\n console.log(content);\n var message_type = 3;\n ws.send(JSON.stringify({\"group\":group,'type' : 3,'content':content,'apptoken':apptoken,'message_type':message_type}));\n }\n },\n error:function (data){\n\n }\n });\n\n }\n );\n\n // 发送语音功能\n (function(){\n var localId=\"\",\n signature = '',\n serverId='';\n $.ajax({\n url:'http://3172.16.58.3/project/index.php?m=Api&c=JsSdk&a=getSignPackage&debugging=test',\n type:'POST',\n data : {'url':location.href},\n success:function(data){\n console.log(data);\n signature = data.data;\n wx.config({\n debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。\n appId: signature.appId, // 必填,公众号的唯一标识\n timestamp:signature.timestamp , // 必填,生成签名的时间戳\n nonceStr: signature.nonceStr, // 必填,生成签名的随机串\n signature: signature.signature,// 必填,签名,见附录1\n jsApiList: [ 'startRecord','stopRecord','playVoice','stopVoice','downloadVoice','uploadVoice','pauseVoice','onVoiceRecordEnd'] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2\n });\n }\n });\n wx.ready(function(){\n wx.onVoicePlayEnd({\n success: function(res){\n stopWave();\n }\n });\n // config信息验证后会执行ready方法,所有接口调用都必须在config接口获得结果之后,config是一个客户端的异步操作,所以如果需要在页面加载时就调用相关接口,则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口,则可以直接调用,不需要放在ready函数中。\n });\n wx.error(function(res){\n // config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名。\n });\n // 开始录音\n function starRecord(event){\n event.preventDefault();\n START = new Date().getTime();\n recordTimer = setTimeout(function(){\n wx.startRecord({\n success: function(){\n localStorage.rainAllowRecord='true';\n },\n cancel: function () {\n alert('用户拒绝授权录音');\n }\n });\n },300);\n }\n //结束录音\n function stopRecord(event) {\n event.preventDefault();\n END = new Date().getTime();\n if((END - START) < 300){\n END = 0;\n START = 0;\n //小于300ms,不录音\n clearTimeout(recordTimer);\n }else{\n wx.stopRecord({\n success: function (res) {\n localId=res.localId;\n uploadRecord();\n },\n fail: function (res) {\n alert(JSON.stringify(res));\n }\n });\n }\n }\n //监听录音自动停止接口\n function onVoiceRecordEnd(){\n wx.onVoiceRecordEnd({\n // 录音时间超过一分钟没有停止的时候会执行 complete 回调\n complete: function (res) {\n localId = res.localId;\n }\n });\n }\n // 播放语音文件\n function playRecord(local_id,serverId){\n wx.playVoice({\n localId:local_id, // 需要播放的音频的本地ID,由stopRecord接口获得\n success: function(){\n wx.stopVoice({\n localId:local_id\n });\n },\n fail:function(){\n wx.downloadVoice({\n serverId:serverId,\n isShowProgressTips: 1,\n success: function (res) {\n localId = res.localId;\n playRecord(localId,serverId);\n }\n });\n }\n });\n }\n //暂停播放语音文件\n function pauseRecCord(){\n wx.pauseVoice({\n localId: localId // 需要暂停的音频的本地ID,由stopRecord接口获得\n });\n }\n //停止播放语音文件\n function stopPlayRecord(){\n wx.stopVoice({\n localId: localId // 需要停止的音频的本地ID,由stopRecord接口获得\n });\n }\n //上传录音\n function uploadRecord(){\n //调用微信的上传录音接口把本地录音先上传到微信的服务器\n //不过,微信只保留3天,而我们需要长期保存,我们需要把资源从微信服务器下载到自己的服务器\n wx.uploadVoice({\n localId:localId, // 需要上传的音频的本地ID,由stopRecord接口获得\n isShowProgressTips: 1, // 默认为1,显示进度提示\n success: function (res) {\n //把录音在微信服务器上的id(res.serverId)发送到自己的服务器供下载。\n serverId = res.serverId; // 返回音频的服务器端ID\n var group =localStorage.getItem(\"group_code\");\n var message_type=2;\n ws.send(JSON.stringify({\"group\":group,'type' : 3,'content':serverId,'apptoken':apptoken,'message_type':message_type}));\n }\n });\n }\n // 下载录音\n function downloadRecord(){\n wx.ready(function () {\n wx.downloadVoice({\n serverId: serverId, // 需要下载的音频的服务器端ID,由uploadVoice接口获得\n isShowProgressTips: 1, // 默认为1,显示进度提示\n success: function (res) {\n localId = res.localId; // 返回音频的本地ID\n return localId;\n }\n });\n })\n }\n // 调用函数\n //按下开始录音\n $(\"#talk_btn\").on(\"touchstart\",function(){\n starRecord(event);\n });\n //松手结束录音\n $(\"#talk_btn\").on(\"touchend\",function(){\n stopRecord(event);\n });\n })();\n\n /*\n * 判断是否存在元素\n * */\n function contains(arr, obj) {\n var i = arr.length;\n while (i--) {\n if (arr[i] === obj) {\n return true;\n }\n }\n return false;\n }\n $(\".imgBtn\").click(function(){\n var grids=$(\".weui-grids\");\n if(grids.is(\":hidden\")){\n grids.show();\n }else{\n grids.hide();\n }\n });\n // 获取群名字\n var group_name =localStorage.getItem(\"group_name\");\n $(\".group_name\").html(group_name);\n // 图片放大预览\n (function(){\n var gallery=$(\".weui-gallery\");\n $(\"#chatPage\").on(\"click\",\".weui-media-box .weui-media-box__bd .weui-media-box__desc img\",function(){\n var url=$(this).attr(\"src\");\n if(gallery.is(\":hidden\")){\n gallery.show();\n $(\".weui-gallery__img\").attr(\"style\",\"background-image: url(\"+url +\")\")\n }\n });\n gallery.click(function(){\n $(\".weui-gallery\").hide();\n });\n })();\n $(function(){\n pushHistory();\n window.addEventListener(\"popstate\", function(e) {\n window.location.href=\"createCrowd.html\";\n }, true);\n function pushHistory() {\n var state = {\n title: \"title\",\n url: \"#\"\n };\n window.history.pushState(state, \"title\", \"#\");\n }\n });\n //进入群资料页面\n $(\".groupInfo\").click(function () {\n window.location.href=\"commDiscu.html\";\n });\n $(\"#chatPage\").on(\"click\",\".weui-media-box .weui-media-box__hd .weui-media-box__thumb\",function () {\n var sender_code=$(this).attr(\"title\");\n console.log(\"群成员code\");\n console.log(sender_code);\n localStorage.setItem(\"sender_code\",sender_code);\n if(sender_code){\n window.location.href=\"groupUserDetails.html\";\n }\n });\n});", "dangerousExampleEn": "1. var danger = localStorage.getItem(\"some\");\n2. \n3. eval(danger);\nLine 2: Unvalidated data is sent to a web browser.", "safeExampleEn": "1. var danger = localStorage.getItem(\"some\");\n2. var safe = filter(danger);\n3. eval(safe);\nLine 2: Filter the data, and then, send it to the browser.", "contexts": [{"lineNo": 701, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "getItem"}}, {"lineNo": 702, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "getItem"}}, {"lineNo": 705, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "705"}}, {"lineNo": 706, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "parseJSON"}}, {"lineNo": 707, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "eval"}}]}} {"id": "afc3cda73b45c18d0a86158d023f2f7beeeedd4f239f8f32af938ec37a39fc1c", "license": {"spdx": ["MIT"], "repo": "janschill/solid-comment", "path": "src/components/error-message.js", "repo_head_hexsha": "caaa9b91be959d6d240f17ed251b0f5035bf0d9e", "stack_hexsha": "4c6293c62386f45a821e9d3682f76e6d61d58acb", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Cross-site scripting", "issueDescriptionEn": "The Cross-site scripting checker finds instances in which unvalidated data is sent to a web browser.\nlocalStorage can be manipulated by other applications. Therefore, if unvalidated data of localStorage is allowed for page generation, attackers can inject malicious scripts into pages.\nThis vulnerability lets attackers take over a user's cookie, session, or other information or execute an abnormal function. You can optionally specify functions that perform the respective roles of receiving, using, warning of, and filtering external inputs.\nMake sure that data is filtered if needed.", "issueLineNumber": 22, "entireCode": "import { get } from 'lodash'\n\nimport Component from './component'\nimport store from '../store/index'\n\nexport default class ErrorMessage extends Component {\n constructor () {\n super({\n store,\n element: document.querySelector('.sc-error')\n })\n }\n\n render () {\n const errorMessage = get(store, 'state.errorMessage.data')\n if (errorMessage !== '') {\n this.showElement()\n const errorMessagBody = errorMessage.body === ''\n ? ''\n : `

    ${errorMessage.body}

    `\n\n this.element.innerHTML = `\n Error: ${errorMessage.summary}\n ${errorMessagBody}\n `\n } else {\n this.hideElement()\n }\n }\n}", "dangerousExampleEn": "1. var danger = localStorage.getItem(\"some\");\n2. \n3. eval(danger);\nLine 2: Unvalidated data is sent to a web browser.", "safeExampleEn": "1. var danger = localStorage.getItem(\"some\");\n2. var safe = filter(danger);\n3. eval(safe);\nLine 2: Filter the data, and then, send it to the browser.", "contexts": [{"lineNo": 16, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "16"}}, {"lineNo": 22, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "="}}]}} {"id": "b8069835bc58d10314ed40c3ca207c5c58edceb4681e92987155ef47dacd6882", "license": {"spdx": ["Apache-2.0"], "repo": "jdnierth/javascript-coding-tests", "path": "challenges/javascript-all-beginning-is-easy/needle-in-the-hay-stack/source/app.js", "repo_head_hexsha": "3dbb6016c6083b5908f2d5252251705a6cf08380", "stack_hexsha": "1ed36e608541bf1967ac12bfeca29c157cd0d9f2", "match": "repo_path"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Cross-site scripting", "issueDescriptionEn": "The Cross-site scripting checker finds instances in which unvalidated data is sent to a web browser.\nlocalStorage can be manipulated by other applications. Therefore, if unvalidated data of localStorage is allowed for page generation, attackers can inject malicious scripts into pages.\nThis vulnerability lets attackers take over a user's cookie, session, or other information or execute an abnormal function. You can optionally specify functions that perform the respective roles of receiving, using, warning of, and filtering external inputs.\nMake sure that data is filtered if needed.", "issueLineNumber": 31, "entireCode": "/**\n * Immediatly called function that will checke whether or not a given\n * value is a leap year or not.\n *\n * @author: \n * @date: 2/24/2017\n */\n\n(function() {\n\n \"use strict\";\n\n var copyDom = document.getElementById('copy'),\n needlePositionsDom = document.getElementById('needlePositions'),\n needlesDom = document.getElementById('needles');\n\n _init();\n\n function _init() {\n var copy = copyDom.innerHTML,\n newCopy,\n numberOfNeedles,\n allNeedlePos;\n\n newCopy = _markNeedle(copy);\n\n allNeedlePos = _findNeedlesRecursive(copy, 'needle', 0, 0);\n\n numberOfNeedles = _getNumberOfNeedles(allNeedlePos);\n\n _showResultMessage(newCopy, allNeedlePos, numberOfNeedles);\n\n }\n\n /**\n * Recursive function to find the\n * @param { String } copy in which to find everything.\n * @param { String } needle the name to search for in the copy\n * @param { Number } pos the index from which to search off from.\n * @param { Number } iter the number of iteration.\n * @returns { Array } an empty array if nothing found otherwise array containing the indexes of found needles.\n * @private\n */\n function _findNeedlesRecursive(copy, needle, pos, iter) {\n\n var newPos = _findNeedle(copy, needle, pos),\n posArray = [], otherPos;\n\n if (newPos != -1) {\n\n console.log(\"\\t\".repeat(iter), 'Starting at: ', pos, ' Interim result at: ', newPos, ', continue searching ...');\n otherPos = _findNeedlesRecursive(copy, needle, newPos + 1, iter + 1);\n\n console.log(\"\\t\".repeat(iter), 'Interim result at: ', newPos, ', further results: ', otherPos);\n posArray.push(newPos);\n posArray = posArray.concat(otherPos);\n\n } else {\n\n console.log(\"\\t\".repeat(iter), 'End reached, return: ', posArray)\n }\n\n return posArray;\n\n }\n\n /**\n * Highlights the needle work in a given copy.\n *\n * @param { String } copy in which to find / mark the needle.\n * @returns { String } the new copy containing highlighted found needles.\n * @private\n */\n function _markNeedle(copy) {\n return copy.replace(/needle/g, 'needle');\n }\n\n /**\n * Find a needle\n * @param { String } copy in which to find the needle\n * @param { String } needle to search for in the copy.\n * @param { Number } index from wich to search from in the copy for the needle.\n * @returns { Number } returns -1 if needle wasn't found else the position of the found needles.\n *\n * @private\n */\n function _findNeedle(copy, needle, index) {\n return copy.indexOf(needle, index);\n }\n\n /**\n * Returns how many needles have been found in the haystack.\n *\n * @param { Array } needleIndexes\n * @returns {number}\n * @private\n */\n function _getNumberOfNeedles(needleIndexes) {\n return needleIndexes.length;\n }\n\n /**\n * Shows the results on the page\n *\n * @private\n */\n function _showResultMessage(highlighted, needlePositions, numberOfNeedles) {\n copyDom.innerHTML = highlighted;\n needlePositionsDom.innerHTML = needlePositions;\n needlesDom.innerHTML = numberOfNeedles;\n\n }\n})();", "dangerousExampleEn": "1. var danger = localStorage.getItem(\"some\");\n2. \n3. eval(danger);\nLine 2: Unvalidated data is sent to a web browser.", "safeExampleEn": "1. var danger = localStorage.getItem(\"some\");\n2. var safe = filter(danger);\n3. eval(safe);\nLine 2: Filter the data, and then, send it to the browser.", "contexts": [{"lineNo": 27, "eventType": "source", "messageKey": "synz.COMMON.value.returned.from", "params": {"arg0": "_findNeedlesRecursive"}}, {"lineNo": 27, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 27, "eventType": "source", "messageKey": "synz.COMMON.called", "params": {"arg0": "_findNeedlesRecursive"}}, {"lineNo": 31, "eventType": "source", "messageKey": "synz.COMMON.called", "params": {"arg0": "_showResultMessage"}}, {"lineNo": 31, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "="}}]}} {"id": "40a5ff1d2502650e1c0ef8139bb5b39ab29ed00c277c3a1fad87130971c91c68", "license": {"spdx": ["MIT"], "repo": "erinlim2001/code-quiz", "path": "script.js", "repo_head_hexsha": "880fadec81d49c659fff5475664479d93425a705", "stack_hexsha": "4d59d922854f4747325082520d19f318a005de6e", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Cross-site scripting", "issueDescriptionEn": "The Cross-site scripting checker finds instances in which unvalidated data is sent to a web browser.\nlocalStorage can be manipulated by other applications. Therefore, if unvalidated data of localStorage is allowed for page generation, attackers can inject malicious scripts into pages.\nThis vulnerability lets attackers take over a user's cookie, session, or other information or execute an abnormal function. You can optionally specify functions that perform the respective roles of receiving, using, warning of, and filtering external inputs.\nMake sure that data is filtered if needed.", "issueLineNumber": 200, "entireCode": "var start = document.getElementById(\"start\");\nvar quiz = document.getElementById(\"quiz\");\nvar question = document.getElementById(\"question\");\nvar choiceA = document.getElementById(\"A\");\nvar choiceB = document.getElementById(\"B\");\nvar choiceC = document.getElementById(\"C\");\nvar choiceD = document.getElementById(\"D\");\nvar scoreDiv = document.getElementById(\"score\");\nvar timerDisplay = document.getElementById(\"timerDisplay\");\nvar enter = document.getElementById(\"enter\");\nvar startOver = document.getElementById(\"startOver\");\n\n//create questions\nvar questions = [\n {\n question: \"Which bird is a universal symbol of peace?\",\n choiceA: \"pigeon\",\n choiceB: \"parrot\",\n choiceC: \"eagle\",\n choiceD: \"dove\",\n correct: \"D\"\n },\n {\n question: \"A snail can sleep for how many years?\",\n choiceA: \"3\",\n choiceB: \"5\",\n choiceC: \"7\",\n choiceD: \"20\",\n correct: \"A\"\n },\n {\n question: \"A group of lions is known as?\",\n choiceA: \"family\",\n choiceB: \"school\",\n choiceC: \"pride\",\n choiceD: \"group\",\n correct: \"C\"\n },\n {\n question: \"How many heart chambers a cockroach has?\",\n choiceA: \"12\",\n choiceB: \"1\",\n choiceC: \"10\",\n choiceD: \"4\",\n correct: \"A\"\n },\n {\n question: \"Which animal has the highest blood pressure?\",\n choiceA: \"dog\",\n choiceB: \"giraffe\",\n choiceC: \"zebra\",\n choiceD: \"koala\",\n correct: \"B\"\n }\n\n];\n\nvar lastQuestion = questions.length - 1;\nlet currentQuestion = 0;\nvar score = 0;\nvar timer;\nvar timeLeft = 75;\n\nfunction setTime() {\n timer = setInterval(function () {\n timeLeft--;\n document.getElementById(\"timeLeft\").innerHTML = timeLeft;\n\n if (timeLeft <= 0) {\n //stops execution of action at set interval\n //automatically zero when time left becomes negative\n timeLeft = 0;\n document.getElementById(\"timeLeft\").innerHTML = timeLeft;\n clearInterval(timer);\n //calls function to end game \n //gameOver();\n }\n }, 1000);\n }\n\nfunction renderQuestion(){\n var q = questions[currentQuestion];\n question.innerHTML = \"

    \" + q.question + \"

    \";\n choiceA.innerHTML = q.choiceA;\n choiceB.innerHTML = q.choiceB;\n choiceC.innerHTML = q.choiceC;\n choiceD.innerHTML = q.choiceD;\n}\n\nstart.addEventListener(\"click\", startQuiz);\nenter.addEventListener(\"click\", highScore);\nstartOver.addEventListener(\"click\", startQuiz);\n\nfunction startQuiz() {\n const description = document.getElementById('description');\n description.style.display = \"none\";\n timeLeft = 75;\n score = 0;\n currentQuestion = 0;\n\n timerDisplay.style.display = \"block\";\n setTime();\n start.style.display = \"none\";\n startOver.style.display = \"none\";\n choiceA.style.display = \"block\";\n choiceB.style.display = \"block\";\n choiceC.style.display = \"block\";\n choiceD.style.display = \"block\";\n scoreDiv.style.display = \"none\";\n\n renderQuestion();\n quiz.style.display= \"block\";\n}\n\nfunction sleep(ms) {\n return new Promise(\n resolve => setTimeout(resolve, ms)\n );\n}\n\nasync function checkAnswer(answer) {\n const output = document.getElementById('output');\n\n if(answer == questions[currentQuestion].correct) {\n score += 20;\n output.style.display = \"block\";\n //output.style.backgroundColor = \"#B8FF33\";\n output.innerHTML = 'Correct!'\n } else {\n timeLeft -= 15;\n output.style.display = \"block\";\n //output.style.backgroundColor = \"#FF3375\";\n output.innerHTML = 'Wrong!'\n }\n await sleep(1000);\n output.style.display = \"none\";\n\n if(currentQuestion < lastQuestion) {\n currentQuestion++;\n renderQuestion();\n } else {\n gameOver();\n clearInterval(timer);\n }\n}\n\nfunction gameOver0(){\n question.style.display = \"none\";\n choices.style.display = \"none\";\n scoreDiv.style.display = \"block\";\n scoreDiv.innerHTML = \"

    YOU GOT: \" + score + \"%

    \";\n}\n\nfunction gameOver(){\n const A = document.getElementById('A');\n const B = document.getElementById('B');\n const C = document.getElementById('C');\n const D = document.getElementById('D');\n const I = document.getElementById('initial');\n const E = document.getElementById('enter');\n\n A.style.display = \"none\";\n B.style.display = \"none\";\n C.style.display = \"none\";\n D.style.display = \"none\";\n question.innerHTML = 'All done!';\n scoreDiv.style.display = \"block\";\n scoreDiv.innerHTML = \"

    YOU GOT: \" + score + \"%
    Enter initial:

    \";\n I.style.display = \"block\";\n E.style.display = \"block\";\n}\n\nfunction highScore() {\n const A = document.getElementById('A');\n const B = document.getElementById('B');\n const C = document.getElementById('C');\n const D = document.getElementById('D');\n const I = document.getElementById('initial');\n const E = document.getElementById('enter');\n const SO = document.getElementById('startOver');\n\n var iText = I.innerText;\n A.style.display = \"none\";\n B.style.display = \"none\";\n C.style.display = \"none\";\n D.style.display = \"none\";\n \n I.style.display = \"none\";\n E.style.display = \"none\";\n savedScore = parseInt(localStorage.getItem(iText));\n \n if (isNaN(savedScore) || score > savedScore) {\n localStorage.setItem(iText, score);\n question.innerHTML = 'High score';\n scoreDiv.style.display = \"block\";\n scoreDiv.innerHTML = \"

    \" + iText + \": \" + score + \"%

    \";\n } else {\n question.innerHTML = 'High score';\n scoreDiv.style.display = \"block\";\n scoreDiv.innerHTML = \"

    \" + iText + \": \" + savedScore + \"%

    \";\n }\n SO.style.display = \"block\";\n \n}", "dangerousExampleEn": "1. var danger = localStorage.getItem(\"some\");\n2. \n3. eval(danger);\nLine 2: Unvalidated data is sent to a web browser.", "safeExampleEn": "1. var danger = localStorage.getItem(\"some\");\n2. var safe = filter(danger);\n3. eval(safe);\nLine 2: Filter the data, and then, send it to the browser.", "contexts": [{"lineNo": 190, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "getItem"}}, {"lineNo": 190, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "parseInt"}}, {"lineNo": 192, "eventType": "source", "messageKey": "synz.COMMON.branch.false.assumed", "params": {"arg0": "197"}}, {"lineNo": 200, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "="}}]}} {"id": "16d2c9d7b77f37fa6e46e1e051bfeec3979f86da50b1c97f1d6e683abd71d4c9", "license": {"spdx": ["MIT"], "repo": "MatheusSiqs/Termooo", "path": "script.js", "repo_head_hexsha": "7712e37b35a04bf36947f4e8c4c5da29456f44d2", "stack_hexsha": "232c9bc88b7ff12971e9650e59f37d50767b940d", "match": "repo_path"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Cross-site scripting", "issueDescriptionEn": "The Cross-site scripting checker finds instances in which unvalidated data is sent to a web browser.\nlocalStorage can be manipulated by other applications. Therefore, if unvalidated data of localStorage is allowed for page generation, attackers can inject malicious scripts into pages.\nThis vulnerability lets attackers take over a user's cookie, session, or other information or execute an abnormal function. You can optionally specify functions that perform the respective roles of receiving, using, warning of, and filtering external inputs.\nMake sure that data is filtered if needed.", "issueLineNumber": 61, "entireCode": "//Site baseado no jogo term.ooo desenvolvido por \nvar teclado = [\"Q\",\"W\",\"E\",\"R\",\"T\",\"Y\",\"U\",\"I\",\"O\",\"P\",\"A\",\"S\",\"D\",\"F\",\"G\",\"H\",\"J\",\"K\",\"L\",\"Z\",\"X\",\"C\",\"V\",\"B\",\"N\",\"M\",\"Backspace\",\"Enter\"]\nvar curResp = [\"\",\"\",\"\",\"\",\"\"]\nvar pos = 0;\nvar linha = 0;\nvar acerto = false;\nvar erro = false;\nvar db, atual;\n\n\nif(!localStorage.getItem(\"db\")){\n\tnovoJogador();\n}else{\n\tcarregarTabela();\n}\n\nfunction novoJogador(){\n\tvar db = {Totaljogos:0,sVitoria:0,mSequencia:0,tentativas:[0,0,0,0,0,0,0]}\n\tvar atual = {chave:[\"F\",\"O\",\"R\",\"T\",\"E\"],aTentativas:[\n\t\t\t[],\n\t\t\t[],\n\t\t\t[],\n\t\t\t[],\n\t\t\t[],\n\t\t\t[],\n\t\t]\n\t}\n\tlocalStorage.setItem(\"db\",JSON.stringify(db));\n\tlocalStorage.setItem(\"atual\",JSON.stringify(atual));\n\t\n\tcarregarTabela();\n}\n\nfunction carregarTabela(){\n\tlet aux,soma = 0;\n\tlet maiorTenta = 0;\n\tlet nJogos = document.getElementById(\"nJogos\")\n\t\n\tdb = localStorage.getItem(\"db\");\n\tatual = localStorage.getItem(\"atual\");\n\t\n\tdb = JSON.parse(db);\n\tatual = JSON.parse(atual);\n\t\n\tdocument.getElementById(\"nJogos\").innerHTML = db.Totaljogos;\n\tdocument.getElementById(\"sVitoria\").innerHTML = db.sVitoria;\n\tdocument.getElementById(\"melhorSequencia\").innerHTML = db.mSequencia;\n\t\n\tfor(aux = 0; aux {\n\t\tif(event.target == modal){\n\t\t\tmodal.style.display = \"none\";\n\t\t}\n\t}, true)\nteclado.forEach( item => {\n\tdocument.getElementById(\"Tecla\"+item).addEventListener('click', () => {\n\t\tlet letra = KeyboardEvent;\n\t\t\n\t\tswitch(item){\n\t\t\tcase \"Backspace\":\n\t\t\t\tletra.keyCode = 8;\n\t\t\t\tescrita(letra);\n\t\t\t\tbreak\n\t\t\tcase \"Enter\":\n\t\t\t\tletra.keyCode = 13;\n\t\t\t\tescrita(letra);\n\t\t\t\tbreak\n\t\t\tdefault:\n\t\t\t\tletra.keyCode = item.charCodeAt();\n\t\t\t\tletra.key = item;\n\t\t\t\tescrita(letra);\t\n\t\t\t\tbreak;\n\t\t}\n\n\t}, true)\n})\ngeraPalavra()\n\n//Gera uma palavra aleatoria\nfunction geraPalavra(){\n\tlet api = new XMLHttpRequest();\n\tlet senha;\n\tlet chave;\n\tlet aux;\n\t\n\tapi.open(\"get\",\"https://api.dicionario-aberto.net/random\", true);\n\tapi.send();\n\tapi.onload = () => {\n\t\tsenha = JSON.parse(api.responseText);\n\t\tsenha.word.toUpperCase();\n\t\tchave = senha.word.split(\"\")\n\t\tconsole.log(chave);\n\t\t\n\t\tfor(aux=0;aux<5;aux++){\n\t\t\tatual.chave[aux] = chave[aux].toUpperCase();\n\t\t}\n\t\t\n\t\t\n\t\tconsole.log(api.responseText)\n\t}\n\t\n}\n\nfunction salvaDB(){\n\tlocalStorage.setItem(\"db\",JSON.stringify(db));\n\tlocalStorage.setItem(\"atual\",JSON.stringify(atual));\n\t\n\tcarregarTabela();\n}\n\n\n//função com o script para ler as entradas e executar os comandos vindos do teclado;\nfunction escrita(key){\n\tif(key.keyCode == 8){\n\t\tif(pos >= 0){\n\t\t\tcurResp[pos-1] = \"\";\n\t\t\tif(pos > 0)\n\t\t\t\tpos--\n\t\t}\n\t}\n\t\n\tif(pos<=4){\n\t\tif(key.keyCode >=65 && key.keyCode <= 90){\n\t\t\tcurResp[pos] = key.key.toUpperCase();\n\t\t\tpos++\n\t\t}\n\t}\n\t\n\tif(key.keyCode == 13){\n\t\tlet label = document.getElementById(\"label\")\n\t\tif(pos == 5){\n\t\t\tcomparacao()\n\t\t}else{\n\t\t\tlabel.innerHTML = \"Somente palavras com 5 letras\"\n\t\t\tlabel.style.visibility = \"visible\";\n\t\t\tsetTimeout( () => {label.style.opacity = 0;},1*1000);\n\t\t\tsetTimeout( () => {label.style.visibility = \"Hidden\";label.style.opacity = 1;},3*1000)\t\t\n\t\t}\n\t\t\n\t}\n\t\n\n\timprimeResp()\n}\n\n//função para a impressao na tela do vetor contendo a escolha do jogador\nfunction imprimeResp(){\n\tlet aux = 0;\n\t\n\tif(linha>5)\n\t\treturn;\n\t\n\tfor(aux = 0; aux<=4;aux++){\n\t\tdocument.getElementById(linha+\"l\"+aux).innerHTML = curResp[aux];\n\t}\n}\n\n//função com o script de verificação das letras se estão certas, se pertencem a chave ou se não possuem na chave;\nfunction comparacao(){\n\tlet aux = 0;\n\tlet sub = 0;\n\tlet count = 0;\n\t\n\tfor(aux = 0;aux <= 4; aux++){\n\t\tlet cell = document.getElementById(linha+\"l\"+aux);\n\t\t//console.log(\"sucess:\\nKey: \"+curResp[aux]+\"\\nChave: \"+chave[aux]+\"\\nteste: \"+(curResp[aux]==chave[aux]));\n\t\t//verificação se a letra possue na palavra e esta no lugar certo\n\t\tatual.aTentativas[linha]+=curResp[aux]\n\t\tif(curResp[aux] == atual.chave[aux]){\n\t\t\tcell.parentNode.animate([\n\t\t\t//keyframe\n\t\t\t\t{transform: 'rotateY(0deg)'},\n\t\t\t\t{transform: 'rotateY(90deg)'},\n\t\t\t\t{transform: 'rotateY(0deg)'}\n\t\t\t],{\n\t\t\t//parametro\n\t\t\t\tduration: 748\n\t\t\t});\n\t\t\tcell.parentNode.style.backgroundColor = \"var(--sucesso)\"\n\t\t\tdocument.getElementById(\"Tecla\"+curResp[aux]).style.backgroundColor = \"var(--sucesso)\"\n\t\t\tcount++;\n\t\t\t\n\t\t}else{\n\t\t\t//verificação se a letra se repete pelo menos uma vez na chave\n\t\t\tfor(sub = 0; sub<= 4; sub++){\n\t\t\t\tif(curResp[aux]==atual.chave[sub]){\n\t\t\t\t\tcell.parentNode.animate([\n\t\t\t\t\t//keyframe\n\t\t\t\t\t\t{transform: 'rotateY(0deg)'},\n\t\t\t\t\t\t{transform: 'rotateY(90deg)'},\n\t\t\t\t\t\t{transform: 'rotateY(0deg)'}\n\t\t\t\t\t],{\n\t\t\t\t\t//parametro\n\t\t\t\t\t\tduration: 748\n\t\t\t\t\t});\n\t\t\t\t\tcell.parentNode.style.backgroundColor = \"var(--warning)\"\n\t\t\t\t\tdocument.getElementById(\"Tecla\"+curResp[aux]).style.backgroundColor = \"var(--warning)\"\n\t\t\t\t\tbreak;\n\t\t\t\t}else{\n\t\t\t\t\t//execução para quando a letra não existe na chave;\n\t\t\t\t\tcell.parentNode.animate([\n\t\t\t\t\t//keyframe\n\t\t\t\t\t\t{transform: 'rotateY(0deg)'},\n\t\t\t\t\t\t{transform: 'rotateY(90deg)'},\n\t\t\t\t\t\t{transform: 'rotateY(0deg)'}\n\t\t\t\t\t],{\n\t\t\t\t\t//parametro\n\t\t\t\t\t\tduration: 748\n\t\t\t\t\t});\n\t\t\t\t\tcell.parentNode.style.backgroundColor = \"var(--gray)\"\n\t\t\t\t\tdocument.getElementById(\"Tecla\"+curResp[aux]).style.backgroundColor = \"var(--gray)\"\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t}\t\n\t}\n\tif(count==5){\n\t\tacerto = true;\n\t}\n\tencerraPartida();\n\tcurResp.fill(\"\")\n\tpos = 0;\n\tlinha++;\n}\n\nfunction encerraPartida(){\n\tif(linha+1 == 6){\n\t\terro = true;\n\t\tlinha++\n\t}\n\t\n\tif(acerto != true && erro != true){\n\t\treturn;\n\t}\n\t\n\tvar modal = document.getElementById(\"modal\");\n\tvar close = document.getElementsByClassName(\"close\");\n\t\n\tif(acerto){\n\t\tdocument.getElementById(\"label\").innerHTML = \"Sucesso\";\n\t\tdocument.getElementById(\"label\").style.visibility = \"visible\";\n\t\tdb.sVitoria++\n\t\tif(db.sVitoria > db.mSequencia){\n\t\t\tdb.mSequencia++;\n\t\t}\n\t}else{\n\t\tdocument.getElementById(\"label\").innerHTML = \"Resposta: \"+atual.chave;\n\t\tdocument.getElementById(\"label\").style.visibility = \"visible\";\n\t\tdb.sVitoria = 0;\n\t}\n\twindow.removeEventListener(\"keydown\",escrita,true)\n\t\n\tdb.tentativas[linha]++\n\tdb.Totaljogos++;\n\t\n\tsalvaDB()\n\t\n\tmodal.style.display = \"block\";\t\t\n}\n\nfunction mostraPlacar(){\n\tlet modal = document.getElementById(\"modal\")\n\t\n\tmodal.style.display = \"block\";\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "dangerousExampleEn": "1. var danger = localStorage.getItem(\"some\");\n2. \n3. eval(danger);\nLine 2: Unvalidated data is sent to a web browser.", "safeExampleEn": "1. var danger = localStorage.getItem(\"some\");\n2. var safe = filter(danger);\n3. eval(safe);\nLine 2: Filter the data, and then, send it to the browser.", "contexts": [{"lineNo": 39, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "getItem"}}, {"lineNo": 61, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "="}}]}} {"id": "70d58beeeb293c91cc25f8e5ef98447236c4b149e702872fa0f59e468afbd4b6", "license": {"spdx": ["MIT"], "repo": "ian13456/cube-wars", "path": "js/setup/gamemode.js", "repo_head_hexsha": "2d4308601e58ae36f093ed836a629f4690fdad3f", "stack_hexsha": "1d2081e6ddae6f2b07b525ca5e491e526b6f0614", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Cross-site scripting", "issueDescriptionEn": "The Cross-site scripting checker finds instances in which unvalidated data is sent to a web browser.\nlocalStorage can be manipulated by other applications. Therefore, if unvalidated data of localStorage is allowed for page generation, attackers can inject malicious scripts into pages.\nThis vulnerability lets attackers take over a user's cookie, session, or other information or execute an abnormal function. You can optionally specify functions that perform the respective roles of receiving, using, warning of, and filtering external inputs.\nMake sure that data is filtered if needed.", "issueLineNumber": 21, "entireCode": "const switchButtonDOM = document.getElementById('gamemode')\nconst godModeDOM = document.getElementById('god-mode')\n\nconst EASY = 'EASY'\nconst REGULAR = 'REGULAR'\nconst HARD = 'HARD'\n\nconst ON = 'ON'\nconst OFF = 'OFF'\n\nconst possibilities = [EASY, REGULAR, HARD]\nlet index = 0\n\nconst godPossibilities = [OFF, ON]\nlet godIndex = 0\n\nconst difficulty = localStorage.getItem('gamemode')\nif (!difficulty) localStorage.setItem('gamemode', EASY)\nelse {\n index = possibilities.findIndex(ele => ele === difficulty)\n switchButtonDOM.innerHTML = difficulty\n}\n\nconst godMode = localStorage.getItem('god-mode')\nif (!godMode) localStorage.setItem('god-mode', OFF)\nelse {\n godIndex = godPossibilities.findIndex(ele => ele === godMode)\n godModeDOM.innerHTML = godMode\n}\n\nswitchButtonDOM.onclick = () => {\n index++\n if (index >= possibilities.length) {\n index = 0\n }\n\n const diff = possibilities[index]\n localStorage.setItem('gamemode', diff)\n\n switchButtonDOM.innerHTML = diff\n}\n\ngodModeDOM.onclick = () => {\n godIndex++\n if (godIndex >= godPossibilities.length) {\n godIndex = 0\n }\n\n const godMode1 = godPossibilities[godIndex]\n localStorage.setItem('god-mode', godMode1)\n\n godModeDOM.innerHTML = godMode1\n}", "dangerousExampleEn": "1. var danger = localStorage.getItem(\"some\");\n2. \n3. eval(danger);\nLine 2: Unvalidated data is sent to a web browser.", "safeExampleEn": "1. var danger = localStorage.getItem(\"some\");\n2. var safe = filter(danger);\n3. eval(safe);\nLine 2: Filter the data, and then, send it to the browser.", "contexts": [{"lineNo": 17, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "getItem"}}, {"lineNo": 17, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 21, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "="}}]}} {"id": "15d58fc1b165d39b91942f7403154acfed00c07d16c5dfc6c8a37add48069149", "license": {"spdx": ["MIT"], "repo": "jenniferkong/jenniferkong.github.io", "path": "00/PUI Assignments/assgn6/main.js", "repo_head_hexsha": "b70c83d37ddf3b796fe4bb3b6f4ef9e45b3e9fab", "stack_hexsha": "b131b146ce641e440191d81a704a72ab698e814b", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Cross-site scripting", "issueDescriptionEn": "The Cross-site scripting checker finds instances in which unvalidated data is sent to a web browser.\nlocalStorage can be manipulated by other applications. Therefore, if unvalidated data of localStorage is allowed for page generation, attackers can inject malicious scripts into pages.\nThis vulnerability lets attackers take over a user's cookie, session, or other information or execute an abnormal function. You can optionally specify functions that perform the respective roles of receiving, using, warning of, and filtering external inputs.\nMake sure that data is filtered if needed.", "issueLineNumber": 131, "entireCode": "function bun(flavor, glaze, quantity, price) {\n this.flavor = flavor;\n this.glaze = glaze;\n this.quantity = quantity;\n this.price = price;\n}\n\nvar cart = [];\nvar newItemQuantity = 0;\n\n// for 6b\n// function addToCart(){\n// console.log(\"add to cart is running\")\n// var newFlavor = document.getElementById(\"flavor\");\n// var newGlaze = addItemToCartGlaze();\n// var newQuantity = addItemToCartQuantity();\n// var newPrice = addItemToCartPrice();\n// console.log(cart.push(bun(newFlavor, newGlaze, newQuantity, newPrice)))\n// return cart.push(bun(newFlavor, newGlaze, newQuantity, newPrice));\n// }\n\n// function addItemToCartQuantity(){\n// console.log(\"add to addItemToCartQuantity is running\");\n// var quantityDiv = document.getElementByID(\"quantity\");\n// var inputs = quantityDiv.getElementsByTagName(\"input\");\n// for (var quantitySelection=0; quantitySelection 0){\n //if quantity is more than 0, i want to update it\n var x = document.getElementById(\"amtInCart\");\n // changing the html doc x to quantity\n var storeCart = localStorage.setItem(\"amount\",quantity);\n //storing my stuff so i can refresh and keep my content\n var quantity2 = localStorage.getItem(\"amount\");\n //retreiving my content to be assigned as quantity2\n quantity = quantity2;\n // referring to my html doc and naming the default 0 as x\n x.innerHTML = quantity;\n //assigning quantity to quantity2\n console.log(quantity2, \"quantity2\");\n\n return quantity2;\n }\n}\n\n// function storeCart(quantity) {\n// console.log(\"storeCart works\");\n// var storeCart = localStorage.setItem(\"amount\",quantity);\n// console.log(\"storeCart\", quantity);\n// return storeCart;\n// }\n\n//uncomment this to clear !!\n// function clearCart(quantity){\n// localStorage.setItem(\"amount\",0);\n// displayValue=0;\n// displayCartInHTML();\n// }\n//things i'm missing\n//shopping cart (need to display, fix css)\n//\n// refresh but keep everything aka local storage\n\n//onload\nconsole.log(\"javascript is reading\")\nconsole.log(cart)", "dangerousExampleEn": "1. var danger = localStorage.getItem(\"some\");\n2. \n3. eval(danger);\nLine 2: Unvalidated data is sent to a web browser.", "safeExampleEn": "1. var danger = localStorage.getItem(\"some\");\n2. var safe = filter(danger);\n3. eval(safe);\nLine 2: Filter the data, and then, send it to the browser.", "contexts": [{"lineNo": 121, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "121"}}, {"lineNo": 127, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "getItem"}}, {"lineNo": 127, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 129, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 131, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "="}}]}} {"id": "0b88d36e99ed0171f496db45d6b3b584e495a791d9a5602bf9b9860b48cffcdf", "license": {"spdx": ["MIT"], "repo": "417946/wanli", "path": "action/upload_action.js", "repo_head_hexsha": "27f854caed64c7565f171a1b944f0dd104383147", "stack_hexsha": "5655be20aff3c18a06bfad22fe89c74ece6f26c6", "match": "repo_path"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Path Traversal", "issueDescriptionEn": "When unverified external inputs are used to access system resources, attackers can manipulate the input values to access resources protected by the system, which lead to create vulnerability. Attackers can exploit this to modify or delete resources, leak system information, and cause service failure due to the conflicts between system resources.\nEnsure to use predefined identifiers only or filter out characters vulnerable to path traversal, i.e.\n/, , ., when you need to use the external input to refer to the system resources including a file or socket port.", "issueLineNumber": 17, "entireCode": "/**\n * Created by zoey on 2015/6/26.\n */\nvar response = require('../routes/common/response');\nvar fs \t\t = require('fs');\nvar path \t = require('path');\nvar config = require('../config').config;\n/**\n * 上传模块\n **/\nexports.upload_img = function(req, res) {\n var callback=null;\n // Parse file.\n if(req.files) {\n var file=req.files.img;\n // Read file.\n fs.readFile(file.path, function (err, data) {\n var name=new Date().getTime()+'.'+file.name.split('\\.')[1];\n console.log(config.upload_talk_dir);\n var p = path.join(config.upload_talk_dir, name);\n // Save file.\n fs.writeFile(p, data, 'utf8', function (err) {\n if (err) {\n console.log(err)\n return res.json(response.buildError('Something went wrong!'));\n } else {\n// res.json(response.buildOK('/uploads/'+p));\n var up_img='http://172.16.17.328:5000/upload/talk/img/'+name;\n return res.json(response.buildOK(up_img));\n }\n });\n });\n }\n};\nexports.upload_voice = function(req, res) {\n var callback=null;\n // Parse file.\n if(req.files) {\n var file=req.files.voice;\n // Read file.\n fs.readFile(file.path, function (err, data) {\n var name=new Date().getTime()+'.'+file.name.split('\\.')[1];\n console.log(config.upload_talk_voice_dir);\n var p = path.join(config.upload_talk_voice_dir, name);\n // Save file.\n fs.writeFile(p, data, 'utf8', function (err) {\n if (err) {\n console.log(err)\n return res.json(response.buildError('Something went wrong!'));\n } else {\n// res.json(response.buildOK('/uploads/'+p));\n var up_voice='http://192.168.127.12:5000/upload/talk/voice/'+name;\n return res.json(response.buildOK(up_voice));\n }\n });\n });\n }\n};", "dangerousExampleEn": "1. const path = require('path');\n2. const fs = require('fs');\n3. \n4. router.post('/Path', function (req, res) {\n5. const content = req.body.content;\n6. const BASE_DIR = 'C:/';\n7. \n8. fs.readFile(path.resolve(BASE_DIR,content), 'utf-8', function (err, data){\n9. if(err){\n10. console.log(err);\n11. }else{\n12. return res.send({data: data});\n13. }\n14. });\n15. });\nLine 8: This is vulnerable to path traversal because an external input is used without proper verification.", "safeExampleEn": "1. const path = require('path');\n2. const fs = require('fs');\n3. \n4. router.post('/Path', function (req, res) {\n5. const content = req.body.content;\n6. const BASE_DIR = 'C:/';\n7. \n8. const safe_content = content.replace(/[\\\\\\/]/gi, \"\");\n9. \n10. fs.readFile(path.resolve(BASE_DIR, safe_content), 'utf-8', function (err, data) {\n11. if (err) {\n12. console.log(err);\n13. return res.send({data: \"This is an invalid input.\"});\n14. } else {\n15. return res.send({data: data});\n16. }\n17. });\n18. });\nLine 10: This is secure because insecure characters are filtered using a regular expression.", "contexts": [{"lineNo": 14, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "14"}}, {"lineNo": 15, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "req"}}, {"lineNo": 17, "eventType": "sink", "messageKey": "jschk.PATH_CONTAMINATION.JS.defect.sink", "params": {}}]}} {"id": "cde63d80016dde1168d902753a63046163844249bdd61a09262f5b8b7982a04b", "license": {"spdx": ["MIT"], "repo": "chiragmakkar/Smart-India-Hackathon-18", "path": "routes/consumer.js", "repo_head_hexsha": "8ea2f6f9f1d01f09d1051c51f5ba097bdb540035", "stack_hexsha": "05fdb5e8ef4e5b5df1980609a867590cf33927ba", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Path Traversal", "issueDescriptionEn": "When unverified external inputs are used to access system resources, attackers can manipulate the input values to access resources protected by the system, which lead to create vulnerability. Attackers can exploit this to modify or delete resources, leak system information, and cause service failure due to the conflicts between system resources.\nEnsure to use predefined identifiers only or filter out characters vulnerable to path traversal, i.e.\n/, , ., when you need to use the external input to refer to the system resources including a file or socket port.", "issueLineNumber": 41, "entireCode": "const express = require('express')\nconst router = express.Router()\nconst mongoose = require('mongoose')\nconst multer = require('multer')\nconst fs = require('fs')\nconst auth = require(__base + 'modules/auth/protect.js')\nconst path = require('path')\nconst consumer = require('../models/consumer').consumer\nconst storage=multer.diskStorage({\n destination:'./uploads/',\n filename:(req,file,cb)=>{\n cb(null,new Date().toISOString()+ file.originalname);\n }\n });\n \nconst upload=multer({storage: storage});\n\n//Saving New Application Data In mongoosegoDb\nrouter.post('/new', auth, require(__base + 'modules/forms/newCon.js'))\n\n//My connections\nrouter.post('/mycon', auth, require('../modules/forms/myCon'))\n\n//Update Connection\nrouter.post('/update', auth, require('../modules/forms/updateCon'))\n\n//Track Connection\nrouter.post('/track', auth, require('../modules/forms/track'))\n\n//testing part\nrouter.put('/transfer', auth, require(__base + 'modules/forms/transferCon.js'))\n\n//for closure of connection\nrouter.patch('/closure', auth, require(__base + 'modules/forms/closeCon.js'))\n\n//for deleting connection\nrouter.delete('/delete', auth, require(__base + 'modules/forms/deleteCon.js'))\n\nrouter.post('/uploadDoc',upload.single('documentImage'),(req,res)=>{\n extn = path.extname(req.file.path)\n fs.readFile(req.file.path, function(err, data){\n if(err) console.log(err)\n\n else{\n url = \"https://s3.ap-south-1.amazonaws.com/sih-2018/\" + require('../modules/misc/uploadToS3')(data, extn)\n consumer.findOneAndUpdate({\"ApplicationID\":req.body.applicationId}, {\n $set:{\n \"consumerDetails\":{\n \"docUrl\":url\n }\n }\n })\n res.send(url)\n }\n })\n});\n\nmodule.exports = router;", "dangerousExampleEn": "1. const path = require('path');\n2. const fs = require('fs');\n3. \n4. router.post('/Path', function (req, res) {\n5. const content = req.body.content;\n6. const BASE_DIR = 'C:/';\n7. \n8. fs.readFile(path.resolve(BASE_DIR,content), 'utf-8', function (err, data){\n9. if(err){\n10. console.log(err);\n11. }else{\n12. return res.send({data: data});\n13. }\n14. });\n15. });\nLine 8: This is vulnerable to path traversal because an external input is used without proper verification.", "safeExampleEn": "1. const path = require('path');\n2. const fs = require('fs');\n3. \n4. router.post('/Path', function (req, res) {\n5. const content = req.body.content;\n6. const BASE_DIR = 'C:/';\n7. \n8. const safe_content = content.replace(/[\\\\\\/]/gi, \"\");\n9. \n10. fs.readFile(path.resolve(BASE_DIR, safe_content), 'utf-8', function (err, data) {\n11. if (err) {\n12. console.log(err);\n13. return res.send({data: \"This is an invalid input.\"});\n14. } else {\n15. return res.send({data: data});\n16. }\n17. });\n18. });\nLine 10: This is secure because insecure characters are filtered using a regular expression.", "contexts": [{"lineNo": 41, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "req"}}, {"lineNo": 41, "eventType": "sink", "messageKey": "jschk.PATH_CONTAMINATION.JS.defect.sink", "params": {}}]}} {"id": "7e1707ad2781bc28903db283715e25ca2980e0f2275e81f170e16bc54e3195ab", "license": {"spdx": ["MIT"], "repo": "JockerChen/test", "path": "node/node-mysql.js", "repo_head_hexsha": "2837fc1e09e1b8b49774497f8ae9ca586e1b1206", "stack_hexsha": "1323da2992695264a10fc7b0e6d99a69d098ea13", "match": "repo_path"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Path Traversal", "issueDescriptionEn": "When unverified external inputs are used to access system resources, attackers can manipulate the input values to access resources protected by the system, which lead to create vulnerability. Attackers can exploit this to modify or delete resources, leak system information, and cause service failure due to the conflicts between system resources.\nEnsure to use predefined identifiers only or filter out characters vulnerable to path traversal, i.e.\n/, , ., when you need to use the external input to refer to the system resources including a file or socket port.", "issueLineNumber": 49, "entireCode": "/*\n * @Author: [JokerChen]\n * @Date: 2020-11-30 15:28:36\n * @LastEditors: [JokerChen]\n * @LastEditTime: 2020-12-10 15:16:32\n * @Description: 测试之前的服务端的相关内容,尝试进行编写相应的接口\n */\nconst fs = require('fs');\nconst mysql = require('mysql');\n//进行注册MYSQL(数据库连接层)\nlet db = mysql.createPool({\n host: 'localhost',\n port: 3306,\n user: 'root',\n password: '',\n database: 'test',\n maxConnection: 10\n})\nconst http = require('http');\nconst url = require('url');\nlet httpServer = http.createServer((req, res) => {\n let { pathname, query } = url.parse(req.url, true);\n let { username, password } = query;\n if (pathname == '/reg') {\n //注册接口\n let querySql = `select * from user_table where username='${username}'`;\n db.query(querySql, (err, json) => {\n if (err) {\n console.log('查询错误');\n res.writeHead('500');\n res.write('{\"code\":200,\"message\":\"数据查询信息错误\"}');\n res.end();\n }\n else {\n //此处处理功能\n }\n });\n console.log('注册功能');\n res.writeHead('200', '注册成功');\n res.end();\n }\n else if (pathname == '/login') {\n //登录功能\n console.log('登录功能');\n res.writeHead('200', '登录功能');\n res.end();\n }\n else {\n fs.readFile(`html${req.url}`, (err, data) => {\n if (err) {\n res.writeHead(404);\n console.log(\"读取文件错误\");\n }\n })\n }\n})\n//服务监听80端口\nhttp.listen('8080');\n//对应的相应的后台接口相应的回复\n", "dangerousExampleEn": "1. const path = require('path');\n2. const fs = require('fs');\n3. \n4. router.post('/Path', function (req, res) {\n5. const content = req.body.content;\n6. const BASE_DIR = 'C:/';\n7. \n8. fs.readFile(path.resolve(BASE_DIR,content), 'utf-8', function (err, data){\n9. if(err){\n10. console.log(err);\n11. }else{\n12. return res.send({data: data});\n13. }\n14. });\n15. });\nLine 8: This is vulnerable to path traversal because an external input is used without proper verification.", "safeExampleEn": "1. const path = require('path');\n2. const fs = require('fs');\n3. \n4. router.post('/Path', function (req, res) {\n5. const content = req.body.content;\n6. const BASE_DIR = 'C:/';\n7. \n8. const safe_content = content.replace(/[\\\\\\/]/gi, \"\");\n9. \n10. fs.readFile(path.resolve(BASE_DIR, safe_content), 'utf-8', function (err, data) {\n11. if (err) {\n12. console.log(err);\n13. return res.send({data: \"This is an invalid input.\"});\n14. } else {\n15. return res.send({data: data});\n16. }\n17. });\n18. });\nLine 10: This is secure because insecure characters are filtered using a regular expression.", "contexts": [{"lineNo": 42, "eventType": "source", "messageKey": "synz.COMMON.branch.false.assumed", "params": {"arg0": "48"}}, {"lineNo": 49, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "req"}}, {"lineNo": 49, "eventType": "sink", "messageKey": "jschk.PATH_CONTAMINATION.JS.defect.sink", "params": {}}]}} {"id": "060a97f292f9c9fbb6a3cbc2fb5a669c4725ad4fd83c7beda5ff7f69afafc562", "license": {"spdx": ["Apache-2.0"], "repo": "iisys-hof/Pippa-Backend", "path": "index.js", "repo_head_hexsha": "928b4dc614a4ac6237980c1c5af59b94a502f3f8", "stack_hexsha": "aeb8144dbfc8ee748d9dd7eb50d47abfce47aada", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Path Traversal", "issueDescriptionEn": "When unverified external inputs are used to access system resources, attackers can manipulate the input values to access resources protected by the system, which lead to create vulnerability. Attackers can exploit this to modify or delete resources, leak system information, and cause service failure due to the conflicts between system resources.\nEnsure to use predefined identifiers only or filter out characters vulnerable to path traversal, i.e.\n/, , ., when you need to use the external input to refer to the system resources including a file or socket port.", "issueLineNumber": 84, "entireCode": "// Absolutely minimal backend implementation for Pippa to serve the Json-files\n// created and utilized as config files. Listens on 8000. Starts with 'node index.js'\n\n// import/set up express framework and it's middleware to execute special tasks\nconst express = require('express');\nconst cors = require('cors')\nconst bodyParser = require('body-parser');\nconst app = express();\napp.use(cors());\napp.use(bodyParser.json());\n\n// import os library for home directory access\nconst os = require('os');\n\n// import node library for filesystem access\nvar fs = require('fs');\n\n//start express server\napp.listen(8000, () => {\n console.log('Pippa Backend Server started!');\n});\n\n// following are route declarations that represent the api under which this server is reachable\n\n// get the main configuration file\napp.route('/api/mainConfig').get((req, res) => {\n\n fs.readFile(os.homedir() + '\\\\Desktop\\\\MainConfig\\\\mainconf.json', 'utf8', function (err, data) {\n if (err) {\n console.error('Could not send Main Configuration');\n console.error(err.stack);\n res.status(500).send();\n } else {\n res.send(data);\n console.log('Sent Main Configuration.');\n }\n });\n});\n\n// set the main configuration file\napp.route('/api/mainConfig').post((req, res) => {\n\n fs.writeFile(os.homedir() + '\\\\Desktop\\\\MainConfig\\\\mainconf.json', JSON.stringify(req.body), 'utf8', function (err, data) {\n if (err) {\n console.error('Could not store Main Configuration');\n console.error(err.stack);\n res.status(500).send();\n } else {\n res.status(200).send(req.body);\n console.log('Stored Main Configuration.');\n }\n });\n});\n\n// get a list of all currently installed skills\n// do so by checking in all filenames from skill config folder\napp.route('/api/skills').get((req, res) => {\n\n fs.readdir(os.homedir() + '\\\\Desktop\\\\SkillConfig', function (err, data) {\n if (err) {\n console.error('Could not retrieve Skill Config folder content');\n console.error(err.stack);\n res.status(500).send();\n } else {\n\n //todo check out for real skill-names which might be a little clunky\n for (var i = 0; i < data.length; i++) {\n noFileEnding = data[i].substring(0, data[i].lastIndexOf('.'))\n fileName = noFileEnding.substring(noFileEnding.lastIndexOf('.') + 1, noFileEnding.length + 1);\n data[i] = {label: fileName, value: noFileEnding};\n }\n\n res.status(200).send(data);\n console.log('Sent Skill List. ' + data.length + ' entries.')\n }\n });\n});\n\n// get the config file for a single skill\napp.route('/api/skills/:name').get((req, res) => {\n\n const requestedSkillName = req.params['name'];\n\n fs.readFile(os.homedir() + '\\\\Desktop\\\\SkillConfig\\\\' + requestedSkillName + '.json', 'utf8', function (err, data) {\n if (err) {\n console.error('Could not send Skill Config. ' + requestedSkillName);\n console.error(err.stack);\n res.status(500).send();\n } else {\n res.status(200).send(data);\n console.log('Sent Skill Config. ' + requestedSkillName)\n }\n });\n});\n\n// set the config file for a single skill\napp.route('/api/skills/:name').post((req, res) => {\n\n const requestedSkillName = req.params['name'];\n\n if (requestedSkillName != null && requestedSkillName != \"\" && requestedSkillName != \"null\") {\n\n fs.writeFile(os.homedir() + '\\\\Desktop\\\\SkillConfig\\\\' + requestedSkillName + '.json', JSON.stringify(req.body), 'utf8', function (err, data) {\n if (err) {\n console.error('Could not set Skill Config. ' + requestedSkillName);\n console.error(err.stack);\n res.status(500).send();\n } else {\n res.status(200).send(req.body);\n console.log('Stored Skill Config. ' + requestedSkillName)\n }\n });\n } else {\n console.error('Could not set Skill Config. ' + requestedSkillName);\n res.status(500).send();\n }\n});", "dangerousExampleEn": "1. const path = require('path');\n2. const fs = require('fs');\n3. \n4. router.post('/Path', function (req, res) {\n5. const content = req.body.content;\n6. const BASE_DIR = 'C:/';\n7. \n8. fs.readFile(path.resolve(BASE_DIR,content), 'utf-8', function (err, data){\n9. if(err){\n10. console.log(err);\n11. }else{\n12. return res.send({data: data});\n13. }\n14. });\n15. });\nLine 8: This is vulnerable to path traversal because an external input is used without proper verification.", "safeExampleEn": "1. const path = require('path');\n2. const fs = require('fs');\n3. \n4. router.post('/Path', function (req, res) {\n5. const content = req.body.content;\n6. const BASE_DIR = 'C:/';\n7. \n8. const safe_content = content.replace(/[\\\\\\/]/gi, \"\");\n9. \n10. fs.readFile(path.resolve(BASE_DIR, safe_content), 'utf-8', function (err, data) {\n11. if (err) {\n12. console.log(err);\n13. return res.send({data: \"This is an invalid input.\"});\n14. } else {\n15. return res.send({data: data});\n16. }\n17. });\n18. });\nLine 10: This is secure because insecure characters are filtered using a regular expression.", "contexts": [{"lineNo": 82, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "req__sparrow_node_js_url_request__.params"}}, {"lineNo": 84, "eventType": "sink", "messageKey": "jschk.PATH_CONTAMINATION.JS.defect.sink", "params": {}}]}} {"id": "cde5eb334273faabaaeaf729d40cd0af2488f166cdf8d77982bb248317b239e4", "license": {"spdx": ["MIT"], "repo": "paratagas/node-websockets-chat", "path": "index.js", "repo_head_hexsha": "6225023511e3d5502af60cfe36b69104beea4a80", "stack_hexsha": "a1d427305c09ba5bc3df34f7ed1e3775cae96d30", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Path Traversal", "issueDescriptionEn": "When unverified external inputs are used to access system resources, attackers can manipulate the input values to access resources protected by the system, which lead to create vulnerability. Attackers can exploit this to modify or delete resources, leak system information, and cause service failure due to the conflicts between system resources.\nEnsure to use predefined identifiers only or filter out characters vulnerable to path traversal, i.e.\n/, , ., when you need to use the external input to refer to the system resources including a file or socket port.", "issueLineNumber": 17, "entireCode": "const errorHandler = require('./server/errorHandler');\nconst extractFilePath = require('./extractFilePath');\nconst fs = require('fs');\nconst http = require('http');\nconst mime = require('mime');\nconst wss = require('./server/websockets-server');\n\nconst server = http.createServer((req, res) => {\n console.log('Responding to a request');\n\n const filePath = extractFilePath(req.url);\n const mimeType = mime.getType(req.url) || 'text/html';\n\n // console.log(`The req.url is: $ { req.url }`);\n // console.log(`The mimeType is: $ { mimeType }`);\n \n fs.readFile(filePath, (err, data) => {\n if (err) {\n errorHandler(err, res);\n return;\n } else {\n res.setHeader('Content-Type', mimeType);\n res.end(data);\n }\n });\n});\n\nserver.listen(3000);", "dangerousExampleEn": "1. const path = require('path');\n2. const fs = require('fs');\n3. \n4. router.post('/Path', function (req, res) {\n5. const content = req.body.content;\n6. const BASE_DIR = 'C:/';\n7. \n8. fs.readFile(path.resolve(BASE_DIR,content), 'utf-8', function (err, data){\n9. if(err){\n10. console.log(err);\n11. }else{\n12. return res.send({data: data});\n13. }\n14. });\n15. });\nLine 8: This is vulnerable to path traversal because an external input is used without proper verification.", "safeExampleEn": "1. const path = require('path');\n2. const fs = require('fs');\n3. \n4. router.post('/Path', function (req, res) {\n5. const content = req.body.content;\n6. const BASE_DIR = 'C:/';\n7. \n8. const safe_content = content.replace(/[\\\\\\/]/gi, \"\");\n9. \n10. fs.readFile(path.resolve(BASE_DIR, safe_content), 'utf-8', function (err, data) {\n11. if (err) {\n12. console.log(err);\n13. return res.send({data: \"This is an invalid input.\"});\n14. } else {\n15. return res.send({data: data});\n16. }\n17. });\n18. });\nLine 10: This is secure because insecure characters are filtered using a regular expression.", "contexts": [{"lineNo": 2, "eventType": "source", "messageKey": "synz.COMMON.value.returned.from", "params": {"arg0": "require"}}, {"lineNo": 2, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 2, "eventType": "source", "messageKey": "synz.COMMON.called", "params": {"arg0": "require"}}, {"lineNo": 11, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "req"}}, {"lineNo": 17, "eventType": "sink", "messageKey": "jschk.PATH_CONTAMINATION.JS.defect.sink", "params": {}}]}} {"id": "4d586fe869adab9cb6e1ac63aea110f8fd36b95b69d26054adf333c36d06e98d", "license": {"spdx": ["Unlicense"], "repo": "normanlol/altify", "path": "index.js", "repo_head_hexsha": "bd779929d869a64d7e884bfed1e2561caca68a3f", "stack_hexsha": "ce9ac0c50bead6fadc324d03d1feca4d0fb03f8f", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Path Traversal", "issueDescriptionEn": "When unverified external inputs are used to access system resources, attackers can manipulate the input values to access resources protected by the system, which lead to create vulnerability. Attackers can exploit this to modify or delete resources, leak system information, and cause service failure due to the conflicts between system resources.\nEnsure to use predefined identifiers only or filter out characters vulnerable to path traversal, i.e.\n/, , ., when you need to use the external input to refer to the system resources including a file or socket port.", "issueLineNumber": 15, "entireCode": "const http = require(\"http\");\nconst fs = require(\"fs\");\nconst gmailnator = require(\"gmailnator\");\nconst cheerio = require(\"cheerio\");\nconst utils = require(\"./utils\");\nconst { parse } = require(\"url\");\nconst port = process.env.PORT || 2345\n\nhttp.createServer(requestListener).listen(port);\nconsole.log(\"listening on port \" + port)\n\nfunction requestListener(request, response) {\n var url = parse(request.url, true);\n if (fs.existsSync(__dirname + \"/web/static\" + url.pathname + \"index.html\")) {\n fs.readFile(__dirname + \"/web/static\" + url.pathname + \"index.html\", function (err, resp) {\n if (err) {\n if (err.stack) {var txt = err.stack;}\n else if (err.message) {var txt = err.message;}\n else if (err.code) {var txt = err.code;}\n else if (err) {var txt = err;}\n response.writeHead(500, {\n \"Content-Type\": \"text/plain\"\n });\n response.end(txt);\n } else {\n response.writeHead(200, {\n \"Content-Type\": \"text/html\"\n });\n response.end(resp);\n }\n });\n } else if (fs.existsSync(__dirname + \"/web/static\" + url.pathname)) {\n fs.readFile(__dirname + \"/web/static\" + url.pathname, function (err, resp) {\n if (err) {\n if (err.stack) {var txt = err.stack;}\n else if (err.message) {var txt = err.message;}\n else if (err.code) {var txt = err.code;}\n else if (err) {var txt = err;}\n response.writeHead(500, {\n \"Content-Type\": \"text/plain\"\n });\n response.end(txt);\n } else {\n response.writeHead(200, {\n \"Content-Type\": contentType(url.pathname)\n });\n response.end(resp);\n }\n });\n } else {\n var pathClean = url.pathname.split(\"/\").slice(1);\n var path = url.pathname;\n switch(pathClean[0]) {\n case \"gen\":\n gmailnator.generateEmail(function(err, resp) {\n if (err) {\n if (err.stack) {var txt = err.stack;}\n else if (err.message) {var txt = err.message;}\n else if (err.code) {var txt = err.code;}\n else if (err) {var txt = err;}\n response.writeHead(500, {\n \"Content-Type\": \"text/plain\"\n });\n response.end(txt);\n } else {\n response.writeHead(200, {\n \"Content-Type\": \"text/plain\"\n });\n response.end(resp);\n }\n })\n return;\n\n case \"check\":\n if (pathClean[1]) {\n gmailnator.checkEmails(pathClean[1], function(err, resp) {\n if (err) {\n if (err.stack) {var txt = err.stack;}\n else if (err.message) {var txt = err.message;}\n else if (err.code) {var txt = err.code;}\n else if (err) {var txt = err;}\n response.writeHead(500, {\n \"Content-Type\": \"text/plain\"\n });\n response.end(txt);\n } else {\n response.writeHead(200, {\n \"Content-Type\": \"application/json\"\n });\n response.end(JSON.stringify(resp));\n }\n })\n } else {\n response.writeHead(302, {\n \"Location\": \"/\"\n });\n response.end();\n }\n return;\n\n case \"read\":\n if (url.query.link && url.query.csrf) {\n gmailnator.getMessage(atob(url.query.link), url.query.csrf, function(err, resp) {\n if (err) {\n if (err.stack) {var txt = err.stack;}\n else if (err.message) {var txt = err.message;}\n else if (err.code) {var txt = err.code;}\n else if (err) {var txt = err;}\n response.writeHead(500, {\n \"Content-Type\": \"text/plain\"\n });\n response.end(txt);\n } else {\n var $ = cheerio.load(resp);\n $(\"a\").attr(\"rel\", \"noreferrer nofollow\");\n response.writeHead(200, {\n \"Content-Type\": \"text/html\"\n });\n response.end($.html());\n }\n })\n } else {\n response.writeHead(302, {\n \"Location\": \"/\"\n });\n response.end();\n }\n return;\n\n case \"parse\":\n if (url.query.link && url.query.csrf) {\n gmailnator.getMessage(atob(url.query.link), url.query.csrf, function(err, resp) {\n if (err) {\n if (err.stack) {var txt = err.stack;}\n else if (err.message) {var txt = err.message;}\n else if (err.code) {var txt = err.code;}\n else if (err) {var txt = err;}\n response.writeHead(500, {\n \"Content-Type\": \"text/plain\"\n });\n response.end(txt);\n } else {\n if (!fs.existsSync(__dirname + \"/temp/\")) {fs.mkdirSync(__dirname + \"/temp/\");}\n var loc = __dirname + \"/temp/\" + randomId()\n fs.writeFile(loc, resp, function(err) {\n if (err !== null) {\n if (err.stack) {var txt = err.stack;}\n else if (err.message) {var txt = err.message;}\n else if (err.code) {var txt = err.code;}\n else if (err) {var txt = err;}\n response.writeHead(500, {\n \"Content-Type\": \"text/plain\"\n });\n response.end(txt);\n } else {\n utils.getVerify(loc, async function(err, resp) {\n if (err) {\n if (err.stack) {var txt = err.stack;}\n else if (err.message) {var txt = err.message;}\n else if (err.code) {var txt = err.code;}\n else if (err) {var txt = err;}\n response.writeHead(500, {\n \"Content-Type\": \"text/plain\"\n });\n response.end(txt);\n } else {\n var resp = JSON.stringify(resp);\n response.writeHead(200, {\n \"Content-Type\": \"application/json\"\n });\n response.end(resp);\n try {\n fs.unlinkSync(loc);\n } catch (error) {\n console.log(\"couldn't delete temp file: '\" + loc + \"' due to an error.\");\n console.log(error);\n }\n }\n })\n }\n })\n }\n })\n } else {\n response.writeHead(302, {\n \"Location\": \"/\"\n });\n response.end();\n }\n return;\n\n default:\n fs.readFile(__dirname + \"/web/dynamic/error/404.html\", function(err, resp) {\n if (err) {\n if (err.stack) {var txt = err.stack;}\n else if (err.message) {var txt = err.message;}\n else if (err.code) {var txt = err.code;}\n else if (err) {var txt = err;}\n response.writeHead(500, {\n \"Content-Type\": \"text/plain\"\n });\n response.end(txt);\n } else {\n response.writeHead(404, {\n \"Content-Type\": \"text/html\"\n });\n response.end(resp);\n }\n });\n return;\n }\n }\n}\n\nfunction contentType(file) {\n switch (file.split(\".\")[file.split(\".\").length - 1]) {\n case \"html\":\n return \"text/html\";\n case \"css\":\n return \"text/css\";\n case \"json\":\n return \"application/json\";\n case \"js\":\n return \"application/javascript\";\n case \"jpg\":\n return \"image/jpeg\";\n case \"png\":\n return \"image/png\";\n case \"gif\":\n return \"images/gif\";\n default:\n return \"text/plain\";\n }\n}\n\nfunction randomId() {\n var result = \"\";\n var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';\n for (var c = 0; c < 10; c++) {\n result += characters.charAt(Math.floor(Math.random() * characters.length));\n }\n return result;\n}\n\nfunction btoa(string) {\n return Buffer.from(string, \"utf-8\").toString(\"base64\");\n}\n\nfunction atob(string) {\n return Buffer.from(string, \"base64\").toString(\"utf-8\");\n}", "dangerousExampleEn": "1. const path = require('path');\n2. const fs = require('fs');\n3. \n4. router.post('/Path', function (req, res) {\n5. const content = req.body.content;\n6. const BASE_DIR = 'C:/';\n7. \n8. fs.readFile(path.resolve(BASE_DIR,content), 'utf-8', function (err, data){\n9. if(err){\n10. console.log(err);\n11. }else{\n12. return res.send({data: data});\n13. }\n14. });\n15. });\nLine 8: This is vulnerable to path traversal because an external input is used without proper verification.", "safeExampleEn": "1. const path = require('path');\n2. const fs = require('fs');\n3. \n4. router.post('/Path', function (req, res) {\n5. const content = req.body.content;\n6. const BASE_DIR = 'C:/';\n7. \n8. const safe_content = content.replace(/[\\\\\\/]/gi, \"\");\n9. \n10. fs.readFile(path.resolve(BASE_DIR, safe_content), 'utf-8', function (err, data) {\n11. if (err) {\n12. console.log(err);\n13. return res.send({data: \"This is an invalid input.\"});\n14. } else {\n15. return res.send({data: data});\n16. }\n17. });\n18. });\nLine 10: This is secure because insecure characters are filtered using a regular expression.", "contexts": [{"lineNo": 13, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 14, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "14"}}, {"lineNo": 15, "eventType": "sink", "messageKey": "jschk.PATH_CONTAMINATION.JS.defect.sink", "params": {}}]}} {"id": "d03d88ac36ede432b82b11ce99376308a2476487b0aff00c0c05e979b2b1076c", "license": {"spdx": ["MIT"], "repo": "deawar/SAG-MongoDB", "path": "controllers/file_upload_controller.js", "repo_head_hexsha": "cd29c2048b83d14178c31b583f5ca9cf5a19b819", "stack_hexsha": "f30a260e4ccbcc5e5ab1ef55dadb3f78a81c0231", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Path Traversal", "issueDescriptionEn": "When unverified external inputs are used to access system resources, attackers can manipulate the input values to access resources protected by the system, which lead to create vulnerability. Attackers can exploit this to modify or delete resources, leak system information, and cause service failure due to the conflicts between system resources.\nEnsure to use predefined identifiers only or filter out characters vulnerable to path traversal, i.e.\n/, , ., when you need to use the external input to refer to the system resources including a file or socket port.", "issueLineNumber": 199, "entireCode": "/* eslint-disable prefer-const */\n/* eslint-disable no-underscore-dangle */\n/* eslint-disable no-plusplus */\n/* eslint-disable camelcase */\nconst express = require('express');\nconst flash = require('express-flash-notification');\nconst bodyParser = require('body-parser');\nconst multer = require('multer');\nconst passport = require('passport');\nconst fs = require('fs');\nconst { ObjectId } = require('bson');\nconst Artwork = require('../models/artwork');\nconst School = require('../models/school');\nconst User = require('../models/user');\nconst Bid = require('../models/bid');\n\nconst app = express();\nrequire('../config/passport')(passport);\nconst helpers = require('../config/helpers');\nconst { checkAuthenticated } = require('../config/middleware/isAuthenticated');\nconst asyncMiddleware = require('../config/middleware/asyncMiddleware');\n\nconst router = express.Router();\napp.use(express.static(`${__dirname}/public`));\napp.use(flash());\napp.use(bodyParser.json());\napp.use(bodyParser.urlencoded({ extended: true }));\n\n// Find school Fx\nfunction findSchoolName(req) {\n // eslint-disable-next-line prefer-destructuring\n let school;\n // school = res.req.user.school;\n if (req.user === null || req.user === undefined) {\n school = 'Make Art, Have Fun!';\n return school;\n }\n // eslint-disable-next-line prefer-destructuring\n school = req.user.school;\n const uploadPath = `./public/upload/${school}/`;\n console.log('School: ', school);\n if (!fs.existsSync(uploadPath)) {\n fs.mkdirSync(uploadPath);\n }\n return school;\n}\n\n// Find Email Fx\nfunction findEmail(req) {\n // eslint-disable-next-line prefer-destructuring\n let email;\n if (req.user === null || req.user === undefined) {\n email = 'Not Found';\n return email;\n }\n // eslint-disable-next-line prefer-destructuring\n email = req.user.email;\n return email;\n}\n\n// Find Role Fx\nfunction findRole(req) {\n // eslint-disable-next-line prefer-destructuring\n let role;\n if (req.user === null || req.user === undefined) {\n role = 'Not Found';\n return role;\n }\n // eslint-disable-next-line prefer-destructuring\n role = req.user.role;\n if (role === 'student') {\n role = 'student';\n return role;\n }\n if (role === 'admin') {\n role = 'admin';\n return role;\n }\n role = 'bidder';\n return role;\n}\n\n// Set Query based on Role Fx\nfunction setQuery(req) {\n // eslint-disable-next-line prefer-destructuring\n let role;\n let query;\n if (req.user === null || req.user === undefined) {\n role = 'Not Found';\n return role;\n }\n // eslint-disable-next-line prefer-destructuring\n role = req.user.role;\n if (role === 'student') {\n query = { artist_email_input: findEmail(req) };\n return query;\n }\n if (role === 'admin') {\n // const query = { school: findSchoolName(req), approved: true };\n query = { school: findSchoolName(req) };\n return query;\n }\n role = 'bidder';\n query = { school: findSchoolName(req), approved: true };\n return query;\n}\n\n// Find first_name Fx\nfunction findFirstName(req) {\n // eslint-disable-next-line prefer-destructuring\n let first_name;\n if (req.user === null || req.user === undefined) {\n first_name = 'Your';\n return first_name;\n }\n // eslint-disable-next-line prefer-destructuring\n first_name = req.user.first_name;\n return first_name;\n}\n\n// get File ext/type\nfunction getFileType(file) {\n const splitfile = file.split('.');\n const getThisType = splitfile[splitfile.length - 1];\n return getThisType;\n}\n// Find Id\nfunction findId(req) {\n let reqvar;\n if (req.user === null || req.user === undefined) {\n reqvar = 'Not Available';\n return reqvar;\n }\n // eslint-disable-next-line no-underscore-dangle\n reqvar = req.user._id;\n return reqvar;\n}\n\nconst storage = multer.diskStorage({\n destination(req, file, cb) {\n cb(null, `./public/upload/${findSchoolName(req)}`);\n // cb(null, uploadPath);\n },\n // By default, multer removes file extensions so let's add them back\n filename(req, file, cb) {\n // cb(null, `${file.fieldname}-${Date.now()}${path.extname(file.originalname)}`);\n cb(null, `${findId(req)}-${file.originalname}`);\n },\n});\n\nconst upload = multer({\n storage,\n limits: { fileSize: 100000000 },\n fileFilter: helpers.imageFilter,\n}).single('sampleFile');\n\n// router.post('/upload', checkAuthenticated, upload.single('sampleFile'), (req, res) => {\nrouter.post('/upload', checkAuthenticated, upload, (req, res) => {\n console.log('====================================');\n console.log('Line 101---------->price_input sent in req.body.price_input: ', req.body.price_input);\n console.log('Line 102 ==>file_upload_controller req.body: ', req.body);\n console.log('Line 103 ===>File_upload_controller File res.files: ', req.files);\n console.log('Text fields sent with file-req.body: ', req.body);\n const school = findSchoolName(req);\n let _id;\n _id = findId(req);\n console.log('====================================');\n console.log('_id: ', _id);\n console.log('====================================');\n app.use(express.static(`public/upload/${findSchoolName(req)}`));\n console.log('line 113-->School: ', school);\n const uploadPath = `./public/upload/${school}/`;\n\n if (!fs.existsSync(uploadPath)) {\n fs.mkdirSync(uploadPath);\n }\n const first_name = findFirstName(req);\n console.log('line 129-->File_name: ', req.file.filename);\n const fileExt = getFileType(req.file.filename);\n console.log('line 131------>File Extension: ', fileExt);\n\n const displayPath = uploadPath;\n const newArtwork = new Artwork({\n artist_firstname_input: req.body.artist_firstname_input,\n artist_lastname_input: req.body.artist_lastname_input,\n artist_email_input: req.body.artist_email_input,\n art_name_input: req.body.art_name_input,\n depth: req.body.d_size_input,\n description_input: req.body.description_input,\n height: req.body.h_size_input,\n medium_input: req.body.medium_input,\n price: req.body.price_input,\n width: req.body.w_size_input,\n school: req.body.school_input,\n approved: req.body.approved,\n img: {\n // eslint-disable-next-line max-len\n // data: fs.readFileSync(path.join(`${__dirname}/public/upload/${findSchoolName(req)}/${findId(req)}-${req.file.originalname}`)),\n data: fs.readFileSync(`./public/upload/${findSchoolName(req)}/${findId(req)}-${req.file.originalname}`),\n contentType: `image/${fileExt}`,\n },\n });\n // newArtwork.create(newArtwork, (err, item) => {\n // if (err) {\n console.log('+++++++++++++++++++>Line 156 newArtwork: ', newArtwork);\n const uploadedArtwork = ``;\n\n newArtwork.save()\n .then((artwork) => {\n console.log('Document inserted succussfully!', artwork);\n // eslint-disable-next-line max-len\n // res.locals.message = req.flash('success', `Document ${artwork.art_name_input} inserted succussfully!`);\n res.status(200);\n })\n .catch((error) => {\n console.error('Line 166->in catch error block', error);\n res.send(400, 'Bad Request');\n });\n});\n\nconst newArtwork = require('../models/artwork');\n\nrouter.get('/get-imgs', checkAuthenticated, (req, res) => {\n if (req.isAuthenticated()) {\n const role = findRole(req);\n const pics = [];\n let artInfo = {};\n const query = setQuery(req);\n // const query = { artist_email_input: findEmail(req) }; //<--check role here\n console.log('Email: ', query);\n newArtwork.find(query, (err, items) => {\n if (!items || items.length === 0) {\n console.log(err);\n return res.status(404).json({\n err: 'No files exist',\n });\n }\n console.log('*********> # of images: ', items.length);\n for (let i = 0; i < items.length; ++i) {\n console.log('get/imgs===============> items[i]._id: ', items[i]._id);\n const base = Buffer.from(items[i].img.data);\n const conversion = base.toString('base64');\n const images = `data:${items[i].img.contentType};base64, ${conversion}`;\n console.log(`get/imgs-------------> items[${i}].img.data: `, items[i].img.data);\n artInfo = {\n artId: items[i]._id,\n artistFirstName: items[i].artist_firstname_input,\n artistLastName: items[i].artist_lastname_input,\n artistEmail: items[i].artist_email_input,\n artName: items[i].art_name_input,\n artDesc: items[i].description_input,\n artMedium: items[i].medium_input,\n artHeight: items[i].height,\n artWidth: items[i].width,\n artDepth: items[i].depth,\n artPrice: items[i].price,\n artApproved: items[i].approved,\n artReviewer: role,\n };\n pics.push(artInfo);\n pics.push(images);\n console.log('------------->artInfo after artInfo push: ', artInfo);\n console.log('------------->pics after artInfo push: ', pics[i].artId);\n }\n return res.status(200).send(pics);\n });\n }\n});\n\n// Gallery Image download\nrouter.get('/get-gallery-imgs', checkAuthenticated, (req, res) => {\n if (req.isAuthenticated()) {\n const pics = [];\n let artInfo = {};\n const galleryschool = { school: findSchoolName(req), approved: true };\n const query = galleryschool;\n console.log('Line 247 file_upload_controller school_input: ', query);\n newArtwork.find(query, (err, items) => {\n if (!items || items.length === 0) {\n console.log(err);\n return res.status(404).json({\n err: 'No files exist',\n });\n }\n console.log('Line 255 file_upload_controller *********> # of images: ', items.length);\n for (let i = 0; i < items.length; ++i) {\n console.log('get/imgs===============> items[i]._id: ', items[i]._id);\n const base = Buffer.from(items[i].img.data);\n const conversion = base.toString('base64');\n const images = `data:${items[i].img.contentType};base64, ${conversion}`;\n console.log(`get/imgs-------------> items[${i}].img.data: `, items[i].img.data);\n artInfo = {\n artId: items[i]._id,\n artistFirstName: items[i].artist_firstname_input,\n artistLastName: items[i].artist_lastname_input,\n artistEmail: items[i].artist_email_input,\n artName: items[i].art_name_input,\n artDesc: items[i].description_input,\n artMedium: items[i].medium_input,\n artHeight: items[i].height,\n artWidth: items[i].width,\n artDepth: items[i].depth,\n artPrice: items[i].price,\n artApproved: items[i].approved,\n };\n pics.push(artInfo);\n pics.push(images);\n console.log('Line 278 file_upload_controller------------->artInfo after artInfo push: ', artInfo);\n console.log('Line 279 file_upload_controller------------->pics after artInfo push: ', pics[i].artId);\n }\n return res.status(200).send(pics);\n });\n }\n});\n\n// Approval button by _id\nrouter.post('/approve', checkAuthenticated, (req, res) => {\n console.log('req.body: ', req.body._id);\n // const query = { _id: `ObjectId('${req.body._id}')` };\n const query = `${req.body._id}`;\n const options = { new: true };\n console.log('query: ', query);\n // newArtwork.findByIdAndUpdate((req.params.id, req.body),\n newArtwork.findByIdAndUpdate(query, { $set: { approved: true } }, options, (err, data) => {\n if (err) {\n console.log(err);\n res.send(400, 'Bad Request');\n }\n console.log('Artwork approved!', data);\n res.status(200).send(data);\n });\n});\n\n// --------------------- Delete artwork by _id --------------------- //\nrouter.post('/delete/', checkAuthenticated, (req, res) => {\n console.log('req.body: ', req.body);\n newArtwork.findByIdAndDelete((req.params.id, req.body),\n (err, data) => {\n if (err) {\n console.log(err);\n } else {\n console.log('Data Deleted!');\n res.send(data);\n }\n });\n});\n\n// https://stackoverflow.com/questions/21194934/how-to-create-a-directory-if-it-doesnt-exist-using-node-js\n\n// ----------------------- Bid Button Gallery --------------------- //\nrouter.post('/add-bid', checkAuthenticated, (req, res) => {\n console.log('got Bid: ', req.body);\n const currentbid = req.body.bid;\n newArtwork.findByIdAndUpdate((req.params.id, req.body), { currentbid },\n (err, data) => {\n if (err) {\n console.log(err);\n res.send(400, 'Bad Request');\n } else {\n console.log('Bid added to Artwork id: ', req.params.id);\n res.status(200).send(data);\n }\n });\n});\n\nrouter.get('/get-bid-img', checkAuthenticated, (req, res) => {\n if (req.isAuthenticated()) {\n // const role = findRole(req);\n const pics = [];\n let artInfo = {};\n const query = setQuery(req);\n // const query = { artist_email_input: findEmail(req) }; //<--check role here\n console.log('Art ID: ', query);\n newArtwork.find(query, (err, items) => {\n if (!items || items.length === 0) {\n console.log(err);\n return res.status(404).json({\n err: 'No files exist',\n });\n }\n console.log('*********> # of images: ', items.length);\n for (let i = 0; i < items.length; ++i) {\n console.log('get/imgs===============> items[i]._id: ', items[i]._id);\n const base = Buffer.from(items[i].img.data);\n const conversion = base.toString('base64');\n const images = `data:${items[i].img.contentType};base64, ${conversion}`;\n console.log(`line 387 get/bid-img-------------> items[${i}].img.data: `, items[i].img.data);\n artInfo = {\n artId: items[i]._id,\n artistFirstName: items[i].artist_firstname_input,\n artistLastName: items[i].artist_lastname_input,\n artistEmail: items[i].artist_email_input,\n artName: items[i].art_name_input,\n artDesc: items[i].description_input,\n artMedium: items[i].medium_input,\n artHeight: items[i].height,\n artWidth: items[i].width,\n artDepth: items[i].depth,\n artPrice: items[i].price,\n artApproved: items[i].approved,\n // artReviewer: role,\n };\n pics.push(artInfo);\n pics.push(images);\n console.log('------------->artInfo after artInfo push: ', artInfo);\n console.log('------------->pics after artInfo push: ', pics[i].artId);\n }\n return res.status(200).send(pics);\n });\n }\n});\nmodule.exports = router;", "dangerousExampleEn": "1. const path = require('path');\n2. const fs = require('fs');\n3. \n4. router.post('/Path', function (req, res) {\n5. const content = req.body.content;\n6. const BASE_DIR = 'C:/';\n7. \n8. fs.readFile(path.resolve(BASE_DIR,content), 'utf-8', function (err, data){\n9. if(err){\n10. console.log(err);\n11. }else{\n12. return res.send({data: data});\n13. }\n14. });\n15. });\nLine 8: This is vulnerable to path traversal because an external input is used without proper verification.", "safeExampleEn": "1. const path = require('path');\n2. const fs = require('fs');\n3. \n4. router.post('/Path', function (req, res) {\n5. const content = req.body.content;\n6. const BASE_DIR = 'C:/';\n7. \n8. const safe_content = content.replace(/[\\\\\\/]/gi, \"\");\n9. \n10. fs.readFile(path.resolve(BASE_DIR, safe_content), 'utf-8', function (err, data) {\n11. if (err) {\n12. console.log(err);\n13. return res.send({data: \"This is an invalid input.\"});\n14. } else {\n15. return res.send({data: data});\n16. }\n17. });\n18. });\nLine 10: This is secure because insecure characters are filtered using a regular expression.", "contexts": [{"lineNo": 199, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "req"}}, {"lineNo": 199, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "findSchoolName"}}, {"lineNo": 199, "eventType": "sink", "messageKey": "jschk.PATH_CONTAMINATION.JS.defect.sink", "params": {}}]}} {"id": "c2545a193da949e33ea0c4ec6ea751f6c335a89771ae2f41466d653b0d09c35a", "license": {"spdx": ["MIT"], "repo": "salmanff/freezr202103", "path": "freezr_system/account_handler.js", "repo_head_hexsha": "e9c137b265ed16be44aec685023bdf481fd31302", "stack_hexsha": "4c9d3c45ef1a80ff342042ba1b30f1522b560fb1", "match": "repo_path"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Path Traversal", "issueDescriptionEn": "When unverified external inputs are used to access system resources, attackers can manipulate the input values to access resources protected by the system, which lead to create vulnerability. Attackers can exploit this to modify or delete resources, leak system information, and cause service failure due to the conflicts between system resources.\nEnsure to use predefined identifiers only or filter out characters vulnerable to path traversal, i.e.\n/, , ., when you need to use the external input to refer to the system resources including a file or socket port.", "issueLineNumber": 468, "entireCode": "// freezr.info - nodejs system files - account_handler\n\n/* global User, Flags */\n\n/* 2021 CEPS 2.0 notes\n - table_id? use instead of app_table for consistency?\n*/\n\nexports.version = '0.0.200'\n\nconst helpers = require('./helpers.js')\nconst bcrypt = require('bcryptjs')\nconst async = require('async')\nconst json = require('comment-json')\nconst fileHandler = require('./file_handler.js')\nrequire('./flags_obj.js')\n\nexports.generate_login_page = function (req, res) {\n // app.get('/login', publicUserPage, accountHandler.generate_login_page)\n // app.get('/account/login', publicUserPage, accountHandler.generate_login_page)\n fdlog('login_page ' + JSON.stringify(req.url))\n if (req.session && req.session.logged_in_user_id && req.url === '/account/login') { // last term relevant only if freezr preferences file has been deleted\n felog('redirect to home - already logged in')\n res.redirect('/account/home')\n } else {\n // fdlog todo - need to sanitize text\n var options = {\n page_title: (req.params.app_name ? 'Freezr App Login for ' + req.params.app_name : ' Login (Freezr)'),\n css_files: './public/info.freezr.public/public/freezr_style.css',\n initial_query: null,\n server_name: req.protocol + '://' + req.get('host'),\n freezr_server_version: req.freezr_server_version,\n app_name: (req.params.app_name ? req.params.app_name : 'info.freezr.account'),\n other_variables: 'var login_for_app_name = ' + (req.params.app_name ? (\"'\" + req.params.app_name + \"';\") : 'null') + ';' +\n ' var loginAction = ' + (req.params.loginaction ? (\"'\" + req.params.loginaction + \"';\") : 'null') + ';' +\n ' var freezrServerStatus = ' + JSON.stringify(req.freezrStatus) + ';' +\n ' freezrAllowSelfReg = ' + req.freezrAllowSelfReg + ';'\n }\n\n if (!req.session) req.session = {}\n if (!req.session.device_code) {\n req.session.device_code = helpers.randomText(20)\n // todo use randomBytes(10).toString(‘base64')\n // todo - Record device code below async-ly and keep track of all attempts to access\n }\n options.app_name = 'info.freezr.public'\n options.page_url = 'public/account_' + ((req.params.app_name && req.params.app_name !== 'info.freezr.public') ? 'app' : '') + 'login.html'\n options.script_files = ['./public/info.freezr.public/public/account_login.js']\n options.user_id = req.session.logged_in_user_id\n\n fileHandler.load_data_html_and_page(req, res, options)\n }\n}\nexports.generateSystemDataPage = function (req, res) {\n // app.get('/account/appdata/:target_app/:action', accountLoggedInUserPage, addUserAppsAndPermDBs, accountHandler.generateSystemDataPage)\n\n req.params.page = 'appdata_' + req.params.action // todo sanitize text\n req.params.other_variables = \"const app_name ='\" + req.params.target_app + \"'\"\n exports.generateAccountPage(req, res)\n}\nexports.generateAccountPage = function (req, res) {\n // app.get('/account/:page', accountLoggedInUserPage, addUserAppsAndPermDBs, accountHandler.generateAccountPage)\n // app.get('/account/:page/:target_app', accountLoggedInUserPage, addUserAppsAndPermDBs, accountHandler.generateAccountPage)\n // assumes user's logged in status has been validated and req.AppToken\n\n fdlog('NEWgenerateAccountPage accountPage: ' + req.url + ' target_app: ' + req.params.target_app + ' page: ' + req.params.page)\n if (!req.params.page) {\n req.params.page = 'home'\n } else {\n req.params.page = req.params.page.toLowerCase()\n }\n\n if (accountPagemanifest[req.params.page]) {\n var options = accountPagemanifest[req.params.page]\n fdlog('have app ', { options })\n options.app_name = 'info.freezr.account'\n options.user_id = req.session.logged_in_user_id\n options.user_is_admin = req.session.logged_in_as_admin\n options.server_name = req.protocol + '://' + req.get('host')\n options.other_variables = req.params.other_variables // only from generateSystemDataPage\n\n // onsole.log(options)\n if (!req.freezrTokenInfo || !req.freezrTokenInfo.app_token || !req.session.logged_in_user_id) {\n helpers.send_failure(res, helpers.error('invalid credentials'), 'account_handler', exports.version, 'login')\n } else if (!options.initial_query_func) {\n res.cookie('app_token_' + req.session.logged_in_user_id, req.freezrTokenInfo.app_token, { path: '/account' })\n fileHandler.load_data_html_and_page(req, res, options)\n } else { // initial_query_func\n res.cookie('app_token_' + req.session.logged_in_user_id, req.freezrTokenInfo.app_token, { path: '/account' })\n req.params.internal_query_token = req.freezrTokenInfo.app_token // internal query request\n\n if (req.params.page === 'perms' && req.query.requestor_app) req.params.target_app = req.query.requestor_app\n\n req.freezrInternalCallFwd = function (err, results) {\n if (err) {\n res.redirect('/admin/public/starterror')\n } else {\n options.queryresults = results\n fileHandler.load_data_html_and_page(req, res, options)\n }\n }\n options.initial_query_func(req, res)\n }\n } else {\n // onsole.log(\"SNBH - accountPagemanifest - Redirecting from generateAccountPage\")\n res.redirect('/account/home')\n }\n}\n\nexports.ping = function (req, res) {\n // app.get('/ceps/ping', addVersionNumber, accountHandler.ping)\n // app.get('/feps/ping', addVersionNumber, accountHandler.ping)\n\n // todo - could also make this token based... so check token to see if logged_in to app and what capabilities the ceps server accepts\n\n fdlog('ping..' + JSON.stringify(req.query))\n if (!req.session.logged_in_user_id) {\n helpers.send_success(res, { logged_in: false, server_type: 'info.freezr', server_version: req.freezr_server_version })\n } else {\n helpers.send_success(res, { logged_in: true, logged_in_as_admin: req.session.logged_in_as_admin, user_id: req.session.logged_in_user_id, server_type: 'info.freezr', server_version: req.freezr_server_version })\n }\n}\n\n// PASSWORD / USER MANAGEMENT\nconst EXPIRY_DEFAULT = 30 * 24 * 60 * 60 * 1000 // 30 days\nexports.app_password_generate_one_time_pass = function (req, res) {\n // app.get('/v1/account/apppassword/generate', accountLoggedInAPI, addAppTokenDB, accountHandler.app_password_generate_one_time_pass)\n\n const userId = req.session.logged_in_user_id\n const appName = (req.query && req.query.app_name) ? req.query.app_name : null\n const expiry = (req.query && req.query.expiry) ? parseInt(req.query.expiry) : (new Date().getTime() + EXPIRY_DEFAULT)\n const oneDevice = !(req.query && req.query.one_device && req.query.one_device === 'false')\n fdlog('app_password_generate_one_time_pass ' + JSON.stringify(req.query) + ' user: ' + userId + 'app:' + appName)\n\n if (!userId) {\n const err = helpers.auth_failure('account_handler.js', exports.version, 'app_password_generate_one_time_pass', 'Missing user id')\n helpers.send_failure(res, err, 'account_handler', exports.version, 'app_password_generate_one_time_pass')\n } else if (!appName) {\n const err = helpers.auth_failure('account_handler.js', exports.version, 'app_password_generate_one_time_pass', 'Missing app name')\n helpers.send_failure(res, err, 'account_handler', exports.version, 'app_password_generate_one_time_pass')\n } else {\n const write = {\n logged_in: false,\n source_device: req.session.device_code,\n owner_id: userId,\n requestor_id: userId,\n app_name: appName,\n app_password: TimeAppPassword(userId, appName, req.session.device_code),\n app_token: helpers.generateAppToken(userId, appName, req.session.device_code), // create token instead\n expiry: expiry,\n one_device: oneDevice,\n user_device: null,\n date_used: null // to be replaced by date\n }\n req.freezrAppTokenDB.create(null, write, null, (err, results) => {\n if (err) {\n helpers.send_failure(res, err, 'account_handler', exports.version, 'app_password_generate_one_time_pass')\n } else {\n helpers.send_success(res, { app_password: , app_name: appName })\n }\n })\n }\n}\nexports.app_password_update_params = function (req, res) {\n // app.get('/v1/account/apppassword/updateparams', accountLoggedInAPI, addAppTokenDB, accountHandler.app_password_update_params)\n\n fdlog('app_password_update_params ' + JSON.stringify(req.query))\n const userId = req.session.logged_in_user_id\n const appName = (req.query && req.query.app_name) ? req.query.app_name : null\n const expiry = (req.query && req.query.expiry) ? parseInt(req.query.expiry) : null\n const oneDevice = !(req.query && req.query.one_device && req.query.one_device === 'false')\n const params = { expiry, oneDevice }\n const password = (req.query && req.query.password) ? req.query.password : \n\n // todo later - should also check if there are open ones and clean up expired ones\n\n if (!userId) {\n const err = helpers.auth_failure('account_handler.js', exports.version, 'app_password_update_params', 'Missing user id')\n helpers.send_failure(res, err, 'account_handler', exports.version, 'app_password_update_params')\n } else if (!appName) {\n const err = helpers.auth_failure('account_handler.js', exports.version, 'app_password_update_params', 'Missing app name')\n helpers.send_failure(res, err, 'account_handler', exports.version, 'app_password_update_params')\n } else if (!password) {\n const err = helpers.auth_failure('account_handler.js', exports.version, 'app_password_update_params', 'Missing app password')\n helpers.send_failure(res, err, 'account_handler', exports.version, 'app_password_update_params')\n } else if (!req.query.expiry && !req.query.one_device && !(req.query.one_device === false)) {\n const err = helpers.auth_failure('account_handler.js', exports.version, 'app_password_update_params', 'failure on device expiry?')\n helpers.send_failure(res, err, 'account_handler', exports.version, 'app_password_update_params')\n } else {\n req.freezrAppTokenDB.query({ app_password: password }, null,\n (err, results) => {\n if (err) {\n helpers.send_failure(res, err, 'account_handler', exports.version, 'app_password_update_params')\n } else if (!results || results.length === 0) {\n err = helpers.error('no_results', 'expected record but found none (app_password_update_params)')\n helpers.send_failure(res, err, 'account_handler', exports.version, 'app_password_update_params')\n } else {\n const record = results[0] // todo - theoretically there could be multiple and the right one need to be found\n if (record.requestor_id !== userId || record.owner_id !== userId || record.app_name !== appName) {\n err = helpers.error('no_results', 'app_name or user_id do not match expected value(app_password_update_params)')\n helpers.send_failure(res, err, 'account_handler', exports.version, 'app_password_update_params')\n } else if (helpers.expiry_date_passed(record.expiry)) {\n err = helpers.error('password_expired', 'One time password has expired.')\n helpers.send_failure(res, err, 'account_handler', exports.version, 'app_password_update_params')\n } else if (record.date_used) {\n err = helpers.error('password_used', 'Cannot change parameters after password has been used')\n helpers.send_failure(res, err, 'account_handler', exports.version, 'app_password_update_params')\n } else {\n var changes = {}\n if (expiry) changes.expiry = expiry\n if (oneDevice || oneDevice === false) changes.one_device = params.oneDevice\n req.freezrAppTokenDB.update((record._id + ''), changes, { replaceAllFields: false }, function (err, results) {\n if (err) {\n helpers.send_failure(res, err, 'account_handler', exports.version, 'app_password_update_params')\n } else {\n helpers.send_success(res, { success: true })\n }\n })\n }\n }\n })\n }\n}\nexports.changePassword = function (req, res) {\n // app.put('/v1/account/changePassword.json', accountLoggedInAPI, addAllUsersDb, accountHandler.changePassword)\n // req.freezrUserDS\n // onsole.log(\"Changing password \"+JSON.stringify(req.body));\n\n var userId = req.body.user_id\n let u = null\n async.waterfall([\n // 1. basic checks\n function (cb) {\n if (!userId) {\n cb(helpers.auth_failure('account_handler.js', exports.version, 'changePassword', 'Missing user id'))\n } else if (!req.session.logged_in_user_id || userId !== req.session.logged_in_user_id) {\n cb(helpers.auth_failure('account_handler.js', exports.version, 'changePassword', 'user not logged in'))\n } else if (!req.body.oldPassword) {\n cb(helpers.auth_failure('account_handler.js', exports.version, 'changePassword', 'Missing old password'))\n } else if (!req.body.newPassword) {\n cb(helpers.auth_failure('account_handler.js', exports.version, 'changePassword', 'Missing new password'))\n } else {\n cb(null)\n }\n },\n\n // 2. get user\n function (cb) {\n req.allUsersDb.query({ user_id: userId }, null, cb)\n },\n\n // 3. check the password\n function (results, cb) {\n require('./user_obj.js')\n u = new User(results[0])\n if (!results || results.length === 0) {\n cb(helpers.auth_failure('account_handler.js', exports.version, 'changePassword', 'funky error'))\n } else if (results.length > 1) {\n cb(helpers.auth_failure('account_handler.js', exports.version, 'changePassword', 'getting too many users'))\n } else if (u.check_passwordSync(req.body.oldPassword)) {\n bcrypt.hash(req.body.newPassword, 10, cb)\n } else {\n fdlog('need to limit number of wring passwords - set a file in the datastore ;) ')\n cb(helpers.auth_failure('account_handler.js', exports.version, 'changePassword', 'Wrong password'))\n }\n },\n\n // 3. change pw for the user.\n function (hash, cb) {\n req.allUsersDb.update(\n { user_id: userId },\n { password: },\n { replaceAllFields: false },\n cb)\n }\n\n ],\n function (err, returns) {\n if (err) {\n helpers.send_failure(res, err, 'account_handler', exports.version, 'changePassword')\n } else if (!returns || !returns.nModified || returns.nModified === 0) {\n helpers.send_failure(res, helpers.error('change error - was not able to change any passwords: ' + JSON.stringify(returns)), 'account_handler', exports.version, 'changePassword')\n } else {\n if (returns.nModified !== 1) felog('changePassword', 'error in changing user records - to investigate why more than 1 modified ', returns)\n helpers.send_success(res, { user: u.response_obj() })\n }\n })\n}\nexports.removeFromFreezr = function (req, res) {\n // app.put('/v1/account/changePassword.json', accountLoggedInAPI, addAllUsersDb, accountHandler.changePassword)\n // req.freezrUserDS\n // onsole.log(\"Changing password \"+JSON.stringify(req.body));\n\n var userId = req.body.user_id\n let u = null\n async.waterfall([\n // 1. basic checks\n function (cb) {\n if (!userId) {\n cb(helpers.auth_failure('account_handler.js', exports.version, 'removeFromFreezr', 'Missing user id'))\n } else if (!req.session.logged_in_user_id || userId !== req.session.logged_in_user_id) {\n cb(helpers.auth_failure('account_handler.js', exports.version, 'removeFromFreezr', 'user not logged in'))\n } else if (!req.body.oldPassword) {\n cb(helpers.auth_failure('account_handler.js', exports.version, 'removeFromFreezr', 'Missing old password'))\n } else {\n cb(null)\n }\n },\n\n // 2. get user\n function (cb) {\n req.allUsersDb.query({ user_id: userId }, null, cb)\n },\n\n // 3. check the password\n function (results, cb) {\n require('./user_obj.js')\n u = new User(results[0])\n if (!results || results.length === 0) {\n cb(helpers.auth_failure('account_handler.js', exports.version, 'removeFromFreezr', 'funky error'))\n } else if (results.length > 1) {\n cb(helpers.auth_failure('account_handler.js', exports.version, 'removeFromFreezr', 'getting too many users'))\n } else if (u.check_passwordSync(req.body.oldPassword)) {\n cb(null)\n } else {\n fdlog('need to limit number of wrong passwords - set a file in the datastore ;) ')\n cb(helpers.auth_failure('account_handler.js', exports.version, 'removeFromFreezr', 'Wrong password'))\n }\n },\n\n // 3. cremvoe the user\n function (cb) {\n if (!req.session.logged_in_as_admin && (req.freezrUserDS.fsParams.type === 'dropbox' || req.freezrUserDS.fsParams.type === 'googleDrive')) {\n req.allUsersDb.delete_record(userId, null, cb)\n } else {\n cb(new Error('A user cannot delete itdslef if it is admin or is using system resources.'))\n }\n }\n\n ],\n function (err, returns) {\n if (err) {\n helpers.send_failure(res, err, 'account_handler', exports.version, 'removeFromFreezr')\n } else {\n helpers.send_success(res, { success: true })\n }\n })\n}\nexports.list_all_user_apps = function (req, res) {\n // app.get('/v1/account/app_list.json', accountLoggedInAPI, accountHandler.list_all_user_apps)\n // accountLoggedInAPI ->\n\n fdlog('account_handler list_all_user_apps')\n\n const userId = req.session.logged_in_user_id\n const userDS = req.freezrUserDS\n const oac = {\n owner: userId,\n app_name: 'info.freezr.account',\n collection_name: 'app_list'\n }\n\n var removedApps = []\n var userApps = []\n\n async.waterfall([\n // 1. get db\n function (cb) {\n userDS.getorInitDb(oac, null, cb)\n },\n\n // 2. get all user apps\n function (appList, cb) {\n if (!appList || !appList.query) {\n cb(new Error('inccomplete or authentication malfucntion getting db for ' + userId))\n } else {\n appList.query({}, null, cb)\n }\n },\n\n function (results, cb) {\n if (results && results.length > 0) {\n results = results.map(app => { return { app_name: app.app_name, removed: app.removed, _date_modified: app._date_modified, _id: app._id, app_display_name: app.app_display_name, offThreadWip: app.offThreadWip, offThreadParams: app.offThreadParams } })\n for (var i = 0; i < results.length; i++) {\n if (results[i].app_name && results[i].app_name === results[i].app_display_name) { results[i].app_display_name = results[i].app_display_name.replace(/\\./g, '. ') }\n results[i].logo = '/app_files/' + results[i].app_name + '/static/logo.png'\n if (results[i].removed) {\n removedApps.push(results[i])\n } else {\n userApps.push(results[i])\n }\n }\n }\n cb(null)\n }\n ],\n function (err) {\n if (err) {\n felog('list_all_user_apps', 'ERROR in list_all_user_apps ', err)\n if (req.freezrInternalCallFwd) {\n req.freezrInternalCallFwd(err, null)\n } else {\n helpers.send_failure(res, err, 'account_handler', exports.version, 'list_all_user_apps')\n }\n } else {\n // onsole.log(\" results\",{removedApps:removedApps, user_apps:userApps})\n if (req.freezrInternalCallFwd) {\n req.freezrInternalCallFwd(null, { removed_apps: removedApps, user_apps: userApps })\n } else {\n helpers.send_success(res, { removed_apps: removedApps, user_apps: userApps })\n }\n }\n })\n}\n\n// App Installation and Updating\nexports.get_file_from_url_to_install_app = function (req, res) {\n // app.post('/v1/account/app_install_from_url.json', accountLoggedInUserPage, addUserAppsAndPermDBs, accountHandler.get_file_from_url_to_install_app)\n // onsole.log(\"get_file_from_url_to_install_app\",req.body)\n\n // todo 2020-07 this needs to be redone so that it saves to a temp file and then\n\n const fs = require('fs')\n const request = require('request')\n\n const download = (url, dest, cb) => {\n fdlog('download ', { url, dest })\n // from stackoverflow.com/questions/11944932/how-to-download-a-file-with-node-js-without-using-third-party-libraries\n const file = fs.createWriteStream(dest)\n const sendReq = request.get(url)\n\n // verify response code\n sendReq.on('response', (response) => {\n if (response.statusCode !== 200) {\n return cb(new Error('Bad Connection - Response status was ' + response.statusCode))\n }\n sendReq.pipe(file)\n })\n\n // close() is async, call cb after close completes\n file.on('finish', () => file.close(cb))\n\n // check for request errors\n sendReq.on('error', (err) => {\n return cb(err)\n })\n\n file.on('error', (err) => {\n if (err) felog('download', 'file error', err)\n cb(err)\n })\n }\n\n const tempAppName = req.body.app_name\n const tempFolderPath = helpers.FREEZR_USER_FILES_DIR + '/' + req.session.logged_in_user_id + '/tempapps/' + tempAppName\n\n fileHandler.mkdirp(tempFolderPath, function (err) {\n if (err) {\n helpers.send_success(res, { success: false, err: err, flags: null, text: '' })\n } else {\n const zipFilePath = tempFolderPath + '/' + tempAppName + '.zip'\n download(req.body.app_url, zipFilePath, function (err) {\n if (err) felog('err', err)\n if (!err && req.body.app_name) {\n req.app_name = req.body.app_name\n req.file = {}\n req.file.originalname = req.body.app_name + '.zip'\n fs.readFile(fileHandler.fullLocalPathTo(zipFilePath), null, function (err, content) {\n if (err) {\n felog('account_handler get_file_from_url_to_install_app ', err)\n helpers.send_success(res, { success: false, err: err, flags: null, text: '' })\n } else {\n req.file.buffer = content\n req.installsource = 'get_file_from_url_to_install_app'\n exports.install_app(req, res)\n }\n })\n\n // req.file.buffer = zipFilePath\n // req.installsource = 'get_file_from_url_to_install_app'\n // exports.install_app(req, res)\n // fdlog? todonow delete tempfile... determine name ... put file under user / files\n } else { // err or missing app name\n var flags = new Flags({})\n flags.meta.app_name = req.body.app_name\n if (!err) err = { code: 'Missing App name', message: 'app name is required to create an app.' }\n if (!err.code) err.code = 'err_unknown'\n if (!err.message) err.message = 'Could not connect to the requested URL'\n flags.add('errors', err.code, { function: 'install_app', text: err.message })\n\n helpers.send_success(res, { success: false, err: err, flags: null, text: '' })\n }\n })\n }\n })\n}\nexports.install_blank_app = function (req, res) {\n // app.post('/v1/account/app_install_blank', accountLoggedInUserPage, addUserAppsAndPermDBs, accountHandler.install_blank_app)\n\n // from access_handler and perm_handler\n fdlog('install_blank_app ')\n const appName = req.body.app_name\n const manifest = {\n identifier: appName,\n display_name: appName,\n version: 0\n }\n var flags = new Flags({ app_name: appName, didwhat: 'installed' })\n\n async.waterfall([\n // 1. make sure data and file names exist and appName is valid\n function (cb) {\n if (!req.session.logged_in_user_id) {\n cb(helpers.missing_data('user_id'))\n } else if (!appName || appName.length < 1) {\n cb(helpers.invalid_data('app name missing - that is the name of the app zip file name before any spaces.', 'account_handler', exports.version, 'install_blank_app'))\n } else if (helpers.system_apps.indexOf(appName) > -1 || !helpers.valid_app_name(appName)) {\n cb(helpers.invalid_data('app name not allowed: ' + appName, 'account_handler', exports.version, 'install_blank_app'))\n } else {\n req.freezrUserAppListDB.read_by_id(appName, cb)\n }\n },\n\n // see if entity exists\n function (existingEntity, cb) {\n if (existingEntity) {\n cb(helpers.invalid_data('app already exists ' + appName, 'account_handler', exports.version, 'install_blank_app'))\n } else {\n // console.log('todo - update permissions?')\n createOrUpdateUserAppList(req.freezrUserAppListDB, manifest, null, cb)\n }\n },\n // get appfs to delete local app files for cloud storage\n function (cb) {\n req.freezrUserDS.getorInitAppFS(appName, {}, cb)\n },\n // delete previous version of cache (or real folder if local)\n function (appFS, cb) {\n if (appFS.fsParams.type === 'local' || appFS.fsParams.type === 'glitch') {\n cb(null) // local files are the main files - dont delete\n } else {\n appFS.cache.appfiles = {}\n const realAppPath = helpers.FREEZR_USER_FILES_DIR + '/' + req.session.logged_in_user_id + '/apps/' + appName\n fileHandler.deleteLocalFolderAndContents(realAppPath, cb)\n }\n }\n ],\n function (err) {\n if (err) {\n if (!err.code) err.code = 'err_unknown'\n flags.add('errors', err.code, { function: 'install_blank_app', text: err.message })\n }\n helpers.send_success(res, { err: err, flags: flags.sentencify() })\n })\n}\nexports.install_app = function (req, res) {\n // installAppFromZipFile => app.put('/v1/account/app_install_from_zipfile.json', accountLoggedInUserPage, addUserAppsAndPermDBs, installAppFromZipFile)\n // onsole.log(\"install_app file.originalname \",req.file.originalname,\"app_name \",req.app_name)\n\n fdlog('install_app ' + req.file.name + (req.installsource || ''))\n\n // from access_handler and perm_handler\n const userDS = req.freezrUserDS\n let appFS // ds generated from userAppFs\n\n const tempAppName = tempAppNameFromFileName(req.file.originalname)\n const tempFolderPath = helpers.FREEZR_USER_FILES_DIR + '/' + req.session.logged_in_user_id + '/tempapps/' + tempAppName\n\n var manifest = null\n let realAppName\n let realAppPath\n var flags = new Flags({})\n\n async.waterfall([\n // 1. make sure data and file names exist and tempAppName is correct\n function (cb) {\n if (!req.session.logged_in_user_id) {\n cb(helpers.missing_data('user_id'))\n } else if (!req.file) {\n cb(helpers.missing_data('file', 'account_handler', exports.version, 'install_app'))\n } else if (!req.file.originalname) {\n cb(helpers.missing_data('file name', 'account_handler', exports.version, 'install_app'))\n } else if (req.file.originalname.length < 5 || req.file.originalname.substr(-4) !== '.zip') {\n cb(helpers.invalid_data('file name not zip: ' + req.file.originalname, 'account_handler', exports.version, 'install_app'))\n } else {\n cb(null)\n }\n },\n\n // REMOVE THE LOCAL temp DIRECTORY and extract zip files to it to read the manifest\n function (cb) {\n fileHandler.deleteLocalFolderAndContents(tempFolderPath, cb)\n },\n function (cb) {\n // if (req.installsource === 'get_file_from_url_to_install_app') {\n // cb(null)\n // } else {\n fileHandler.extractZipToLocalFolder(req.file.buffer, tempFolderPath, tempAppName, cb)\n // }\n },\n\n // get the manifest file and the real name and check it\n function (cb) {\n fileHandler.getLocalManifest(tempFolderPath, cb)\n },\n function (manifestFromFile, cb) {\n fdlog('gort manifest ', { manifestFromFile })\n manifest = manifestFromFile\n realAppName = (manifest && manifest.identifier) ? manifest.identifier : tempAppName\n flags = new Flags({ app_name: realAppName, didwhat: 'installed' })\n if (realAppName !== tempAppName) flags.add('notes', 'app_name_different')\n\n if (!realAppName || realAppName.length < 1) {\n fileHandler.deleteLocalFolderAndContents(tempFolderPath, function (err) {\n if (err) felog('install_app', 'error deleting local folder after app name missing ')\n cb(helpers.invalid_data('app name missing - that is the name of the app zip file name before any spaces.', 'account_handler', exports.version, 'install_app'))\n })\n } else if (helpers.system_apps.indexOf(realAppName) > -1 || !helpers.valid_app_name(realAppName)) {\n fileHandler.deleteLocalFolderAndContents(tempFolderPath, function (err) {\n if (err) felog('install_app', 'error deleting local folder 2 after app name not allowed ')\n cb(helpers.invalid_data('app name not allowed: ' + tempAppName, 'account_handler', exports.version, 'install_app'))\n })\n } else {\n cb(null)\n }\n },\n // get appfs to eextract app files\n function (cb) {\n userDS.getorInitAppFS(realAppName, {}, cb)\n },\n // delete previous version of cache (or real folder if local)\n function (userAppFS, cb) {\n appFS = userAppFS\n // todo fdlog - add glitch prefix to folder\n realAppPath = helpers.FREEZR_USER_FILES_DIR + '/' + req.session.logged_in_user_id + '/apps/' + realAppName\n appFS.cache.appfiles = {}\n fileHandler.deleteLocalFolderAndContents(realAppPath, cb)\n },\n // extract to local folder\n function (cb) {\n fileHandler.extractZipToLocalFolder(req.file.buffer, realAppPath, tempAppName, cb)\n },\n // extract to actual location (except when it is a local system - ie it already exists)\n function (cb) {\n if (appFS.fsParams.type === 'local' || appFS.fsParams.type === 'glitch') {\n cb(null) // already copied to local above\n } else if (req.installsource === 'get_file_from_url_to_install_app' && ['dropbox', 'googleDrive'].includes(appFS.fsParams.type)) {\n // console.log todo - dropbox and google drive should have an offline isntall parameter that should be used instead of the includes above\n offThreadExtraction({\n file: req.file.buffer,\n name: req.file.originalname,\n appFS,\n freezrUserAppListDB: req.freezrUserAppListDB,\n fileUrl: req.body.app_url,\n versionDate: new Date().getTime(),\n init: true\n }, cb)\n } else {\n fileHandler.extractZipAndReplaceToCloudFolder(req.file.buffer, req.file.originalname, appFS, cb)\n }\n },\n function (cb) { // remove the temprary file\n fileHandler.deleteLocalFolderAndContents(tempFolderPath, cb)\n },\n\n // 5. check manifest (populate app_version and app_display_name and permissons)\n function (cb) {\n if (!manifest) flags.add('notes', 'manifest_missing')\n if (!manifest) manifest = {}\n if (!manifest.identifier) manifest.identifier = realAppName\n if (!manifest.display_name) manifest.display_name = realAppName\n if (!manifest.version) manifest.version = 0\n\n flags = fileHandler.checkManifest(manifest, realAppName, manifest.version, flags)\n\n updatePermissionRecordsFromManifest(req.freezrUserPermsDB, realAppName, manifest, cb)\n },\n\n // 6. Update the app list\n function (cb) {\n const customEnv = null // todo to be added later\n createOrUpdateUserAppList(req.freezrUserAppListDB, manifest, customEnv, cb)\n },\n\n // 8. If app already exists, flag it as an update\n function (info, cb) {\n if (info.isUpdate) {\n flags.add('notes', 'app_updated_msg')\n flags.meta.didwhat = 'updated'\n } else {\n flags.meta.didwhat = 'uploaded'\n }\n cb(null)\n }\n // todo later (may be) - also check manifest permissions (as per changeNamedPermissions) to warn of any issues\n ],\n function (err, dummy) {\n // todo: if there is an error in a new manifest the previous one gets wied out but the ap still runs (as it was instaled before successfully), so it should be marked with an error.\n // todo: also better to wipe out old files so old files dont linger if they dont exist in new version\n flags.meta.app_name = realAppName\n if (err) {\n if (!err.code) err.code = 'err_unknown'\n flags.add('errors', err.code, { function: 'install_app', text: err.message })\n }\n // onsole.log(flags.sentencify())\n helpers.send_success(res, { err: err, flags: flags.sentencify() })\n\n // preload databases\n if (manifest.app_tables && Object.keys(manifest.app_tables).length > 0 && manifest.app_tables.constructor === Object) {\n for (const appTable in manifest.app_tables) {\n const oac = {\n owner: req.session.logged_in_user_id,\n app_name: realAppName,\n app_table: appTable\n }\n req.freezrUserDS.getorInitDb(oac, {}, function (err, aDb) {\n if (err) felog('install_app - err in initiating installed app db ', err)\n aDb.query(null, { count: 1 }, function (err, results) {\n if (err) felog('install_app - err in querying installed app db ', err)\n fdlog('db fake query for init - query results ', results)\n })\n })\n }\n }\n })\n}\nconst tempAppNameFromFileName = function (originalname) {\n let name = ''\n const parts = originalname.split('.')\n if (helpers.endsWith(parts[(parts.length - 2)], '-main')) parts[(parts.length - 2)] = parts[(parts.length - 2)].slice(0, -7)\n parts.splice(parts.length - 1, 1)\n name = parts.join('.')\n name = name.split(' ')[0]\n return name\n}\nconst TRY_THRESHOLD = 5\nconst offThreadExtraction = function (params, callback) {\n fdlog('offThreadExtraction ', { params })\n /* file: req.file.buffer,\n name: req.file.originalname,\n appFS,\n freezrUserAppListDB: req.freezrUserAppListDB,\n fileUrl: req.body.app_url,\n versionDate: new Date().getTime(),\n init: true\n // appRecord: [record from freezrUserAppListDB]\n // params.filesRemaining = fileList\n */\n // Note params and appRecord both retain fileList for redundancy on error count\n // and also to allow this to be added as a scheduled task, where params variable is lost\n // and the appRecord alone is relied on\n if (params.init) {\n const [err, fileList] = fileHandler.appFileListFromZip(params.file)\n if (err) {\n felog('offThreadExtraction err in appFileListFromZip', { params, err })\n callback(err)\n } else {\n // flag the freezrUserAppListDB as being WIP and\n const offThreadStatus = {\n installFileUrl: params.fileUrl,\n offThreadParams: {\n tryNum: 1,\n versionDate: params.versionDate,\n filesRemaining: fileList\n },\n offThreadWip: true\n }\n params.freezrUserAppListDB.read_by_id(params.appFS.appName, function (err, record) {\n if (err) {\n felog('offThreadExtraction err in read_by_id', { params, err })\n callback(err)\n } else if (!record) {\n params.freezrUserAppListDB.create(params.appFS.appName, { app_name: params.appFS.appName, app_display_name: params.appFS.appName, manifest: null, removed: false }, null, function (err) {\n if (err) {\n callback(err)\n } else {\n offThreadExtraction(params, callback)\n }\n })\n } else {\n params.freezrUserAppListDB.update(params.appFS.appName, offThreadStatus, { replaceAllFields: false }, function (err, result) {\n if (err) {\n felog('offThreadExtraction err in freezrUserAppListDB', { params, err })\n callback(err)\n } else {\n params.init = false\n params.tryNum = 1\n params.filesRemaining = fileList\n setTimeout(function () {\n fileHandler.removeCloudAppFolder(params.appFS, function (err) {\n if (err) felog('offThreadExtraction err in removeCloudAppFolder - (Will try installing in any case) ', err)\n offThreadExtraction(params)\n })\n }, 2000)\n callback()\n }\n })\n }\n })\n }\n } else if (params.tryNum > TRY_THRESHOLD) {\n // donnothing\n felog('offThreadExtraction - tried installing app maximum times ', params.tryNum)\n } else {\n params.freezrUserAppListDB.read_by_id(params.appFS.appName, function (err, appRecord) {\n if (err) {\n felog('offThreadExtraction - freezrUserAppListDB.read_by_id err ', { params, err })\n params.tryNum++\n setTimeout(function () { offThreadExtraction(params) }, params.tryNum * 2000)\n } else if (!appRecord || !appRecord.offThreadParams || !appRecord.offThreadParams.tryNum) {\n params.tryNum++\n felog('offThreadExtraction - freezrUserAppListDB.read_by_id NO APP RECORD ', { params, err })\n setTimeout(function () { offThreadExtraction(params) }, params.tryNum * 2000)\n } else if (appRecord.offThreadParams.versionDate !== params.versionDate) {\n felog('offThreadExtraction - vefsion date mismatch', { appRecord, params, err })\n // new installation process has begun - abort installation\n } else if (appRecord.offThreadWip === false) {\n felog('offThreadExtraction - fileList was emptied SNBH')\n } else {\n params.appRecord = appRecord\n fileHandler.extractNextFile(params, function (err, newFileList) {\n if (err) {\n params.tryNum++\n setTimeout(function () { offThreadExtraction(params) }, params.tryNum * 2000)\n } else if (newFileList.length === 0) {\n const offThreadStatus = {\n offThreadParams: null,\n offThreadWip: false\n }\n params.freezrUserAppListDB.update(params.appFS.appName, offThreadStatus, { replaceAllFields: false }, function (err, result) {\n if (err) felog('offThreadExtraction - all done but error at end', { params })\n })\n } else {\n params.tryNum = 1\n params.filesRemaining = newFileList\n const offThreadStatus = {\n tryNum: 1,\n versionDate: params.versionDate,\n filesRemaining: newFileList\n }\n params.freezrUserAppListDB.update(params.appFS.appName, offThreadStatus, { replaceAllFields: false }, function (err, result) {\n if (err) {\n felog('offThreadWip freezrUserAppListDB - updating status interrupted ', { err, result })\n params.tryNum++\n }\n setTimeout(function () {\n offThreadExtraction(params)\n }, 5000)\n })\n }\n })\n }\n })\n }\n}\nexports.appMgmtActions = function (req, res) /* deleteApp updateApp */ {\n // app.post('/v1/account/appMgmtActions.json', accountLoggedInAPI, addUserAppsAndPermDBs, accountHandler.appMgmtActions)\n // onsole.log(\"At app mgmt actions \"+JSON.stringify(req.body));\n\n var action = (req.body && req.body.action) ? req.body.action : null\n var appName = (req.body && req.body.app_name) ? req.body.app_name : null\n\n if (action === 'removeAppFromHomePage') {\n req.freezrUserAppListDB.update(appName, { removed: true }, { replaceAllFields: false }, function (err, result) {\n if (err) {\n felog('appMgmtActions', 'removeAppFromHomePage err for ' + appName, err)\n helpers.send_failure(res, err, 'account_handler', exports.version, '', 'could not mark as removed')\n } else {\n helpers.send_success(res, { success: true })\n }\n })\n } else if (action === 'deleteApp') {\n async.waterfall([\n function (cb) {\n req.freezrUserAppListDB.delete_record(appName, null, cb)\n },\n function (result, cb) {\n req.freezrUserPermsDB.delete_records({ requestor_app: appName }, null, cb)\n },\n function (results, cb) {\n const folderPath = helpers.FREEZR_USER_FILES_DIR + '/' + req.session.logged_in_user_id + '/apps/' + appName\n fileHandler.deleteLocalFolderAndContents(folderPath, cb)\n },\n function (cb) {\n req.freezrUserDS.getorInitAppFS(appName, {}, cb)\n },\n function (appFS, cb) {\n appFS.removeAllAppFiles(null, cb)\n },\n function (cb) {\n fdlog('need to remove tables when remove app too?')\n // 2020 todo - when deleting app, get user to also approve deleting the app_tables\n // send app_table names to know what to delete\n // create a new perm flow to get the userds and delete all relevant tables\n // also then remove all table_id related to the above tables in permissions\n // also need to check if tables are being used y other apps\n cb(null)\n }\n ], function (err) {\n if (err) {\n helpers.send_internal_err_failure(res, 'account_handler', exports.version, 'appMgmtActions - deleteApp', 'Internal error trying to delete app. ')\n } else {\n // onsole.log(\"success in deleting app\")\n helpers.send_success(res, { success: true })\n }\n })\n } else if (action === 'updateApp') {\n fdlog('going to updateApp ', appName)\n\n var flags = new Flags({ app_name: appName })\n const realAppName = appName\n const userDS = req.freezrUserDS\n let manifest = null\n let appFS\n const realAppPath = helpers.FREEZR_USER_FILES_DIR + '/' + req.session.logged_in_user_id + '/apps/' + realAppName\n\n async.waterfall([\n // updateApp 1. make sure data and file names exist\n function (cb) {\n if (!req.session.logged_in_user_id) {\n cb(helpers.missing_data('user_id'))\n } else if (!helpers.valid_app_name(realAppName)) {\n cb(helpers.invalid_data('app name: ' + realAppName, 'account_handler', exports.version, 'appMgmtActions'))\n } else if (!realAppName || realAppName.length < 1) {\n cb(helpers.invalid_data('app name missing - ', '', exports.version, 'install_app'))\n } else if (helpers.system_apps.indexOf(realAppName) > -1 || !helpers.valid_app_name(realAppName)) {\n cb(helpers.invalid_data('app name not allowed: ' + appName, 'account_handler', exports.version, 'install_app'))\n } else if (!userDS) {\n cb(helpers.missing_data('userDS'))\n } else {\n cb(null)\n }\n },\n\n // get appFS and delete the local folder (if using cloud storage)\n function (cb) {\n userDS.getorInitAppFS(realAppName, {}, cb)\n },\n function (userAppFS, cb) {\n appFS = userAppFS\n if (appFS.fsParams.type === 'local' || appFS.fsParams.type === 'glitch') {\n cb(null)\n } else {\n fileHandler.deleteLocalFolderAndContents(realAppPath, cb)\n }\n },\n\n // reset cache and read app manifest and update perms and app record\n function (cb) {\n appFS.cache.appfiles = {}\n\n appFS.readAppFile(helpers.APP_MANIFEST_FILE_NAME, {}, cb)\n },\n function (readmanifest, cb) {\n if (readmanifest) {\n try {\n manifest = json.parse(readmanifest)\n } catch (e) {\n felog('error parsing manifest ', e)\n flags.add('notes', 'manifest_read_err')\n }\n } else {\n flags.add('notes', 'manifest_missing')\n }\n if (!manifest) manifest = {}\n if (!manifest.identifier) manifest.identifier = realAppName\n if (!manifest.display_name) manifest.display_name = realAppName\n if (!manifest.version) manifest.version = 0\n\n flags = fileHandler.checkManifest(manifest, realAppName, manifest.version, flags)\n\n updatePermissionRecordsFromManifest(req.freezrUserPermsDB, realAppName, manifest, cb)\n },\n\n function (cb) {\n createOrUpdateUserAppList(req.freezrUserAppListDB, manifest, null, cb)\n }\n ],\n function (err, info) {\n flags.meta.app_name = realAppName\n if (err) {\n flags.add('errors', 'err_unknown', { function: 'appMgmtActions update', text: JSON.stringify(err) })\n } else if (info.isUpdate) {\n flags.add('notes', 'app_updated_msg')\n flags.meta.didwhat = 'updated'\n } else {\n flags.meta.didwhat = 'uploaded'\n }\n helpers.send_success(res, flags.sentencify())\n })\n } else {\n helpers.send_failure(res, new Error('unknown action'), 'account_handler', exports.version, 'appMgmtActions')\n }\n}\n\n// PERMISSIONS\n// format: {requestor_app, name, table_id, type, description, 'returnFields', 'searchFields'}\nexports.CEPSrequestorAppPermissions = function (req, res) {\n // app.get('/ceps/perms/get', userAPIRights, addUserPermDBs, accountHandler.CEPSrequestorAppPermissions)\n\n const requestorId = req.freezrTokenInfo.requestor_id // requestor and requestee are the same\n const requestorApp = req.freezrTokenInfo.app_name\n fdlog('CEPSrequestorAppPermissions for ', { requestorApp, requestorId }) // + 'req.freezrTokenInfo', req.freezrTokenInfo)\n\n // if (req.query) { console.log('todo - have to add queries on permission name and table_id') }\n req.freezrUserPermsDB.query({ requestor_app: requestorApp, status: { $ne: 'removed' } }, {}, function (err, returnPerms) {\n fdlog('CEPSrequestorAppPermissions ', { requestorApp, returnPerms })\n if (err) {\n helpers.send_failure(res, err, 'account_handler', exports.version, 'requestorApp')\n } else {\n fdlog({ returnPerms })\n helpers.send_success(res, returnPerms)\n }\n })\n}\nexports.allRequestorAppPermissions = function (req, res) {\n // app.get('/v1/permissions/getall/:app_name', userAPIRights, addUserPermDBs, accountHandler.allRequestorAppPermissions)\n // optional query: groupall\n // groupall and having a call forward (req.freezrInternalCallFwd) groups the items in various categories\n\n const requestorApp = req.params.target_app || req.params.app_name // target_app for account/perms\n fdlog('allRequestorAppPermissions for requestorApp ' + requestorApp + ' target_app is' + req.params.target_app) // + 'req.freezrTokenInfo', req.freezrTokenInfo)\n if (req.freezrTokenInfo.app_name !== req.params.app_name && req.freezrTokenInfo.app_name !== 'info.freezr.account') {\n felog('allRequestorAppPermissions', 'auth error', req.freezrTokenInfo.app_name, req.params.app_name, ' - tocken info: ', req.freezrTokenInfo)\n helpers.send_failure(res, new Error('auth error - allRequestorAppPermissions'), 'account_handler', exports.version, 'disallowed')\n } else {\n req.freezrUserPermsDB.query({ requestor_app: requestorApp, status: { $ne: 'removed' } }, {}, function (err, returnPerms) {\n fdlog('allRequestorAppPermissions : req.query: ', { requestorApp, returnPerms })\n if (err) {\n helpers.send_failure(res, err, 'account_handler', exports.version, 'requestorApp')\n } else if ((req.query && req.query.groupall) || req.freezrIntermediateCallFwd || req.freezrInternalCallFwd) {\n var ret = {}\n ret[requestorApp] = groupPermissions(returnPerms, requestorApp)\n ret[requestorApp].app_name = '' // todo get app name and display name [later: why blank?]\n ret[requestorApp].app_display_name = requestorApp\n\n if (req.freezrIntermediateCallFwd) { /* ie coming from internal request for perm */\n fdlog('have freezrIntermediateCallFwd', { ret })\n req.freezrIntermediateCallFwd(null, ret)\n } else if (req.freezrInternalCallFwd) { /* ie coming from internal request for perm */\n fdlog('have freezrInternalCallFwd', { ret })\n req.freezrInternalCallFwd(null, ret)\n } else {\n // fdlog('sending success - allRequestorAppPermissions - NO freezrIntermediateCallFwd')\n helpers.send_success(res, ret)\n }\n } else {\n // fdlog({ returnPerms })\n helpers.send_success(res, returnPerms)\n }\n })\n }\n}\nfunction groupPermissions (returnPermissions, appName) {\n var groupedPermissions = {\n outside_scripts: [],\n thisAppToThisApp: [],\n thisAppToOtherApps: [],\n otherAppsToThisApp: [],\n unknowns: []\n }\n\n if (!returnPermissions || returnPermissions.length === 0) {\n return groupedPermissions\n } else {\n let aPerm\n for (var i = 0; i < returnPermissions.length; i++) {\n aPerm = returnPermissions[i]\n /*\n if (aPerm.type === 'outside_scripts') {\n groupedPermissions.outside_scripts.push(aPerm)\n } else\n */\n if (['share_records', 'db_query'].indexOf(aPerm.type) > -1 && aPerm.requestor_app === appName && helpers.startsWith(aPerm.table_id, appName)) {\n groupedPermissions.thisAppToThisApp.push(aPerm)\n } else if (['upload_pages'].indexOf(aPerm.type) > -1 && aPerm.requestor_app === appName) {\n groupedPermissions.thisAppToThisApp.push(aPerm)\n } else if (['share_records', 'read_all', 'write_all', 'db_query'].indexOf(aPerm.type) > -1 && aPerm.requestor_app !== appName && helpers.startsWith(aPerm.table_id, appName)) {\n groupedPermissions.otherAppsToThisApp.push(aPerm)\n } else if (['share_records', 'read_all', 'write_all', 'db_query'].indexOf(aPerm.type) > -1 && aPerm.requestor_app === appName && !helpers.startsWith(aPerm.table_id, appName)) {\n groupedPermissions.thisAppToOtherApps.push(aPerm)\n } else {\n groupedPermissions.unknowns.push(aPerm)\n felog('groupPermissions', 'ERROR - why this . uknown permission ' + JSON.stringify(aPerm))\n }\n }\n // onsole.log(\"returning groupedPermissions\", groupedPermissions)\n return groupedPermissions\n }\n}\nexports.generatePermissionHTML = function (req, res) {\n // app.get('/v1/permissions/gethtml/:app_name', userAPIRights, addUserPermDBs, accountHandler.generatePermissionHTML)\n fdlog('generatePermissionHTML ' + req.url, 'req.params', req.params)\n\n if (!req.freezrTokenInfo) fdlog('generatePermissionHTML Missing req.freezrTokenInfo')\n // fdlog('generatePermissionHTML req.params', req.params, 'req.query', req.query, 'switch? ' + (req.path.indexOf('/account/perms') === 0) + ' ' + req.path.indexOf('/account/perms'))\n if (req.query.table_id && req.path.indexOf('/account/perms') === 0) { // ie parameters are under query\n fdlog('switch fpr account/perms') // todo - review\n // req.params.app_name = req.params.target_app\n // req.params.requestee_app = req.query.requestor_app\n }\n req.freezrIntermediateCallFwd = function (err, results) {\n if (err) felog('generatePermissionHTML', 'err in generatePermissionHTML - freezrIntermediateCallFwd ', err)\n fdlog('freezrIntermediateCallFwd results ', JSON.stringify(results))\n var Mustache = require('mustache')\n // todo add option to wrap pcard in html header\n fileHandler.getLocalSystemAppFileContent('systemapps/info.freezr.account/account_permobject.html', function (err, htmlForPermGroup) {\n let htmlContent = ''\n if (err || !htmlForPermGroup) {\n felog('generatePermissionHTML', 'file missing', 'html file missing')\n htmlContent = 'error - unable to retrieve html'\n } else {\n htmlForPermGroup = htmlForPermGroup.toString()\n Object.keys(results).forEach(function (appName, i) {\n const appObj = results[appName]\n htmlContent += ''\n htmlContent += '


    ' + appObj.app_display_name + '
    ' + appName + '
    '\n\n htmlContent += '

    '\n\n const IntroText = {\n outside_scripts: 'This app is asking for permission to be able to access programming scripts from the web. This can be VERY DANGEROUS. DO NOT ACCEPT THIS unless you totally trust the app provider and the source of the script.
    PROCEED WITH CAUTION. ',\n thisAppToThisApp: 'This app is asking for permission to share data from this app:',\n thisAppToOtherApps: 'This app is asking for permissions to access data from other apps:',\n otherAppsToThisApp: 'Other apps are asking for permission to see your data from this app:',\n unkowns: 'These permissions are uknkown to freezr'\n }\n const addPermSentence = function (aPerm) {\n let sentence = ''\n const hasBeenAccepted = (aPerm.granted && !aPerm.outDated)\n const otherApp = !helpers.startsWith(aPerm.table_id, aPerm.requestor_app)\n const accessWord = otherApp ? 'access and share' : 'share'\n\n sentence += hasBeenAccepted ? 'This app is able to ' : 'This app wants to be able to '\n if (aPerm.type === 'share_records') {\n sentence += accessWord + ' individual data records from the table ' + '\" : '>') + aPerm.table_id + ',' + ' with the your contacts and the public.
    '\n } else if (aPerm.type === 'upload_pages') {\n sentence += accessWord + ' individual files with the public.
    '\n } else if (aPerm.type === 'read_all') {\n sentence += accessWord + ' read all the records in the table: ' + \"\" + aPerm.table_id + ',' + '.
    '\n } else if (aPerm.type === 'db_query') {\n sentence += accessWord + 'query the table: ' + \"\" + aPerm.table_id + ',' + '.
    '\n }\n if (aPerm.outDated) sentence += 'This permission was previously granted but the permission paramteres have changed to you would need to re-authorise it.
    '\n aPerm.sentence = sentence\n aPerm.action = hasBeenAccepted ? 'Deny' : 'Accept'\n return aPerm\n }\n\n let permCount = 0\n Object.keys(appObj).forEach(function (permType, i) {\n if (permType !== 'app_name' && permType !== 'app_display_name') {\n var toRender = {\n perm_grouping_intro: IntroText[permType],\n perm_list: appObj[permType],\n perm_type: permType\n }\n if (toRender.perm_list.length > 0) {\n // toRender.perm_list =\n permCount++\n toRender.perm_list.map(addPermSentence)\n // fdlog('permobject - toRender for key: ', permType, ' for toRender.perm_list: ', toRender.perm_list)\n htmlContent += Mustache.render(htmlForPermGroup, toRender)\n }\n }\n })\n if (permCount === 0) htmlContent += '
    There are no requests to share data related to this app.
    '\n })\n }\n if (req.freezrInternalCallFwd) {\n req.freezrInternalCallFwd(err, { all_perms_in_html: htmlContent })\n } else {\n helpers.send_success(res, { all_perms_in_html: htmlContent })\n }\n })\n }\n exports.allRequestorAppPermissions(req, res)\n}\nexports.changeNamedPermissions = function (req, res) {\n // app.put('/v1/permissions/change/:requestee_app_table', accountLoggedInAPI, addUserPermsAndRequesteeDB, addPublicRecordsDB, accountHandler.changeNamedPermissions)\n\n fdlog('changePermissions ' + JSON.stringify(req.body))\n if (req.body.changeList && req.body.changeList.length === 1 && req.body.changeList[0].name && req.body.changeList[0].action && req.body.changeList[0].table_id && req.body.changeList[0].requestor_app) {\n const list = req.body.changeList[0]\n\n const permQuery = { name: list.name, table_id: list.table_id, requestor_app: list.requestor_app }\n req.freezrUserPermsDB.query(permQuery, {}, function (err, results) {\n if (err) {\n felog('changeNamedPermissions', err)\n helpers.send_failure(res, helpers.error('error getting permissions from db'), 'account_handler', exports.version, 'changeNamedPermissions')\n } else if (results.length === 0) {\n helpers.send_failure(res, helpers.error('permission record not found - try re-installing app'), 'account_handler', exports.version, 'changeNamedPermissions')\n } else if (results.length > 1) {\n req.freezrUserPermsDB.delete(results[1]._id, function (err, ret) {\n if (err) { felog('changeNamedPermissions', 'could not delete extra permission') } else { felog('changeNamedPermissions', 'extra permission SNBH') }\n helpers.send_failure(res, helpers.error('SNBH - more than one permission record'), 'account_handler', exports.version, 'changeNamedPermissions')\n })\n } else if (list.action === 'Accept' || list.action === 'Deny') {\n fdlog('changeNamedPermissions - going to accept or deny:', list.action)\n // update and also\n const granted = (list.action === 'Accept')\n const change = { outDated: false, granted, revokeIsWip: (!granted), status: (granted ? 'granted' : 'declined') }\n // const change = { outDated: false, granted, revokeIsWip: (!granted) }\n const oldGrantees = results[0].grantees || []\n const permId = results[0]._id\n req.freezrUserPermsDB.update(results[0]._id, change, { replaceAllFields: false }, function (err, results) {\n if (err) {\n felog('changeNamedPermissions', 'ERR in update freezrUserPermsDB', err)\n helpers.send_failure(res, err, 'account_handler', exports.version, 'changeNamedPermissions')\n } else if (!granted) {\n const fullPermName = (permQuery.requestor_app + '/' + permQuery.name).replace(/\\./g, '. ')\n // todo - this function needs to scale - in case of too many records, split in chunks\n // Get all records with grantee permissions and remove the permission\n async.forEach(oldGrantees, function (grantee, cb2) {\n // console.log('THIS NEEDS TO BE UPDATED!!!??? 2021')\n var thequery = {}\n thequery['_accessible.' + grantee + '.' + fullPermName + '.granted'] = true\n req.freezrRequesteeDB.query(thequery, {}, function (err, recs) {\n if (err) felog('changeNamedPermissions', 'ERR in freezrRequesteeDB query ', thequery, ' err: ', err)\n fdlog('todo - also need to update freezrPublicPermDB if there are no more public permissions')\n async.forEach(recs, function (rec, cb3) {\n const accessible = rec._accessible\n const publicid = (accessible[grantee] && accessible[grantee][fullPermName] && accessible[grantee][fullPermName].publicid) ? accessible[grantee][fullPermName].publicid : null\n if (accessible[grantee] && accessible[grantee][fullPermName]) delete accessible[grantee][fullPermName]\n if (helpers.isEmpty(accessible[grantee])) delete accessible[grantee]\n req.freezrRequesteeDB.update(rec._id, { accessible: accessible }, { replaceAllFields: false }, function (err) {\n if (err) felog('changeNamedPermissions', 'ERR in freezrRequesteeDB update ', rec._id, 'err: ', err)\n if (grantee !== '_public') {\n cb3(err)\n } else {\n // accessiblesQuery = {permissionName: permQuery.name, table_id: permQuery.table_id, requestor_app:permQuery.requestor_app, dataOwner:req.session.logged_in_user_id, originalRecordId:}\n req.freezrPublicRecordsDB.delete_record(publicid, cb3)\n }\n })\n }, cb2)\n })\n }, function (err) {\n if (err) felog('changeNamedPermissions', 'if error, the perm update should be added to a clean up list')\n if (err) {\n helpers.send_failure(res, helpers.invalid_data('Could not affect chenge throughout freezr.', 'account_handler'), 'account_handler', exports.version, 'changeNamedPermissions')\n } else {\n req.freezrUserPermsDB.update(permId, { revokeIsWip: false, grantees: [] }, { replaceAllFields: false }, function (err) {\n if (err) {\n felog('changeNamedPermissions', 'freezrUserPermsDB ERR in update permId ', permId, ' err: ', err)\n helpers.send_failure(res, helpers.invalid_data('Could not affect chenge throughout freezr.', 'account_handler'), 'account_handler', exports.version, 'changeNamedPermissions')\n } else {\n helpers.send_success(res, { success: true, name: permQuery.name, buttonId: req.body.changeList[0].buttonId, action: list.action, flags: null })\n }\n })\n }\n })\n } else { // granted\n fdlog('todo freezrPublicPermDB functionality needs to be tested')\n req.freezrPublicManifestsDb.query({ user_id: req.session.logged_in_user_id, app_name: list.requestor_app }, null, (err, results) => {\n if (err) {\n felog('changeNamedPermissions', 'error setting freezrPublicPermDB - also flag below needs to be set correctly')\n helpers.send_success(res, { success: true, name: permQuery.name, buttonId: req.body.changeList[0].buttonId, action: list.action, flags: ['freezrPublicPermDB - error reading record'] })\n } else {\n fdlog('todo - need to get each card as well')\n var permissions = [list.name]\n var recId = null\n if (results && results[0]) {\n recId = results[0]._id\n permissions = helpers.addToListAsUnique(results[0].permissions, list.name)\n }\n const write = {\n manifest: req.freezrRequestorManifest,\n cards: req.freezrPublicCards,\n ppages: req.freezrPublicPages,\n user_id: req.session.logged_in_user_id,\n app_name: list.requestor_app,\n permissions\n }\n const sendResult = function (err, result) {\n const flags = err ? ['freezrPublicPermDB - error setting record'] : null\n helpers.send_success(res, { success: true, name: permQuery.name, buttonId: req.body.changeList[0].buttonId, action: list.action, flags })\n }\n if (results && results[0]) {\n req.freezrPublicManifestsDb.update(recId, write, { replaceAllFields: true }, sendResult)\n } else {\n req.freezrPublicManifestsDb.create(recId, write, null, sendResult)\n }\n }\n })\n }\n })\n } else {\n helpers.send_failure(res, helpers.invalid_data('action needs to be Deny or Accept.', 'account_handler'), 'account_handler', exports.version, 'changeNamedPermissions')\n }\n })\n } else {\n helpers.send_failure(res, helpers.invalid_data('One request at a time can be accepted.', 'account_handler'), 'account_handler', exports.version, 'changeNamedPermissions')\n }\n}\n\nconst permissionObjectFromManifestParams = function (requestorApp, manifestPerm) {\n const PERMISSION_FIELD_TYPES = {\n requestor_app: 'string',\n table_id: 'string',\n type: 'string',\n name: 'string',\n description: 'string',\n return_fields: 'array',\n search_fields: 'array'\n // Added by freezr\n // granted: 'bool',\n // status: 'string',\n }\n let err = ''\n let returnpermission = null\n const name = manifestPerm.name\n if (!manifestPerm || typeof manifestPerm !== 'object' || !requestorApp) {\n felog('permissionObjectFromManifestParams', 'cannot make permission without a proper permission object ', { requestorApp, name })\n err = 'Cannot make permission without a proper permission object.'\n }\n if (!err && !name) {\n felog('permissionObjectFromManifestParams', 'cannot make permission without a name ', { requestorApp, name })\n err = 'Cannot make permission without a name.'\n }\n if (!err && (!manifestPerm.type || (!manifestPerm.table_id && manifestPerm.type !== 'upload_pages'))) {\n felog('permissionObjectFromManifestParams', 'cannot make permission without a table ', { manifestPerm, requestorApp, name })\n err = (err ? ' And ' : name + ': ') + 'Cannot make permission without a table_id or type. '\n }\n\n if (!err) {\n returnpermission = {}\n Object.entries(PERMISSION_FIELD_TYPES).forEach(([key, prop]) => {\n switch (prop) {\n case 'bool':\n err += key + ' '\n break\n case 'array':\n if (!manifestPerm[key]) {\n returnpermission[key] = []\n } else if (Array.isArray(manifestPerm[key])) {\n returnpermission[key] = [...manifestPerm[key]]\n } else {\n err += key + ' '\n }\n break\n case 'string':\n if (!manifestPerm[key]) {\n returnpermission[key] = ''\n } else if (typeof manifestPerm[key] === 'string') {\n returnpermission[key] = manifestPerm[key]\n } else {\n err += key + ' '\n }\n break\n default:\n err += key + ' '\n }\n })\n if (err) {\n err = name + ': Wrong types send for ' + err\n felog('permissionObjectFromManifestParams', 'cWrong types for permission ', { manifestPerm, requestorApp, name })\n returnpermission = null\n } else {\n returnpermission.name = name\n returnpermission.requestor_app = requestorApp\n }\n }\n\n return [err, returnpermission]\n}\nconst updatePermissionRecordsFromManifest = function (freezrUserPermsDB, appName, manifest, callback) {\n const manifestPerms = (manifest && manifest.permissions && Object.keys(manifest.permissions).length > 0) ? JSON.parse(JSON.stringify(manifest.permissions)) : null\n\n if (!manifest || !manifestPerms) {\n // these should already have been flagged\n callback(null)\n } else {\n // make a list of the schemas to re-iterate later and add blank permissions\n var cleanedManifestPermList = []\n var allPermissionNames = []\n var errs = []\n\n if (manifestPerms && manifestPerms.length > 0) {\n manifestPerms.forEach((statedPerm, i) => {\n const [err, cleanedManifestPerm] = permissionObjectFromManifestParams(appName, statedPerm)\n if (err) {\n errs.push(err)\n } else {\n cleanedManifestPermList.push(cleanedManifestPerm)\n allPermissionNames.push(statedPerm.name)\n }\n })\n }\n\n if (errs.length > 0) {\n callback(new Error(errs.join('\\n')))\n } else {\n freezrUserPermsDB.query({ requestor_app: appName }, {}, function (err, existingPermList) {\n if (err) {\n callback(err)\n } else {\n existingPermList.forEach((perm) => {\n if (!allPermissionNames.includes(perm.name)) allPermissionNames.push(perm.name)\n })\n }\n\n async.forEach(allPermissionNames, function (permissionName, cb) { // get perms\n const cleanedManifestPerm = objectFromList(cleanedManifestPermList, 'name', permissionName)\n const existingPermFromDb = objectFromList(existingPermList, 'name', permissionName)\n\n if (!existingPermFromDb) { // create new perm: cleanedManifestPerm.name for aUser\n cleanedManifestPerm.granted = false\n cleanedManifestPerm.status = 'pending'\n cleanedManifestPerm.grantees = []\n freezrUserPermsDB.create(null, cleanedManifestPerm, {}, cb)\n } else if (!cleanedManifestPerm) { // permission has been removed so it must be outdated\n existingPermFromDb.status = 'removed'\n existingPermFromDb.granted = false\n freezrUserPermsDB.update(existingPermFromDb._id, existingPermFromDb, {}, cb)\n } else if (permissionsAreSame(cleanedManifestPerm, existingPermFromDb)) { // leave as is\n if (existingPermFromDb.status === 'removed') {\n existingPermFromDb.status = 'pending' // ie no longer removed\n freezrUserPermsDB.update(existingPermFromDb._id, existingPermFromDb, {}, cb)\n } else {\n cb(null)\n }\n } else {\n cleanedManifestPerm.status = 'outdated'\n cleanedManifestPerm.granted = false\n cleanedManifestPerm.previousGrantees = existingPermFromDb.grantees\n cleanedManifestPerm.grantees = []\n freezrUserPermsDB.update(existingPermFromDb._id, cleanedManifestPerm, {}, cb)\n }\n },\n function (err) {\n if (err) {\n callback(err)\n } else {\n callback(null)\n }\n })\n })\n }\n }\n}\nconst objectFromList = function (objectList, param, value) {\n let foundObject = null\n objectList.forEach((anObject, i) => {\n if (anObject[param] === value) {\n foundObject = anObject\n }\n })\n return foundObject\n}\n\nconst createOrUpdateUserAppList = function (userAppListDb, manifest, env, callback) {\n // ??? note - currently updates the app_display_name only (and marks it as NOT removed)\n\n fdlog('createOrUpdateUserAppList ', { manifest })\n\n let appExists = false\n let appEntity = null\n\n const appName = (manifest.identifier) ? manifest.identifier : null\n const appDisplayName = (manifest.display_name) ? manifest.display_name : manifest.identifier\n\n async.waterfall([\n // 1 make sure data exists and that app exists\n function (cb) {\n if (!appName) {\n cb(helpers.missing_data('app_name', 'account_handler', exports.version, 'add_app'))\n } else if (!helpers.valid_app_name(appName)) {\n cb(helpers.invalid_data('app_name: ' + appName, 'account_handler', exports.version, 'createOrUpdateUserAppList'))\n } else {\n userAppListDb.read_by_id(appName, cb)\n }\n },\n\n // 3. create or update the app in the database.\n function (existingEntity, cb) {\n if (existingEntity) {\n appExists = true\n appEntity = existingEntity\n appEntity.manifest = manifest\n appEntity.removed = false\n appEntity.app_name = appName\n appEntity.app_display_name = appDisplayName\n if (env || appEntity.env) appEntity.env = env\n userAppListDb.update(appName, appEntity, { replaceAllFields: true }, cb)\n } else {\n appEntity = { app_name: appName, app_display_name: appDisplayName, manifest, env, removed: false }\n userAppListDb.create(appName, appEntity, null, cb)\n }\n }\n ],\n function (err) {\n if (err) {\n callback(err, {})\n } else {\n callback(null, { isUpdate: appExists })\n }\n })\n}\nconst permissionsAreSame = function (p1, p2) {\n return objectsaresame(p1, p2, ['granted', 'status', 'grantees', 'previousGrantees'])\n}\nconst objectsaresame = function (obj1, obj2, givenIgnorekeys = []) {\n var ignorekeys = [...givenIgnorekeys]\n if (typeof obj1 !== typeof obj2) {\n return false\n }\n if (!obj1 || ['string', 'boolean', 'number'].includes(typeof obj1)) return obj1 === obj2\n\n let areSame = true\n for (const key in obj1) {\n if ((!ignorekeys.includes(key)) && !objectsaresame(obj1[key], obj2[key], [], false)) {\n areSame = false\n }\n ignorekeys.push(key)\n }\n if (areSame) {\n for (const key in obj2) {\n if ((!ignorekeys.includes(key)) && !objectsaresame(obj1[key], obj2[key], [])) {\n areSame = false\n }\n }\n }\n return areSame\n}\n\n// VALIDATIONS\nexports.CEPSValidator = function (req, res) {\n // app.get('/ceps/perms/validationtoken', validationTokenChecks, addValidationTokenDB, accountHandler.CEPSValidator)\n // NOTE:'req.query.set' requires being logged in but others are public\n // req.query.set => userAPIRights => req.freezrTokenInfo\n // req.query.set and verify => req.freezrValidationTokenDB\n // req.query.validate => req.freezrCepsContacts req.freezrUserPermsDB req.freezrAppTokenDB\n\n if (req.params.action === 'set') {\n /*\n { data_owner_host : {host url},\n data_owner_user : {username},\n table_id : {table-identifier},\n requestor_user :{username of requestor on her/his own pds},\n permission : {name of permission},\n app_id: {requesting app’s id}, [-> change to requestor_app??]\n record_id : {_id of record being shared} // (optional)\n }\n */\n if (req.body.app_id !== req.freezrTokenInfo.app_name) {\n felog('CEPSValidator mismatch - body ', req.body, ' vs token ', req.freezrTokenInfo)\n helpers.send_failure(res, helpers.error('data mismatch'), 'account_handler', exports.version, 'CEPSValidator set')\n } else if (req.freezrTokenInfo.requestor_id !== req.freezrTokenInfo.owner_id) {\n felog('auth failure ', req.body, ' vs token ', req.freezrTokenInfo)\n helpers.send_failure(res, helpers.error('incomplete request'), 'account_handler', exports.version, 'CEPSValidator set')\n } else if (!req.body.data_owner_host || !req.body.data_owner_user) {\n felog('incomplete request ', req.body, ' vs token ', req.freezrTokenInfo)\n helpers.send_failure(res, helpers.error('incomplete request'), 'account_handler', exports.version, 'CEPSValidator set')\n } else {\n const validationtoken = helpers.randomText(30)\n const EXPIRATION_MINUTES = 5\n const expiration = new Date().getTime() + EXPIRATION_MINUTES * 60 * 1000\n\n const newValidator = {\n validation_token: validationtoken,\n expiration: expiration,\n requestor_user: req.freezrTokenInfo.requestor_id,\n data_owner_host: req.body.data_owner_host,\n data_owner_user: req.body.data_owner_user,\n permission: req.body.permission,\n table_id: req.body.table_id,\n app_id: req.freezrTokenInfo.app_name,\n record_id: req.body.record_id // {_id of record being shared} // (optional)\n }\n req.freezrValidationTokenDB.create(null, newValidator, null, function (err, returns) {\n fdlog('freezrValidationTokenDB.create ', { err, returns })\n if (err) {\n felog('error in freezrValidationTokenDB ', err)\n helpers.send_failure(res, helpers.error('incomplete request'), 'account_handler', exports.version, 'CEPSValidator set')\n } else {\n helpers.send_success(res, { validation_token: validationtoken, expiration: expiration })\n }\n })\n }\n } else if (req.params.action === 'validate') {\n /*\n validation_token: {Same as above}\n data_owner_user : {Same as above},\n data_owner_host : {Same as above},\n table_id : {Same as above},\n permission : {Same as above},\n app_id : {Same as above},\n requestor_user : {Same as above},\n requestor_host: {Same as above,\n */\n const requestor = req.query.requestor_user + '@' + req.query.requestor_host.replace(/\\./g, '_')\n const appToken = helpers.generateAppToken(requestor, req.query.app_id, null)\n const accessTokenExpiry = (new Date().getTime() + EXPIRY_DEFAULT)\n async.waterfall([\n // 1. basic checks\n function (cb) {\n if (!req.query.validation_token || !req.query.data_owner_user || !req.query.table_id || !req.query.permission || !req.query.requestor_user || !req.query.requestor_host) {\n felog('incomplete request ', req.body)\n cb(helpers.error('incomplete request'))\n } else {\n cb(null)\n }\n },\n\n // 2. make sure contact exists (todo - can also make sure that the person has turned on sharing. Need to create a flag in the userDS)\n function (cb) {\n req.freezrCepsContacts.query({ username: req.query.requestor_user, serverurl: req.query.requestor_host }, null, cb)\n },\n function (contacts, cb) {\n if (contacts && contacts.length > 0) {\n cb(null)\n } else {\n felog('no contacts')\n cb(helpers.error('invalid request - c'))\n }\n },\n\n // make sure permission has been granted\n function (cb) {\n const dbQuery = {\n table_id: req.query.table_id,\n name: req.query.permission,\n granted: true\n }\n req.freezrUserPermsDB.query(dbQuery, {}, function (err, grantedPerms) {\n if (err) {\n felog('invalid requst getting granted perms ', err)\n cb(helpers.error('invalid request 1'))\n } else if (!grantedPerms || grantedPerms.length < 1) {\n felog('invalid requst getting granted perms ', { grantedPerms })\n cb(helpers.error('invalid request 2'))\n } else {\n // [2021 - groups] freezrAttributes.reader\n let hasRight = false\n grantedPerms.forEach((item) => {\n if (item.grantees && item.grantees.includes(requestor)) hasRight = true\n })\n // console.log('todo - here check for each requestee or the groups they are in... also see if permission name will be used')\n felog('invalid request getting granted perms ', { err, requestor })\n cb(hasRight ? null : helpers.error('invalid request getting permissions granted'))\n }\n })\n },\n\n function (cb) {\n if (req.query.data_owner_host === req.query.requestor_host) {\n req.freezrValidationTokenDB.query(validationParamsFromQuery(req.query), null, function (err, returns) {\n if (err) {\n cb(err)\n } else if (!returns || returns.length < 1) {\n cb(helpers.error('not verifited 1'))\n } else {\n cb(null, { verified: true })\n }\n })\n } else {\n // https://flaviocopes.com/node-http-post\n const isLocalhost = helpers.startsWith(req.query.requestor_host, 'http://localhost')\n const https = isLocalhost ? require('http') : require('https')\n\n let queryString = 'validation_token=' + req.query.validation_token\n queryString += '&data_owner_user=' + req.query.data_owner_user\n queryString += '&data_owner_host=' + req.query.data_owner_host\n queryString += '&permission=' + req.query.permission\n queryString += '&table_id=' + req.query.table_id\n queryString += '&requestor_user=' + req.query.requestor_user\n queryString += '&requestor_host=' + req.query.requestor_host\n\n const options = {\n hostname: isLocalhost ? 'localhost' : req.query.requestor_host.slice(8),\n path: '/ceps/perms/validationtoken/verify?' + queryString,\n // protocol: isLocalhost ? 'http:' : 'https:',\n method: 'GET',\n headers: {\n 'Content-Type': 'application/json'\n // 'Content-Length': data.length\n }\n }\n if (isLocalhost) options.port = req.query.requestor_host.slice(17)\n const verifyReq = https.request(options, (verifyRes) => {\n verifyRes.on('data', (returns) => {\n cb(null, returns)\n })\n })\n verifyReq.on('error', (error) => {\n felog('error in veriffy ', error)\n cb(helpers.error('incomplete validation'))\n })\n verifyReq.write('') // data\n verifyReq.end()\n }\n },\n\n function (otherServerReturns, cb) {\n otherServerReturns = JSON.parse(otherServerReturns.toString())\n if (otherServerReturns.verified) {\n const write = {\n logged_in: false,\n requestor_id: requestor,\n owner_id: req.query.data_owner_user,\n app_name: req.query.app_id,\n app_token: appToken, // create token instead\n expiry: accessTokenExpiry,\n one_device: null,\n user_device: null,\n date_used: null // to be replaced by date\n }\n req.freezrAppTokenDB.create(null, write, null, cb)\n } else {\n felog('invalid request getting other server returns', { otherServerReturns })\n cb(helpers.error('invalid request 3'))\n }\n }\n ],\n function (err, results) {\n fdlog('CEPSValidator validate 5 ', { results, err })\n if (err) {\n helpers.send_failure(res, err, 'account_handler', exports.version, 'CEPSValidator validate')\n } else if (!results) {\n helpers.send_failure(res, err, 'account_handler', exports.version, 'CEPSValidator validate')\n } else {\n helpers.send_success(res, { validated: true, 'access-token': appToken, expiry: accessTokenExpiry })\n }\n })\n } else if (req.params.action === 'verify') {\n if (!req.query.validation_token || !req.query.data_owner_user || !req.query.data_owner_host || !req.query.table_id || !req.query.permission || !req.query.requestor_user || !req.query.requestor_host) {\n felog('Missing verification data query:', req.query, ' url:' + req.url)\n helpers.send_failure(res, helpers.error('invalid data'), 'account_handler', exports.version, 'CEPSValidator verify')\n } else {\n req.freezrValidationTokenDB.query(validationParamsFromQuery(req.query), null, function (err, returns) {\n if (err) {\n helpers.send_failure(res, helpers.error('incomplete request'), 'account_handler', exports.version, 'CEPSValidator verify')\n } else if (!returns || returns.length === 0) {\n helpers.send_failure(res, helpers.error('incomplete request'), 'account_handler', exports.version, 'CEPSValidator verify')\n } else {\n helpers.send_success(res, { verified: true })\n }\n })\n }\n } else {\n helpers.send_failure(res, helpers.error('invalid query'), 'account_handler', exports.version, 'CEPSValidator')\n }\n}\nconst validationParamsFromQuery = function (query) {\n const params = {\n validation_token: query.validation_token,\n data_owner_user: query.data_owner_user,\n data_owner_host: query.data_owner_host,\n permission: query.permission,\n table_id: query.table_id,\n requestor_user: query.requestor_user,\n expiration: { $gt: new Date().getTime() }\n }\n return params\n}\n\n// CONFIGS\nvar accountPagemanifest = { // manifest parameters for accounts pages\n home: {\n page_title: 'Accounts Home (Freezr)',\n css_files: ['./public/info.freezr.public/public/freezr_style.css', 'account_home.css'],\n page_url: 'account_home.html',\n initial_query_func: exports.list_all_user_apps,\n // initial_query: {'url':'/v1/account/app_list.json'},\n app_name: 'info.freezr.account',\n script_files: ['account_home.js']\n },\n settings: {\n page_title: 'Account Settings (freezr)',\n css_files: './public/info.freezr.public/public/freezr_style.css',\n page_url: 'account_settings.html',\n initial_query_func: function (req, res) {\n if (req.freezrUserDS && req.freezrUserDS.fsParams && req.freezrUserDS.dbParams) {\n req.freezrInternalCallFwd(null, { owner: req.freezrUserDS.owner, fsParamsType: req.freezrUserDS.fsParams.type, dbParamsType: req.freezrUserDS.dbParams.type })\n } else {\n req.freezrInternalCallFwd(null, { owner: null, error: 'no user ds found' })\n }\n },\n\n script_files: ['account_settings.js']\n },\n app_management: {\n page_title: 'Apps (freezr)',\n css_files: ['./public/info.freezr.public/public/freezr_style.css', 'account_app_management.css'],\n page_url: 'account_app_management.html',\n // initial_query: {'url':'/v1/account/app_list.json'},\n initial_query_func: exports.list_all_user_apps,\n script_files: ['account_app_management.js', './public/info.freezr.public/public/mustache.js']\n },\n reauthorise: {\n page_title: 'Apps (freezr)',\n css_files: ['./public/info.freezr.public/public/freezr_style.css', './public/info.freezr.public/public/firstSetUp.css'],\n page_url: 'account_reauthorise.html',\n initial_query_func: function (req, res) {\n if (req.freezrUserDS && req.freezrUserDS.owner && req.freezrUserDS.fsParams && req.freezrUserDS.fsParams.type) {\n req.freezrInternalCallFwd(null, { owner: req.freezrUserDS.owner, fsParamsType: req.freezrUserDS.fsParams.type })\n } else {\n req.freezrInternalCallFwd(null, { owner: null, error: 'no user ds found' })\n }\n },\n // initial_query: {'url':'/v1/account/app_list.json'},\n script_files: ['reauthorise.js']\n },\n perms: {\n page_title: 'Permissions (freezr)',\n css_files: ['./public/info.freezr.public/public/freezr_style.css', './public/info.freezr.public/public/firstSetUp.css'],\n page_url: 'account_perm.html',\n // initial_query: {'url':'/v1/account/app_list.json'},\n initial_query_func: exports.generatePermissionHTML,\n script_files: ['account_perm.js']\n },\n autoclose: {\n page_title: 'Autoclose tab (freezr)',\n page_url: 'account_autoclose.html',\n script_files: ['account_autoclose.js']\n },\n appdata_view: {\n page_title: 'View all my data ',\n page_url: 'account_appdata_view.html',\n css_files: ['account_appdata_view.css'],\n script_files: ['account_appdata_view.js', 'FileSaver.js']\n },\n appdata_backup: {\n page_title: 'Backup and Restore data',\n page_url: 'account_appdata_backup.html',\n css_files: ['account_appdata_backup.css'],\n script_files: ['account_appdata_backup.js', 'FileSaver.js']\n },\n contacts: {\n page_title: 'CEPS Contacts',\n page_url: 'contacts.html',\n css_files: ['contacts.css'],\n script_files: ['contacts.js']\n }\n}\n\n// Loggers\nconst LOG_ERRORS = true\nconst felog = function (...args) { if (LOG_ERRORS) helpers.warning('account_handler.js', exports.version, ...args) }\nconst LOG_DEBUGS = false\nconst fdlog = function (...args) { if (LOG_DEBUGS) console.log(...args) }", "dangerousExampleEn": "1. const path = require('path');\n2. const fs = require('fs');\n3. \n4. router.post('/Path', function (req, res) {\n5. const content = req.body.content;\n6. const BASE_DIR = 'C:/';\n7. \n8. fs.readFile(path.resolve(BASE_DIR,content), 'utf-8', function (err, data){\n9. if(err){\n10. console.log(err);\n11. }else{\n12. return res.send({data: data});\n13. }\n14. });\n15. });\nLine 8: This is vulnerable to path traversal because an external input is used without proper verification.", "safeExampleEn": "1. const path = require('path');\n2. const fs = require('fs');\n3. \n4. router.post('/Path', function (req, res) {\n5. const content = req.body.content;\n6. const BASE_DIR = 'C:/';\n7. \n8. const safe_content = content.replace(/[\\\\\\/]/gi, \"\");\n9. \n10. fs.readFile(path.resolve(BASE_DIR, safe_content), 'utf-8', function (err, data) {\n11. if (err) {\n12. console.log(err);\n13. return res.send({data: \"This is an invalid input.\"});\n14. } else {\n15. return res.send({data: data});\n16. }\n17. });\n18. });\nLine 10: This is secure because insecure characters are filtered using a regular expression.", "contexts": [{"lineNo": 464, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "464"}}, {"lineNo": 468, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "fullLocalPathTo"}}, {"lineNo": 468, "eventType": "sink", "messageKey": "jschk.PATH_CONTAMINATION.JS.defect.sink", "params": {}}]}} {"id": "5e11eedc99d35c69e6deeaf4dfe6c188f8e2406472236f4014a8f041bbcef34a", "license": {"spdx": ["OML", "RSA-MD"], "repo": "peakforest/peakforest-webapp", "path": "src/main/webapp/resources/nmrviewer/libs/uglify.js", "repo_head_hexsha": "8384d687e23d034925bc74ef8600749c0780fb2a", "stack_hexsha": "4a40a9462ec0d66266a03797d7ffc4e2dba9dc7c", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Path Traversal", "issueDescriptionEn": "When unverified external inputs are used to access system resources, attackers can manipulate the input values to access resources protected by the system, which lead to create vulnerability. Attackers can exploit this to modify or delete resources, leak system information, and cause service failure due to the conflicts between system resources.\nEnsure to use predefined identifiers only or filter out characters vulnerable to path traversal, i.e.\n/, , ., when you need to use the external input to refer to the system resources including a file or socket port.", "issueLineNumber": 5, "entireCode": "var fs = require(\"fs\"),\n uglify = require(\"uglify-js\");\n\nvar filename = process.argv[2],\n toplevel = uglify.parse(fs.readFileSync(filename, \"utf8\"), {filename: filename}),\n output = uglify.OutputStream({ascii_only: true}),\n compressor = uglify.Compressor(true),\n warn = uglify.AST_Node.warn;\n\nuglify.AST_Node.warn = function(s, o) {\n if (o.msg === \"Accidental global?\" && o.name === \"st\" && o.line === 1 && !o.col) return;\n warn.apply(this, arguments);\n};\n\ntoplevel.figure_out_scope();\ntoplevel.scope_warnings({\n undeclared: false,\n unreferenced: false,\n assign_to_global: true,\n func_arguments: false,\n nested_defuns: false,\n eval: false\n});\n\ntoplevel = toplevel.transform(compressor);\n\ntoplevel.figure_out_scope();\ntoplevel.compute_char_frequency(true);\ntoplevel.mangle_names(true);\ntoplevel.print(output);\n\nrequire(\"util\").print(output.get());", "dangerousExampleEn": "1. const path = require('path');\n2. const fs = require('fs');\n3. \n4. router.post('/Path', function (req, res) {\n5. const content = req.body.content;\n6. const BASE_DIR = 'C:/';\n7. \n8. fs.readFile(path.resolve(BASE_DIR,content), 'utf-8', function (err, data){\n9. if(err){\n10. console.log(err);\n11. }else{\n12. return res.send({data: data});\n13. }\n14. });\n15. });\nLine 8: This is vulnerable to path traversal because an external input is used without proper verification.", "safeExampleEn": "1. const path = require('path');\n2. const fs = require('fs');\n3. \n4. router.post('/Path', function (req, res) {\n5. const content = req.body.content;\n6. const BASE_DIR = 'C:/';\n7. \n8. const safe_content = content.replace(/[\\\\\\/]/gi, \"\");\n9. \n10. fs.readFile(path.resolve(BASE_DIR, safe_content), 'utf-8', function (err, data) {\n11. if (err) {\n12. console.log(err);\n13. return res.send({data: \"This is an invalid input.\"});\n14. } else {\n15. return res.send({data: data});\n16. }\n17. });\n18. });\nLine 10: This is secure because insecure characters are filtered using a regular expression.", "contexts": [{"lineNo": 4, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 5, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "filename"}}, {"lineNo": 5, "eventType": "sink", "messageKey": "jschk.PATH_CONTAMINATION.JS.defect.sink", "params": {}}]}} {"id": "7db3ed0f7b0725f2d504ec081b0301e512d9ae8ac49e2182e132476d3dbbe994", "license": {"spdx": ["MIT"], "repo": "sarasioux/cryptosuits-api", "path": "routes/index.js", "repo_head_hexsha": "a7ccee0aa78157ba9db7ea87788a3828a833890e", "stack_hexsha": "60c62a2f4e8307eff047886daf71dcdf2ebcaf05", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Path Traversal", "issueDescriptionEn": "When unverified external inputs are used to access system resources, attackers can manipulate the input values to access resources protected by the system, which lead to create vulnerability. Attackers can exploit this to modify or delete resources, leak system information, and cause service failure due to the conflicts between system resources.\nEnsure to use predefined identifiers only or filter out characters vulnerable to path traversal, i.e.\n/, , ., when you need to use the external input to refer to the system resources including a file or socket port.", "issueLineNumber": 35, "entireCode": "const express = require('express');\nconst Web3 = require('web3');\nconst TruffleContract = require(\"@truffle/contract\");\nconst fs = require('fs');\n\nconst { convert } = require('convert-svg-to-png');\n\n// Constants\nconst siteUrl = 'https://cryptosuits.herokuapp.com/';\n//const siteUrl = 'http://localhost:3000/';\nconst provider = 'wss://rinkeby.infura.io/ws/v3/721b7c03aa4d4431b4d6a5f9876d116a';\n//const provider = 'http://127.0.0.1:7545';\nconst ownerAccount = '0x00796e910Bd0228ddF4cd79e3f353871a61C351C'; // Address of the current queryer\n\n// Start the router\nconst router = express.Router();\nlet contract, deployed;\n\n// Set the reveal\nlet reveal = true;\n\nconst colors = ['6a8494', '75a375', '8c5851', '8971b1'];\n\n/* GET home page. */\nrouter.get('/', function(req, res) {\n res.json({msg:'GTFO'});\n});\n\nrouter.get('/json/:id', function(req, res) {\n const id = req.params.id;\n initContract().then(() => {\n getToken(id).then((exists) => {\n if(exists) {\n if(reveal) {\n const data = fs.readFileSync('./tokens/output3/' + id + '.json');\n const json = JSON.parse(data);\n json.ipfs = json.image;\n json.image = siteUrl + 'image/' + id;\n \n // Set the name\n json.name = 'CryptoSuit #' + id;\n \n res.json(json);\n } else {\n res.json({image: siteUrl + 'suit.png'});\n }\n } else {\n res.json({exists: exists});\n }\n });\n });\n});\n\nrouter.get('/json2/:id', function(req, res) {\n const id = req.params.id;\n //initContract().then(() => {\n //getToken(id).then((exists) => {\n //if(exists) {\n //if(reveal) {\n const data = fs.readFileSync('./tokens/output3/' + id + '.json');\n const json = JSON.parse(data);\n res.json(json);\n //} else {\n // res.json({image: siteUrl + 'suit.png'});\n //}\n //} else {\n // res.json({exists: exists});\n //}\n //});\n //});\n});\n\nrouter.get('/image/:id', function(req, res) {\n const id = req.params.id;\n const data = fs.readFileSync('./tokens/output3/' + id + '.json');\n const json = JSON.parse(data);\n const color = colors[Math.floor(Math.random() * 4)];\n let svg = ``;\n convert(svg, {width: 1000, height: 1000, puppeteer: { timeout: 0, args: ['--no-sandbox', '--disable-setuid-sandbox']}}).then((png) => {\n res.set('Content-Type', 'image/png');\n res.send(png);\n });\n});\n\nrouter.get('/CryptoSuits.json', function(req, res) {\n let rawData = fs.readFileSync(process.cwd() + '/build/contracts/CryptoSuits.json');\n let json = JSON.parse(rawData);\n res.json(json);\n});\n\nconst initContract = async function() {\n const web3 = new Web3(Web3.givenProvider || provider);\n let rawData = fs.readFileSync(process.cwd() + '/build/contracts/CryptoSuits.json');\n let json = JSON.parse(rawData);\n contract = TruffleContract(json);\n contract.setProvider(web3.currentProvider);\n contract.defaults({\n from: ownerAccount,\n gasPrice: 0\n });\n deployed = await contract.deployed();\n};\n\nconst getToken = async function(id) {\n try {\n const tokenExists = await deployed.exists.call(id, {from: ownerAccount, value: 0});\n return tokenExists;\n }\n catch (error) {\n console.log('Web3 Error', error);\n return false;\n }\n};\n\nmodule.exports = router;", "dangerousExampleEn": "1. const path = require('path');\n2. const fs = require('fs');\n3. \n4. router.post('/Path', function (req, res) {\n5. const content = req.body.content;\n6. const BASE_DIR = 'C:/';\n7. \n8. fs.readFile(path.resolve(BASE_DIR,content), 'utf-8', function (err, data){\n9. if(err){\n10. console.log(err);\n11. }else{\n12. return res.send({data: data});\n13. }\n14. });\n15. });\nLine 8: This is vulnerable to path traversal because an external input is used without proper verification.", "safeExampleEn": "1. const path = require('path');\n2. const fs = require('fs');\n3. \n4. router.post('/Path', function (req, res) {\n5. const content = req.body.content;\n6. const BASE_DIR = 'C:/';\n7. \n8. const safe_content = content.replace(/[\\\\\\/]/gi, \"\");\n9. \n10. fs.readFile(path.resolve(BASE_DIR, safe_content), 'utf-8', function (err, data) {\n11. if (err) {\n12. console.log(err);\n13. return res.send({data: \"This is an invalid input.\"});\n14. } else {\n15. return res.send({data: data});\n16. }\n17. });\n18. });\nLine 10: This is secure because insecure characters are filtered using a regular expression.", "contexts": [{"lineNo": 30, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "req"}}, {"lineNo": 34, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "34"}}, {"lineNo": 35, "eventType": "sink", "messageKey": "jschk.PATH_CONTAMINATION.JS.defect.sink", "params": {}}]}} {"id": "800f6c46438174419730427b21bedcd4dd37f457697b152b58e50ee6820b09d0", "license": {"spdx": ["MIT"], "repo": "gebhardm/flm03", "path": "MQTTrealtime/mqttrealtime.js", "repo_head_hexsha": "b623755d0f11c5b4d11a27eed29ee5a45ef4809c", "stack_hexsha": "0f379d5d9fd4d478af62e841d736096ca2551561", "match": "repo_path"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Path Traversal", "issueDescriptionEn": "When unverified external inputs are used to access system resources, attackers can manipulate the input values to access resources protected by the system, which lead to create vulnerability. Attackers can exploit this to modify or delete resources, leak system information, and cause service failure due to the conflicts between system resources.\nEnsure to use predefined identifiers only or filter out characters vulnerable to path traversal, i.e.\n/, , ., when you need to use the external input to refer to the system resources including a file or socket port.", "issueLineNumber": 45, "entireCode": "/*\n * This script serves a graph display on received MQTT messages\n * topic: /device//flx/voltage/ and\n * /device//flx/current/\n * payload: [[,],[<32 comma separated values>],\"mV|mA\"]\n * , Karlsruhe, 2016\n *\n * Released under the MIT license. See LICENSE file for details.\n *\n * Static http server part taken from (rpflorence on github)\n * https://gist.github.com/rpflorence/701407\n * ************************************************************\n * Note: see package.json for dependencies\n */\n// use http for page serving, fs for getting the *.html files\nvar httpport = 1080;\n\nvar http = require(\"http\").createServer(httphandler).listen(httpport);\n\nvar fs = require(\"fs\");\n\nvar url = require(\"url\");\n\nvar path = require(\"path\");\n\n// Serve the index.html page\nfunction httphandler(req, res) {\n var uri = url.parse(req.url).pathname, filename = path.join(process.cwd(), uri);\n var contentTypesByExtension = {\n \".html\": \"text/html\",\n \".css\": \"text/css\",\n \".js\": \"text/javascript\"\n };\n // serve requested files\n fs.exists(filename, function(exists) {\n if (!exists) {\n res.writeHead(404, {\n \"Content-Type\": \"text/plain\"\n });\n res.write(\"404 Not Found\\n\");\n res.end();\n return;\n }\n if (fs.statSync(filename).isDirectory()) filename += \"/index.html\";\n fs.readFile(filename, \"binary\", function(err, file) {\n if (err) {\n res.writeHead(500, {\n \"Content-Type\": \"text/plain\"\n });\n res.write(err + \"\\n\");\n res.end();\n return;\n }\n var headers = {};\n var contentType = contentTypesByExtension[path.extname(filename)];\n if (contentType) headers[\"Content-Type\"] = contentType;\n res.writeHead(200, headers);\n res.write(file, \"binary\");\n res.end();\n });\n });\n}", "dangerousExampleEn": "1. const path = require('path');\n2. const fs = require('fs');\n3. \n4. router.post('/Path', function (req, res) {\n5. const content = req.body.content;\n6. const BASE_DIR = 'C:/';\n7. \n8. fs.readFile(path.resolve(BASE_DIR,content), 'utf-8', function (err, data){\n9. if(err){\n10. console.log(err);\n11. }else{\n12. return res.send({data: data});\n13. }\n14. });\n15. });\nLine 8: This is vulnerable to path traversal because an external input is used without proper verification.", "safeExampleEn": "1. const path = require('path');\n2. const fs = require('fs');\n3. \n4. router.post('/Path', function (req, res) {\n5. const content = req.body.content;\n6. const BASE_DIR = 'C:/';\n7. \n8. const safe_content = content.replace(/[\\\\\\/]/gi, \"\");\n9. \n10. fs.readFile(path.resolve(BASE_DIR, safe_content), 'utf-8', function (err, data) {\n11. if (err) {\n12. console.log(err);\n13. return res.send({data: \"This is an invalid input.\"});\n14. } else {\n15. return res.send({data: data});\n16. }\n17. });\n18. });\nLine 10: This is secure because insecure characters are filtered using a regular expression.", "contexts": [{"lineNo": 28, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "req"}}, {"lineNo": 28, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "parse"}}, {"lineNo": 28, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "join"}}, {"lineNo": 28, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 45, "eventType": "sink", "messageKey": "jschk.PATH_CONTAMINATION.JS.defect.sink", "params": {}}]}} {"id": "38e06bf1bf80f2b80a53b34c4d38802cea24b7bcf2067bdf59bd09fc507d3fb1", "license": {"spdx": ["MIT"], "repo": "Crystal2030/nodestudy", "path": "day3/1.ajax/3.form.js", "repo_head_hexsha": "5b79f6c68ccfbe773d992de2fc7f40ad1400106e", "stack_hexsha": "3b2d53063da9b7bdde2859ff9d116278fd03b12d", "match": "repo_path"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Path Traversal", "issueDescriptionEn": "When unverified external inputs are used to access system resources, attackers can manipulate the input values to access resources protected by the system, which lead to create vulnerability. Attackers can exploit this to modify or delete resources, leak system information, and cause service failure due to the conflicts between system resources.\nEnsure to use predefined identifiers only or filter out characters vulnerable to path traversal, i.e.\n/, , ., when you need to use the external input to refer to the system resources including a file or socket port.", "issueLineNumber": 77, "entireCode": "//引入核心模块\nvar http = require('http');\n//引用URL解析URL参数\nvar url = require('url');\n//读写文件\nvar fs = require('fs');\nvar formidable = require('formidable');\nvar querystring = require('querystring');\nvar util = require('util');\nvar mime = require('mime');\n//创建http服务器\n//只有当提交form表单,并且是GET请求的时候,浏览器才会把表单进行序列化拼到URL后面\nhttp.createServer(function(req,res){\n //一定会返回一个对象\n // true的话urlObj的query也会是一个对象,否则就是一个字符串\n // username=zfpx&password= -> {username:'zfpx',password:}\n var urlObj = url.parse(req.url,true);\n //路径名\n var pathname = urlObj.pathname;\n if(pathname == '/'){\n //读取文件的内容\n fs.readFile('./3.form.html','utf8',function(err,data){\n res.end(data);\n })\n }else if(pathname == '/reg'){\n var result='';\n //当读到客户端提交过来的数据时会触发data事件,然后调用回调函数\n req.on('data',function(data){\n result +=data;\n })\n req.on('end',function(data){\n //取出请求体的内容类型\n var contentType = req.headers['content-type'];\n //如果请求体发过来的是序列化表单\n if(contentType =='application/x-www-form-urlencoded'){\n //把查询字符串转成对象\n var obj = querystring.parse(result);\n console.log(obj);\n }else if(contentType == 'application/json'){\n var obj = JSON.parse(result);\n console.log(obj);\n }\n\n //发送响应\n res.end('ok');\n })\n }else if(pathname == '/reg2'){\n // 构建一个解析器\n var formParser = new formidable.IncomingForm();\n ///用解析器解析请求体\n //把非file的input放在fields里\n //把文件类型的元素放在files里\n formParser.parse(req, function(err, fields, files) {\n fs.readFile(files.avatar.path,function(err,data){\n console.log(files.avatar);\n var filename = '/imgs/'+files.avatar.name;\n fs.writeFile('.'+filename,data,function(err){\n res.writeHead(200,{'Content-Type':'text/plain'});\n res.end(filename);\n })\n })\n });\n }else{\n /**\n * . 当前目录\n * ./3.uploader.js 当前目录下的某个文件\n * / : 1. 如果是在HTML的链接中,代表URL根目录\n * 2. 如果出现在读文件的时候,则它代表当前盘符的根目录\n *\n * 3.uploader.js: 代表当前目录下面的index.js文件 = ./3.uploader.js\n * .. :代表上一级目录\n */\n fs.exists('.'+pathname,function(exists){\n if(exists){\n //从文件名中获取文件的Content-Type\n res.setHeader('Content-Type',mime.lookup(pathname));\n fs.readFile('.'+pathname,function(err,data){\n res.end(data);\n })\n }else{\n res.statusCode = 404;\n res.end('404');\n }\n })\n }\n\n\n}).listen(8000);", "dangerousExampleEn": "1. const path = require('path');\n2. const fs = require('fs');\n3. \n4. router.post('/Path', function (req, res) {\n5. const content = req.body.content;\n6. const BASE_DIR = 'C:/';\n7. \n8. fs.readFile(path.resolve(BASE_DIR,content), 'utf-8', function (err, data){\n9. if(err){\n10. console.log(err);\n11. }else{\n12. return res.send({data: data});\n13. }\n14. });\n15. });\nLine 8: This is vulnerable to path traversal because an external input is used without proper verification.", "safeExampleEn": "1. const path = require('path');\n2. const fs = require('fs');\n3. \n4. router.post('/Path', function (req, res) {\n5. const content = req.body.content;\n6. const BASE_DIR = 'C:/';\n7. \n8. const safe_content = content.replace(/[\\\\\\/]/gi, \"\");\n9. \n10. fs.readFile(path.resolve(BASE_DIR, safe_content), 'utf-8', function (err, data) {\n11. if (err) {\n12. console.log(err);\n13. return res.send({data: \"This is an invalid input.\"});\n14. } else {\n15. return res.send({data: data});\n16. }\n17. });\n18. });\nLine 10: This is secure because insecure characters are filtered using a regular expression.", "contexts": [{"lineNo": 17, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "req"}}, {"lineNo": 17, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "parse"}}, {"lineNo": 74, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "74"}}, {"lineNo": 77, "eventType": "sink", "messageKey": "jschk.PATH_CONTAMINATION.JS.defect.sink", "params": {}}]}} {"id": "a5d1d1567905078125dda7e0217cafad85becbe833efc14391c7c875baa3ad57", "license": {"spdx": ["Apache-2.0"], "repo": "alex-charos/gi-web", "path": "app.js", "repo_head_hexsha": "7d7f7a2fe9582d2b555294f79e0509da6b58d824", "stack_hexsha": "869c64fe6a1d04f017006d82dc615f32cadfe7ca", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Path Traversal", "issueDescriptionEn": "When unverified external inputs are used to access system resources, attackers can manipulate the input values to access resources protected by the system, which lead to create vulnerability. Attackers can exploit this to modify or delete resources, leak system information, and cause service failure due to the conflicts between system resources.\nEnsure to use predefined identifiers only or filter out characters vulnerable to path traversal, i.e.\n/, , ., when you need to use the external input to refer to the system resources including a file or socket port.", "issueLineNumber": 20, "entireCode": "var express \t\t\t= require('express');\nvar sys \t\t\t\t= require('sys');\nvar exec \t\t\t\t= require('child_process').exec;\nvar execSync\t\t\t= require('child_process').execSync;\nvar fs \t\t\t\t\t= require('fs');\nvar app \t\t\t\t= express();\nvar gi_issue_git_dir \t= '.issues';\nvar gi_issue_root_dir \t= gi_issue_git_dir + '/issues';\nvar bodyParser = require('body-parser');\n\napp.use(bodyParser.json()); // support json encoded bodies\n\napp.get('/', function (req, res) {\n\tres.send(giList());\n});\n\napp.get('/issues/', function (req, res) {\n\tvar issueId = req.query[\"id\"];\n\tconsole.log( issueId );\n\tres.send(getIssue(issueId, gi_issue_root_dir+'/'+issueId.substring(0,2)+'/'+issueId.substring(2)));\n\t\n});\napp.post('/', function(req, res) {\n\tvar issueId = req.body.id;\n\tif (issueId === undefined) {\n\t\tconsole.log('new issue...');\n\t\tvar issue = createIssue(req.body);\n\t\tissueId = issue.id;\n\t}\n\n\tres.send(getIssue(issueId, gi_issue_root_dir+'/'+issueId.substring(0,2)+'/'+issueId.substring(2)));\n\n})\n\nfunction createIssue(issue) {\n\tvar issueShortId = execSync(\"gi new -s \\\"\"+ issue.header+\"\\\"\").toString().split(\"\\n\")[1].split(\" \")[2];\n\t\n\tvar issueId \t = execSync(\"gi show \" + issueShortId).toString().split(\"\\n\")[0].split(\" \")[1];\n\tconsole.log(issueId);\n\n\tissue.id = issueId;\n\n\treturn issue;\n\t\n}\n\nfunction giList() {\n\tvar issues = [];\n\t var issuesDir = getDirectoryContents(gi_issue_root_dir);\n\t for (var i=0; i < issuesDir.length; i++) {\n\t \tvar issueDir = getDirectoryContents(gi_issue_root_dir+'/'+ issuesDir[i]);\n\t \tvar issueId = issuesDir[i]+issueDir[0];\n\n\t \t issues.push(getIssue(issueId, gi_issue_root_dir+'/'+issuesDir[i]+'/'+issueDir[0]));\n\t }\n\t return issues;\n}\n\nfunction getIssue(issueId, directory) {\n\tvar headerAndDescription = fs.readFileSync(directory+'/description').toString().split(\"\\n\");\n\tvar header = headerAndDescription[0];\n\tvar description ='';\n\n\tfor (var i =1; i< headerAndDescription.length; i++) {\n\t\tdescription += headerAndDescription[i] ;\n\t\tif (i 2)\n\t\t\t\treturn;\n\t\t\tloginHubTimeoutCount++;\n\t\t\tif(loginHubTimeoutCount > 3) {\n\t\t\t\tloginHubTimeoutCount = 0;\n\t\t\t\tloginHubTimeoutDoneCount++;\n\t\t\t\tsetDeviceHub(stableHub);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tloginToHub();\n\t\t\treturn;\n\t\t}\n\t\tif (ws.bLoggedIn)\n\t\t\treturn;\n\t\tif (ws.received_challenge)\n\t\t\tsendLoginCommand(ws, ws.received_challenge);\n\t\telse {\n\t\t\tws.bLoggingIn = true;\n\t\t\tloginHubTimeoutCount = 0;\n\t\t}\n\t\tconsole.log('done loginToHub');\n\t});\n}\n\n\nsetInterval(loginToHub, RECONNECT_TO_HUB_PERIOD);\neventBus.on('connected', loginToHub);\n\nfunction sendLoginCommand(ws, challenge){\n\tvar objLogin = {challenge: challenge, pubkey: objMyPermanentDeviceKey.pub_b64};\n\tobjLogin.signature = ecdsaSig.sign(objectHash.getDeviceMessageHashToSign(objLogin), objMyPermanentDeviceKey.priv);\n\tnetwork.sendJustsaying(ws, 'hub/login', objLogin);\n\tws.bLoggedIn = true;\n\tsendTempPubkey(ws, objMyTempDeviceKey.pub_b64);\n\t//pow wallet modified version\n\t//network.initWitnessesIfNecessary(ws);\n\tresendStalledMessages();\n}\n\nfunction sendTempPubkey(ws, temp_pubkey, callbacks){\n\tif (!callbacks)\n\t\tcallbacks = {ifOk: function(){}, ifError: function(){}};\n\tnetwork.sendRequest(ws, 'hub/temp_pubkey', createTempPubkeyPackage(temp_pubkey), false, function(ws, request, response){\n\t\tif (response === 'updated')\n\t\t\treturn callbacks.ifOk();\n\t\tvar error = response.error || (\"unrecognized response: \"+JSON.stringify(response));\n\t\tcallbacks.ifError(error);\n\t});\n}\n\nfunction createTempPubkeyPackage(temp_pubkey){\n\tvar objTempPubkey = {\n\t\ttemp_pubkey: temp_pubkey, \n\t\tpubkey: objMyPermanentDeviceKey.pub_b64\n\t};\n\tobjTempPubkey.signature = ecdsaSig.sign(objectHash.getDeviceMessageHashToSign(objTempPubkey), objMyPermanentDeviceKey.priv);\n\treturn objTempPubkey;\n}\n\n\n// ------------------------------\n// rotation of temp keys\n\n\nfunction genPrivKey(){\n\tvar privKey;\n\tdo {\n\t\tconsole.log(\"generating new priv key\");\n\t\tprivKey = crypto.randomBytes(32);\n\t}\n\twhile (!ecdsa.privateKeyVerify(privKey));\n\treturn privKey;\n}\n\nvar last_rotate_wake_ts = Date.now();\n\nfunction rotateTempDeviceKeyIfCouldBeAlreadyUsed(){\n\tvar actual_interval = Date.now() - last_rotate_wake_ts;\n\tlast_rotate_wake_ts = Date.now();\n\tif (actual_interval > TEMP_DEVICE_KEY_ROTATION_PERIOD + 1000)\n\t\treturn console.log(\"woke up after sleep or high load, will skip rotation\");\n\tif (objMyTempDeviceKey.use_count === 0) // new key that was never used yet\n\t\treturn console.log(\"the current temp key was not used yet, will not rotate\");\n\t// if use_count === null, the key was set at start up, it could've been used before\n\trotateTempDeviceKey();\n}\n\nfunction rotateTempDeviceKey(){\n\tif (!saveTempKeys)\n\t\treturn console.log(\"no saving function\");\n\tconsole.log(\"will rotate temp device key\");\n\tnetwork.findOutboundPeerOrConnect(conf.WS_PROTOCOL+my_device_hub, function onLocatedHubForRotation(err, ws){\n\t\tif (err)\n\t\t\treturn console.log('will not rotate because: '+err);\n\t\tif (ws.readyState !== ws.OPEN)\n\t\t\treturn console.log('will not rotate because connection is not open');\n\t\tif (!ws.bLoggedIn)\n\t\t\treturn console.log('will not rotate because not logged in'); // reconnected and not logged in yet\n\t\tvar new_priv_key = genPrivKey();\n\t\tvar objNewMyTempDeviceKey = {\n\t\t\tuse_count: 0,\n\t\t\tpriv: new_priv_key,\n\t\t\tpub_b64: ecdsa.publicKeyCreate(new_priv_key, true).toString('base64')\n\t\t};\n\t\tsaveTempKeys(new_priv_key, objMyTempDeviceKey.priv, function(err){\n\t\t\tif (err){\n\t\t\t\tconsole.log('failed to save new temp keys, canceling: '+err);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tobjMyPrevTempDeviceKey = objMyTempDeviceKey;\n\t\t\tobjMyTempDeviceKey = objNewMyTempDeviceKey;\n\t\t\tbreadcrumbs.add('rotated temp device key');\n\t\t\tsendTempPubkey(ws, objMyTempDeviceKey.pub_b64);\n\t\t});\n\t});\n}\n\nfunction scheduleTempDeviceKeyRotation(){\n\tif (bScheduledTempDeviceKeyRotation)\n\t\treturn;\n\tbScheduledTempDeviceKeyRotation = true;\n\tconsole.log('will schedule rotation in 1 minute');\n\tsetTimeout(function(){\n\t\t// due to timeout, we are probably last to request (and receive) this lock\n\t\tmutex.lock([\"from_hub\"], function(unlock){\n\t\t\tconsole.log(\"will schedule rotation\");\n\t\t\trotateTempDeviceKeyIfCouldBeAlreadyUsed();\n\t\t\tlast_rotate_wake_ts = Date.now();\n\t\t\tsetInterval(rotateTempDeviceKeyIfCouldBeAlreadyUsed, TEMP_DEVICE_KEY_ROTATION_PERIOD);\n\t\t\tunlock();\n\t\t});\n\t}, 60*1000);\n}\n\n\n// ---------------------------\n// sending/receiving messages\n\nfunction deriveSharedSecret(ecdh, peer_b64_pubkey){\n\tvar shared_secret_src = ecdh.computeSecret(peer_b64_pubkey, \"base64\");\n\tvar shared_secret = crypto.createHash(\"sha256\").update(shared_secret_src).digest().slice(0, 16);\n\treturn shared_secret;\n}\n\nfunction decryptPackage(objEncryptedPackage){\n\tvar priv_key;\n\tif (objEncryptedPackage.dh.recipient_ephemeral_pubkey === objMyTempDeviceKey.pub_b64){\n\t\tpriv_key = objMyTempDeviceKey.priv;\n\t\tif (objMyTempDeviceKey.use_count)\n\t\t\tobjMyTempDeviceKey.use_count++;\n\t\telse\n\t\t\tobjMyTempDeviceKey.use_count = 1;\n\t\tconsole.log(\"message encrypted to temp key\");\n\t}\n\telse if (objMyPrevTempDeviceKey && objEncryptedPackage.dh.recipient_ephemeral_pubkey === objMyPrevTempDeviceKey.pub_b64){\n\t\tpriv_key = objMyPrevTempDeviceKey.priv;\n\t\tconsole.log(\"message encrypted to prev temp key\");\n\t\t//console.log(\"objMyPrevTempDeviceKey: \"+JSON.stringify(objMyPrevTempDeviceKey));\n\t\t//console.log(\"prev temp private key buf: \", priv_key);\n\t\t//console.log(\"prev temp private key b64: \"+priv_key.toString('base64'));\n\t}\n\telse if (objEncryptedPackage.dh.recipient_ephemeral_pubkey === objMyPermanentDeviceKey.pub_b64){\n\t\tpriv_key = objMyPermanentDeviceKey.priv;\n\t\tconsole.log(\"message encrypted to permanent key\");\n\t}\n\telse{\n\t\tconsole.log(\"message encrypted to unknown key\");\n\t\tsetTimeout(function(){\n\t\t\tthrow Error(\"message encrypted to unknown key, device \"+my_device_address+\", len=\"+objEncryptedPackage.encrypted_message.length+\". The error might be caused by restoring from an old backup or using the same keys on another device.\");\n\t\t}, 100);\n\t//\teventBus.emit('nonfatal_error', \"message encrypted to unknown key, device \"+my_device_address+\", len=\"+objEncryptedPackage.encrypted_message.length, new Error('unknown key'));\n\t\treturn null;\n\t}\n\t\n\tvar ecdh = crypto.createECDH('secp256k1');\n\tif (process.browser) // workaround bug in crypto-browserify https://github.com/crypto-browserify/createECDH/issues/9\n\t\tecdh.generateKeys(\"base64\", \"compressed\");\n\tecdh.setPrivateKey(priv_key);\n\tvar shared_secret = deriveSharedSecret(ecdh, objEncryptedPackage.dh.sender_ephemeral_pubkey);\n\tvar iv = new Buffer(objEncryptedPackage.iv, 'base64');\n\tvar decipher = crypto.createDecipheriv('aes-128-gcm', shared_secret, iv);\n\tvar authtag = new Buffer(objEncryptedPackage.authtag, 'base64');\n\tdecipher.setAuthTag(authtag);\n\tvar enc_buf = Buffer(objEncryptedPackage.encrypted_message, \"base64\");\n//\tvar decrypted1 = decipher.update(enc_buf);\n\t// under browserify, decryption of long buffers fails with Array buffer allocation errors, have to split the buffer into chunks\n\tvar arrChunks = [];\n\tvar CHUNK_LENGTH = 4096;\n\tfor (var offset = 0; offset < enc_buf.length; offset += CHUNK_LENGTH){\n\t//\tconsole.log('offset '+offset);\n\t\tarrChunks.push(decipher.update(enc_buf.slice(offset, Math.min(offset+CHUNK_LENGTH, enc_buf.length))));\n\t}\n\tvar decrypted1 = Buffer.concat(arrChunks);\n\tarrChunks = null;\n\tvar decrypted2 = decipher.final();\n\tbreadcrumbs.add(\"decrypted lengths: \"+decrypted1.length+\" + \"+decrypted2.length);\n\tvar decrypted_message_buf = Buffer.concat([decrypted1, decrypted2]);\n\tvar decrypted_message = decrypted_message_buf.toString(\"utf8\");\n\tconsole.log(\"decrypted: \"+decrypted_message);\n\tvar json = JSON.parse(decrypted_message);\n\tif (json.encrypted_package){ // strip another layer of encryption\n\t\tconsole.log(\"inner encryption\");\n\t\treturn decryptPackage(json.encrypted_package);\n\t}\n\telse\n\t\treturn json;\n}\n\n// a hack to read large text from cordova sqlite\nfunction readMessageInChunksFromOutbox(message_hash, len, handleMessage){\n\tvar CHUNK_LEN = 1000000;\n\tvar start = 1;\n\tvar message = '';\n\tfunction readChunk(){\n\t\tdb.query(\"SELECT SUBSTR(message, ?, ?) AS chunk FROM outbox WHERE message_hash=?\", [start, CHUNK_LEN, message_hash], function(rows){\n\t\t\tif (rows.length !== 1)\n\t\t\t\tthrow Error(rows.length+' msgs by hash in outbox');\n\t\t\tmessage += rows[0].chunk;\n\t\t\tstart += CHUNK_LEN;\n\t\t\t(start > len) ? handleMessage(message) : readChunk();\n\t\t});\n\t}\n\treadChunk();\n}\n\nfunction resendStalledMessages(){\n\tconsole.log(\"resending stalled messages\");\n\tif (!objMyPermanentDeviceKey)\n\t\treturn console.log(\"objMyPermanentDeviceKey not set yet, can't resend stalled messages\");\n\tmutex.lockOrSkip(['stalled'], function(unlock){\n\t\tvar bCordova = (typeof window !== 'undefined' && window && window.cordova);\n\t\tdb.query(\n\t\t\t\"SELECT \"+(bCordova ? \"LENGTH(message) AS len\" : \"message\")+\", message_hash, `to`, pubkey, hub \\n\\\n\t\t\tFROM outbox JOIN correspondent_devices ON `to`=device_address \\n\\\n\t\t\tWHERE outbox.creation_date<\"+db.addTime(\"-1 MINUTE\")+\" ORDER BY outbox.creation_date\", \n\t\t\tfunction(rows){\n\t\t\t\tconsole.log(rows.length+\" stalled messages\");\n\t\t\t\tasync.eachSeries(\n\t\t\t\t\trows, \n\t\t\t\t\tfunction(row, cb){\n\t\t\t\t\t\tif (!row.hub){ // weird error\n\t\t\t\t\t\t\teventBus.emit('nonfatal_error', \"no hub in resendStalledMessages: \"+JSON.stringify(row)+\", l=\"+rows.length, new Error('no hub'));\n\t\t\t\t\t\t\treturn cb();\n\t\t\t\t\t\t}\n\t\t\t\t\t\t//\tthrow Error(\"no hub in resendStalledMessages: \"+JSON.stringify(row));\n\t\t\t\t\t\tvar send = function(message){\n\t\t\t\t\t\t\tvar objDeviceMessage = JSON.parse(message);\n\t\t\t\t\t\t\t//if (objDeviceMessage.to !== row.to)\n\t\t\t\t\t\t\t// throw \"to mismatch\";\n\t\t\t\t\t\t\tconsole.log('sending stalled '+row.message_hash);\n\t\t\t\t\t\t\tsendPreparedMessageToHub(row.hub, row.pubkey, row.message_hash, objDeviceMessage, {ifOk: cb, ifError: function(err){ cb(); }});\n\t\t\t\t\t\t};\n\t\t\t\t\t\tbCordova ? readMessageInChunksFromOutbox(row.message_hash, row.len, send) : send(row.message);\n\t\t\t\t\t},\n\t\t\t\t\tunlock\n\t\t\t\t);\n\t\t\t}\n\t\t);\n\t});\n}\n\nsetInterval(resendStalledMessages, SEND_RETRY_PERIOD);\n\n// reliable delivery\n// first param is either WebSocket or hostname of the hub\nfunction reliablySendPreparedMessageToHub(ws, recipient_device_pubkey, json, callbacks, conn){\n\tvar recipient_device_address = objectHash.getDeviceAddress(recipient_device_pubkey);\n\tconsole.log('will encrypt and send to '+recipient_device_address+': '+JSON.stringify(json));\n\t// encrypt to recipient's permanent pubkey before storing the message into outbox\n\tvar objEncryptedPackage = createEncryptedPackage(json, recipient_device_pubkey);\n\t// if the first attempt fails, this will be the inner message\n\tvar objDeviceMessage = {\n\t\tencrypted_package: objEncryptedPackage\n\t};\n\tvar message_hash = objectHash.getBase64Hash(objDeviceMessage);\n\tconn = conn || db;\n\tconn.query(\n\t\t\"INSERT INTO outbox (message_hash, `to`, message) VALUES (?,?,?)\", \n\t\t[message_hash, recipient_device_address, JSON.stringify(objDeviceMessage)], \n\t\tfunction(){\n\t\t\tif (callbacks && callbacks.onSaved)\n\t\t\t\tcallbacks.onSaved();\n\t\t\tsendPreparedMessageToHub(ws, recipient_device_pubkey, message_hash, json, callbacks);\n\t\t}\n\t);\n}\n\n// first param is either WebSocket or hostname of the hub\nfunction sendPreparedMessageToHub(ws, recipient_device_pubkey, message_hash, json, callbacks){\n\tif (!callbacks)\n\t\tcallbacks = {ifOk: function(){}, ifError: function(){}};\n\tif (typeof ws === \"string\"){\n\t\tvar hub_host = ws;\n\t\tnetwork.findOutboundPeerOrConnect(conf.WS_PROTOCOL+hub_host, function onLocatedHubForSend(err, ws){\n\t\t\tif (err)\n\t\t\t\treturn callbacks.ifError(err);\n\t\t\tsendPreparedMessageToConnectedHub(ws, recipient_device_pubkey, message_hash, json, callbacks);\n\t\t});\n\t}\n\telse\n\t\tsendPreparedMessageToConnectedHub(ws, recipient_device_pubkey, message_hash, json, callbacks);\n}\n\n// first param is WebSocket only\nfunction sendPreparedMessageToConnectedHub(ws, recipient_device_pubkey, message_hash, json, callbacks){\n\tnetwork.sendRequest(ws, 'hub/get_temp_pubkey', recipient_device_pubkey, false, function(ws, request, response){\n\t\tfunction handleError(error){\n\t\t\tcallbacks.ifError(error);\n\t\t\tdb.query(\"UPDATE outbox SET last_error=? WHERE message_hash=?\", [error, message_hash], function(){});\n\t\t}\n\t\tif (response.error)\n\t\t\treturn handleError(response.error);\n\t\tvar objTempPubkey = response;\n\t\tif (!objTempPubkey.temp_pubkey || !objTempPubkey.pubkey || !objTempPubkey.signature)\n\t\t\treturn handleError(\"missing fields in hub response\");\n\t\tif (objTempPubkey.pubkey !== recipient_device_pubkey)\n\t\t\treturn handleError(\"temp pubkey signed by wrong permanent pubkey\");\n\t\tif (!ecdsaSig.verify(objectHash.getDeviceMessageHashToSign(objTempPubkey), objTempPubkey.signature, objTempPubkey.pubkey))\n\t\t\treturn handleError(\"wrong sig under temp pubkey\");\n\t\tvar objEncryptedPackage = createEncryptedPackage(json, objTempPubkey.temp_pubkey);\n\t\tvar recipient_device_address = objectHash.getDeviceAddress(recipient_device_pubkey);\n\t\tvar objDeviceMessage = {\n\t\t\tencrypted_package: objEncryptedPackage,\n\t\t\tto: recipient_device_address,\n\t\t\tpubkey: objMyPermanentDeviceKey.pub_b64 // who signs. Essentially, the from again. \n\t\t};\n\t\tobjDeviceMessage.signature = ecdsaSig.sign(objectHash.getDeviceMessageHashToSign(objDeviceMessage), objMyPermanentDeviceKey.priv);\n\t\tnetwork.sendRequest(ws, 'hub/deliver', objDeviceMessage, false, function(ws, request, response){\n\t\t\tif (response === \"accepted\"){\n\t\t\t\tdb.query(\"DELETE FROM outbox WHERE message_hash=?\", [message_hash], function(){\n\t\t\t\t\tcallbacks.ifOk();\n\t\t\t\t});\n\t\t\t}\n\t\t\telse\n\t\t\t\thandleError( response.error || (\"unrecognized response: \"+JSON.stringify(response)) );\n\t\t});\n\t});\n}\n\nfunction createEncryptedPackage(json, recipient_device_pubkey){\n\tvar text = JSON.stringify(json);\n//\tconsole.log(\"will encrypt and send: \"+text);\n\tvar ecdh = crypto.createECDH('secp256k1');\n\tvar sender_ephemeral_pubkey = ecdh.generateKeys(\"base64\", \"compressed\");\n\tvar shared_secret = deriveSharedSecret(ecdh, recipient_device_pubkey); // Buffer\n\tconsole.log(shared_secret.length);\n\t// we could also derive iv from the unused bits of ecdh.computeSecret() and save some bandwidth\n\tvar iv = crypto.randomBytes(12); // 128 bits (16 bytes) total, we take 12 bytes for random iv and leave 4 bytes for the counter\n\tvar cipher = crypto.createCipheriv(\"aes-128-gcm\", shared_secret, iv);\n\t// under browserify, encryption of long strings fails with Array buffer allocation errors, have to split the string into chunks\n\tvar arrChunks = [];\n\tvar CHUNK_LENGTH = 2003;\n\tfor (var offset = 0; offset < text.length; offset += CHUNK_LENGTH){\n\t//\tconsole.log('offset '+offset);\n\t\tarrChunks.push(cipher.update(text.slice(offset, Math.min(offset+CHUNK_LENGTH, text.length)), 'utf8'));\n\t}\n\tarrChunks.push(cipher.final());\n\tvar encrypted_message_buf = Buffer.concat(arrChunks);\n\tarrChunks = null;\n//\tvar encrypted_message_buf = Buffer.concat([cipher.update(text, \"utf8\"), cipher.final()]);\n\t//console.log(encrypted_message_buf);\n\tvar encrypted_message = encrypted_message_buf.toString(\"base64\");\n\t//console.log(encrypted_message);\n\tvar authtag = cipher.getAuthTag();\n\t// this is visible and verifiable by the hub\n\tvar encrypted_package = {\n\t\tencrypted_message: encrypted_message,\n\t\tiv: iv.toString('base64'),\n\t\tauthtag: authtag.toString('base64'),\n\t\tdh: {\n\t\t\tsender_ephemeral_pubkey: sender_ephemeral_pubkey,\n\t\t\trecipient_ephemeral_pubkey: recipient_device_pubkey\n\t\t}\n\t};\n\treturn encrypted_package;\n}\n\n// first param is either WebSocket or hostname of the hub or null\nfunction sendMessageToHub(ws, recipient_device_pubkey, subject, body, callbacks, conn){\n\t// this content is hidden from the hub by encryption\n\tvar json = {\n\t\tfrom: my_device_address, // presence of this field guarantees that you cannot strip off the signature and add your own signature instead\n\t\tdevice_hub: my_device_hub, \n\t\tsubject: subject, \n\t\tbody: body\n\t};\n\tconn = conn || db;\n\tif (ws)\n\t\treturn reliablySendPreparedMessageToHub(ws, recipient_device_pubkey, json, callbacks, conn);\n\tvar recipient_device_address = objectHash.getDeviceAddress(recipient_device_pubkey);\n\tconn.query(\"SELECT hub FROM correspondent_devices WHERE device_address=?\", [recipient_device_address], function(rows){\n\t\tif (rows.length !== 1)\n\t\t\tthrow Error(\"no hub in correspondents\");\n\t\treliablySendPreparedMessageToHub(rows[0].hub, recipient_device_pubkey, json, callbacks, conn);\n\t});\n}\n\nfunction sendMessageToDevice(device_address, subject, body, callbacks, conn){\n\tconn = conn || db;\n\tconn.query(\"SELECT hub, pubkey FROM correspondent_devices WHERE device_address=?\", [device_address], function(rows){\n\t\tif (rows.length !== 1)\n\t\t\tthrow Error(\"correspondent not found\");\n\t\tsendMessageToHub(rows[0].hub, rows[0].pubkey, subject, body, callbacks, conn);\n\t});\n}\n\n\n\n// -------------------------\n// pairing\n\n\nfunction sendPairingMessage(hub_host, recipient_device_pubkey, pairing_secret, reverse_pairing_secret, callbacks){\n\tvar body = {pairing_secret: pairing_secret, device_name: my_device_name};\n\tif (reverse_pairing_secret)\n\t\tbody.reverse_pairing_secret = reverse_pairing_secret;\n\tsendMessageToHub(hub_host, recipient_device_pubkey, \"pairing\", body, callbacks);\n}\n\nfunction startWaitingForPairing(handlePairingInfo){\n\tvar pairing_secret = crypto.randomBytes(9).toString(\"base64\");\n\tvar pairingInfo = {\n\t\tpairing_secret: pairing_secret,\n\t\tdevice_pubkey: objMyPermanentDeviceKey.pub_b64,\n\t\tdevice_address: my_device_address,\n\t\thub: my_device_hub\n\t};\n\tdb.query(\"INSERT INTO pairing_secrets (pairing_secret, expiry_date) VALUES(?, \"+db.addTime(\"+1 MONTH\")+\")\", [pairing_secret], function(){\n\t\thandlePairingInfo(pairingInfo);\n\t});\n}\n\n// {pairing_secret: \"random string\", device_name: \"\", reverse_pairing_secret: \"random string\"}\nfunction handlePairingMessage(json, device_pubkey, callbacks){\n\tvar body = json.body;\n\tvar from_address = objectHash.getDeviceAddress(device_pubkey);\n\tif (!ValidationUtils.isNonemptyString(body.pairing_secret))\n\t\treturn callbacks.ifError(\"correspondent not known and no pairing secret\");\n\tif (!ValidationUtils.isNonemptyString(json.device_hub)) // home hub of the sender\n\t\treturn callbacks.ifError(\"no device_hub when pairing\");\n\tif (!ValidationUtils.isNonemptyString(body.device_name))\n\t\treturn callbacks.ifError(\"no device_name when pairing\");\n\tif (\"reverse_pairing_secret\" in body && !ValidationUtils.isNonemptyString(body.reverse_pairing_secret))\n\t\treturn callbacks.ifError(\"bad reverse pairing secret\");\n\tdb.query(\n\t\t\"SELECT is_permanent FROM pairing_secrets WHERE pairing_secret=? AND expiry_date > \"+db.getNow(), \n\t\t[body.pairing_secret], \n\t\tfunction(pairing_rows){\n\t\t\tif (pairing_rows.length === 0)\n\t\t\t\treturn callbacks.ifError(\"pairing secret not found or expired\");\n\t\t\t// add new correspondent and delete pending pairing\n\t\t\tdb.query(\n\t\t\t\t\"INSERT \"+db.getIgnore()+\" INTO correspondent_devices (device_address, pubkey, hub, name, is_confirmed) VALUES (?,?,?,?,1)\", \n\t\t\t\t[from_address, device_pubkey, json.device_hub, body.device_name],\n\t\t\t\tfunction(){\n\t\t\t\t\tdb.query( // don't update name if already confirmed\n\t\t\t\t\t\t\"UPDATE correspondent_devices SET is_confirmed=1, name=? WHERE device_address=? AND is_confirmed=0\", \n\t\t\t\t\t\t[body.device_name, from_address],\n\t\t\t\t\t\tfunction(){\n\t\t\t\t\t\t\teventBus.emit(\"paired\", from_address);\n\t\t\t\t\t\t\tif (pairing_rows[0].is_permanent === 0){ // multiple peers can pair through permanent secret\n\t\t\t\t\t\t\t\tdb.query(\"DELETE FROM pairing_secrets WHERE pairing_secret=?\", [body.pairing_secret], function(){});\n\t\t\t\t\t\t\t\teventBus.emit('paired_by_secret-'+body.pairing_secret, from_address);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (body.reverse_pairing_secret)\n\t\t\t\t\t\t\t\tsendPairingMessage(json.device_hub, device_pubkey, body.reverse_pairing_secret, null);\n\t\t\t\t\t\t\tcallbacks.ifOk();\n\t\t\t\t\t\t}\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t);\n\t\t}\n\t);\n}\n\n\n\n// -------------------------------\n// correspondents\n\nfunction addUnconfirmedCorrespondent(device_pubkey, device_hub, device_name, onDone){\n\tconsole.log(\"addUnconfirmedCorrespondent\");\n\tvar device_address = objectHash.getDeviceAddress(device_pubkey);\n\tdb.query(\n\t\t\"INSERT \"+db.getIgnore()+\" INTO correspondent_devices (device_address, pubkey, hub, name, is_confirmed) VALUES (?,?,?,?,0)\", \n\t\t[device_address, device_pubkey, device_hub, device_name],\n\t\tfunction(){\n\t\t\tif (onDone)\n\t\t\t\tonDone(device_address);\n\t\t}\n\t);\n}\n\nfunction readCorrespondents(handleCorrespondents){\n\tdb.query(\"SELECT device_address, hub, name, my_record_pref, peer_record_pref FROM correspondent_devices ORDER BY name\", function(rows){\n\t\thandleCorrespondents(rows);\n\t});\n}\n\nfunction readCorrespondent(device_address, handleCorrespondent){\n\tdb.query(\"SELECT device_address, hub, name, my_record_pref, peer_record_pref FROM correspondent_devices WHERE device_address=?\", [device_address], function(rows){\n\t\thandleCorrespondent(rows.length ? rows[0] : null);\n\t});\n}\n\nfunction readCorrespondentsByDeviceAddresses(arrDeviceAddresses, handleCorrespondents){\n\tdb.query(\n\t\t\"SELECT device_address, hub, name, pubkey, my_record_pref, peer_record_pref FROM correspondent_devices WHERE device_address IN(?) ORDER BY name\", \n\t\t[arrDeviceAddresses], \n\t\tfunction(rows){\n\t\t\thandleCorrespondents(rows);\n\t\t}\n\t);\n}\n\nfunction updateCorrespondentProps(correspondent, onDone){\n\tdb.query(\n\t\t\"UPDATE correspondent_devices SET hub=?, name=?, my_record_pref=?, peer_record_pref=? WHERE device_address=?\", \n\t\t[correspondent.hub, correspondent.name, correspondent.my_record_pref, correspondent.peer_record_pref, correspondent.device_address], \n\t\tfunction(){\n\t\t\tif (onDone) onDone();\n\t\t}\n\t);\n}\n\nfunction addIndirectCorrespondents(arrOtherCosigners, onDone){\n\tasync.eachSeries(arrOtherCosigners, function(correspondent, cb){\n\t\tif (correspondent.device_address === my_device_address)\n\t\t\treturn cb();\n\t\tdb.query(\n\t\t\t\"INSERT \"+db.getIgnore()+\" INTO correspondent_devices (device_address, hub, name, pubkey, is_indirect) VALUES(?,?,?,?,1)\", \n\t\t\t[correspondent.device_address, correspondent.hub, correspondent.name, correspondent.pubkey],\n\t\t\tfunction(){\n\t\t\t\tcb();\n\t\t\t}\n\t\t);\n\t}, onDone);\n}\n\nfunction removeCorrespondentDevice(device_address, onDone){\n\tbreadcrumbs.add('correspondent removed: '+device_address);\n\tvar arrQueries = [];\n\tdb.addQuery(arrQueries, \"DELETE FROM outbox WHERE `to`=?\", [device_address]);\n\tdb.addQuery(arrQueries, \"DELETE FROM correspondent_devices WHERE device_address=?\", [device_address]);\n\tasync.series(arrQueries, onDone);\n}\n\n// -------------------------------\n// witnesses\n\n\nfunction getWitnessesFromHub(cb){\n\tconsole.log('getWitnessesFromHub');\n\tif (!my_device_hub){\n\t\tconsole.log('getWitnessesFromHub: no hub yet');\n\t\treturn setTimeout(function(){\n\t\t\tgetWitnessesFromHub(cb);\n\t\t}, 2000);\n\t}\n\tnetwork.findOutboundPeerOrConnect(conf.WS_PROTOCOL+my_device_hub, function(err, ws){\n\t\tif (err)\n\t\t\treturn cb(err);\n\t\tnetwork.sendRequest(ws, 'get_witnesses', null, false, function(ws, request, response){\n\t\t\tif (response.error)\n\t\t\t\treturn cb(response.error);\n\t\t\tvar arrWitnessesFromHub = response;\n\t\t\tcb(null, arrWitnessesFromHub);\n\t\t});\n\t});\n}\n\n// responseHandler(error, response) callback\nfunction requestFromHub(command, params, responseHandler){\n\tif (!my_device_hub)\n\t\treturn setTimeout(function(){ requestFromHub(command, params, responseHandler); }, 2000);\n\tnetwork.findOutboundPeerOrConnect(conf.WS_PROTOCOL+my_device_hub, function(err, ws){\n\t\tif (err)\n\t\t\treturn responseHandler(err);\n\t\tnetwork.sendRequest(ws, command, params, false, function(ws, request, response){\n\t\t\tif (response.error)\n\t\t\t\treturn responseHandler(response.error);\n\t\t\tresponseHandler(null, response);\n\t\t});\n\t});\n}\n\n\nexports.getMyDevicePubKey = getMyDevicePubKey;\nexports.getMyDeviceAddress = getMyDeviceAddress;\nexports.uPMyColdDeviceAddress = uPMyColdDeviceAddress;\nexports.setMyColdDeviceAddress = setMyColdDeviceAddress;\nexports.getMyColdDeviceAddress = getMyColdDeviceAddress;\nexports.isValidPubKey = isValidPubKey;\n\nexports.genPrivKey = genPrivKey;\n\nexports.setDevicePrivateKey = setDevicePrivateKey;\nexports.setTempKeys = setTempKeys;\nexports.setDeviceAddress = setDeviceAddress;\nexports.setNewDeviceAddress = setNewDeviceAddress;\nexports.setDeviceName = setDeviceName;\nexports.setDeviceHub = setDeviceHub;\n\nexports.scheduleTempDeviceKeyRotation = scheduleTempDeviceKeyRotation;\n\nexports.decryptPackage = decryptPackage;\n\nexports.handleChallenge = handleChallenge;\nexports.loginToHub = loginToHub;\n\nexports.sendMessageToHub = sendMessageToHub;\nexports.sendMessageToDevice = sendMessageToDevice;\n\nexports.sendPairingMessage = sendPairingMessage;\nexports.startWaitingForPairing = startWaitingForPairing;\nexports.handlePairingMessage = handlePairingMessage;\n\nexports.addUnconfirmedCorrespondent = addUnconfirmedCorrespondent;\nexports.readCorrespondents = readCorrespondents;\nexports.readCorrespondent = readCorrespondent;\nexports.readCorrespondentsByDeviceAddresses = readCorrespondentsByDeviceAddresses;\nexports.updateCorrespondentProps = updateCorrespondentProps;\nexports.removeCorrespondentDevice = removeCorrespondentDevice;\nexports.addIndirectCorrespondents = addIndirectCorrespondents;\nexports.getWitnessesFromHub = getWitnessesFromHub;\nexports.requestFromHub = requestFromHub;", "dangerousExampleEn": "1. const crypto = require(\"crypto\");\n2. const dan_hash_content = crypto.createHash('sha256').update(content).digest('hex');\nLine 2: This is insecure because data without a salt value is used for the hash function.", "safeExampleEn": "1. const crypto = require(\"crypto\");\n2. \n3. const randomBytes = new Uint32Array(1);\n4. crypto.randomFillSync(randomBytes);\n5. const safe_salt1 = randomBytes[0].toString();\n6. const safe_hash_content1 = crypto.createHash('sha256').update(orgin_content+safe_salt1).digest('hex');\n7. \n8. const safe_salt2 = crypto.randomBytes(4).toString('hex');\n9. const safe_hash_content2 = crypto.createHash('sha256').update(orgin_content+safe_salt2).digest('hex');\nLine 6, 9: This is secure because a hash function with a salt value is used.", "contexts": [{"lineNo": 308, "eventType": "sink", "messageKey": "jschk.WEAK_HASH.JS.defect.salt", "params": {"arg0": "sha256"}}]}} {"id": "65fa2260c188c5514eb7ece09d2eeb754467227ef1ecf9f83597e22c35a2b59d", "license": {"spdx": ["MIT"], "repo": "TakutoYoshikai/usbkey", "path": "index.js", "repo_head_hexsha": "ffbfaa9a95348f7cd9984ba7f182a3f053479ea4", "stack_hexsha": "5c23cac01522c7dfec7d2d7d1d6313cac2fc5486", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "One-way Hash Function Used Without Salt", "issueDescriptionEn": "When storing sensitive information such as passwords, it is recommended to use a one-way hash function that converts data of any length into a fixed-sized hash value. If sensitive information is stored without using salt in a one-way hash function, an attacker may identify the hash value using a pre-calculated rainbow table.\nWhen storing sensitive information such as passwords, it is secure to use a one-way hash function that converts data of any length into a fixed-sized hash value. In addition, it is necessary to generate a unique salt value for each user. To accomplish this, the salt value should be stored separately for each user. The latest hash functions, such as bcrypt and PBKDF2, support this process. However, if you use a hash function that does not support it, you will need to manually provide the salt value.", "issueLineNumber": 6, "entireCode": "const usbDetect = require(\"usb-detection\");\nconst fs = require(\"fs\");\nconst crypto = require(\"crypto\");\n\nfunction makeHash(id) {\n return crypto.createHash(\"sha256\").update(id, \"utf8\").digest(\"hex\");\n}\n\nfunction makeUniqueId(device) {\n return makeHash(device.deviceName + \":\" + device.manufacturer + \":\" + device.serialNumber);\n}\n\nfunction register(pwPath) {\n usbDetect.on(\"add\", (device) => {\n const pw = makeUniqueId(device);\n fs.writeFileSync(pwPath, pw, { flag: \"w\" });\n usbDetect.stopMonitoring();\n process.exit(0);\n });\n usbDetect.startMonitoring();\n}\nfunction observe(pwPath, events) {\n const pw = fs.readFileSync(pwPath, \"utf8\").slice(0, 64);\n usbDetect.on(\"add\", (device) => {\n const id = makeUniqueId(device); \n if (pw === id) {\n events.add();\n }\n });\n\n usbDetect.on(\"remove\", (device) => {\n const id = makeUniqueId(device); \n if (pw === id) {\n events.remove();\n }\n });\n usbDetect.startMonitoring();\n}\n\nmodule.exports = {\n observe,\n register,\n}", "dangerousExampleEn": "1. const crypto = require(\"crypto\");\n2. const dan_hash_content = crypto.createHash('sha256').update(content).digest('hex');\nLine 2: This is insecure because data without a salt value is used for the hash function.", "safeExampleEn": "1. const crypto = require(\"crypto\");\n2. \n3. const randomBytes = new Uint32Array(1);\n4. crypto.randomFillSync(randomBytes);\n5. const safe_salt1 = randomBytes[0].toString();\n6. const safe_hash_content1 = crypto.createHash('sha256').update(orgin_content+safe_salt1).digest('hex');\n7. \n8. const safe_salt2 = crypto.randomBytes(4).toString('hex');\n9. const safe_hash_content2 = crypto.createHash('sha256').update(orgin_content+safe_salt2).digest('hex');\nLine 6, 9: This is secure because a hash function with a salt value is used.", "contexts": [{"lineNo": 6, "eventType": "sink", "messageKey": "jschk.WEAK_HASH.JS.defect.salt", "params": {"arg0": "sha256"}}]}} {"id": "6868b1f82e591d67cfc887bbc4c7388b2eedffda0561fba7c06bc5458eeff19f", "license": {"spdx": ["MIT"], "repo": "Ningthangom/shoppingEcommerce", "path": "backend/controllers/authController.js", "repo_head_hexsha": "2ea78df4cb3761e661f89b2fb838d89a49d637f4", "stack_hexsha": "a23c4686659175b0afa5376f65d6695d78877456", "match": "repo_path"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "One-way Hash Function Used Without Salt", "issueDescriptionEn": "When storing sensitive information such as passwords, it is recommended to use a one-way hash function that converts data of any length into a fixed-sized hash value. If sensitive information is stored without using salt in a one-way hash function, an attacker may identify the hash value using a pre-calculated rainbow table.\nWhen storing sensitive information such as passwords, it is secure to use a one-way hash function that converts data of any length into a fixed-sized hash value. In addition, it is necessary to generate a unique salt value for each user. To accomplish this, the salt value should be stored separately for each user. The latest hash functions, such as bcrypt and PBKDF2, support this process. However, if you use a hash function that does not support it, you will need to manually provide the salt value.", "issueLineNumber": 108, "entireCode": "\n const User = require('../models/user');\n\n const ErrorHandler = require('../utils/errorHandler');\n const catchAsyncErrors = require('../middlewares/catchAsyncErrors');\n const sendToken = require('../utils/jwtToken');\n const sendEmail = require('../utils/sendEmail')\n const crypto = require('crypto');\n const cloudinary = require('cloudinary')\n\n\n // registor a user => api/v1/registered\n exports.registerUser = catchAsyncErrors (async (req, res, next) => {\n\n const result = await cloudinary.v2.uploader.upload(req.body.avator, {\n folder: 'avators',\n width:150,\n crop: \"scale\"\n })\n\n // pull the name, email and password from req.body\n const {name, email, password} = req.body;\n\n const user = await User.create({\n name,\n email,\n password,\n avator: {\n public_id: result.public_id,\n url: result.secure_url\n }\n })\n\n sendToken(user, 200, res );\n })\n\n // login User => /api/v1/login\n\n exports.loginUser = catchAsyncErrors (async (req, res, next) => {\n const {email, password} = req.body;\n\n // check if email and product is entered by user \n\n if(!email || !password) {\n return next(new ErrorHandler('Please Enter email & password', 400));\n };\n // finding user in database\n const user = await User.findOne({email}).select('+password')\n\n if(!user) {\n return next(new ErrorHandler('Invalid Email or Password', 401))\n }\n\n // check if the password is correct\n const isPasswordMatched = await user.comparePassword(password);\n\n if(!isPasswordMatched) {\n return next(new ErrorHandler('Invalid Email or Password', 401));\n }\n\n sendToken(user, 200, res );\n })\n \n\n // forgot password => /api/v1/password/forgot\n exports.forgotPassword = catchAsyncErrors (async (req, res, next) => {\n\n const user = await User.findOne({email: req.body.email});\n if(!user){\n return next(new ErrorHandler('Invalid email', 404))\n }\n\n // get reset token \n const resetToken = user.getResetPasswordToken();\n await user.save({validateBeforeSave: false})\n\n // create reset password url \n const resetUrl = `${req.protocol}://${req.get('host')}/password/reset/${resetToken}`\n\n const message = `your password reset token is as follow: \\n\\n${resetUrl}\\n\\n if you have not requested this email, please ingor it`\n\n try {\n\n await sendEmail ({\n email: user.email,\n subject: 'shopit password recovery',\n message\n\n })\n res.status(200).json({\n success: true,\n message: `Email sent to ${user.email}`\n })\n\n }catch(error) {\n user.resetPasswordToken = ;\n user.resetPasswordExpire = undefined;\n\n await user.save({validateBeforeSave: false})\n\n return next(new ErrorHandler(error.message, 500))\n }\n })\n\n // reset password => /api/v1/password/reset/:token\n exports.resetPassword = catchAsyncErrors (async (req, res, next) => {\n // hash url token\n const resetPasswordToken = crypto.createHash('sha256').update(req.params.token).digest('hex')\n const user = await User.findOne({\n resetPasswordToken, \n resetPasswordExpire: { $gt: Date.now()}\n })\n if(!user) {\n return next(new ErrorHandler('Password reset is not invalid or expired', 400))\n }\n\n if(req.body.password !== req.body.confirmPassword){\n return next(new ErrorHandler('Password does not match', 400))\n }\n\n // set up new password\n user.password = ;\n\n\n user.resetPasswordToken = ;\n user.resetPasswordExpire = ;\n\n await user.save()\n sendToken(user, 200, res);\n })\n\n\n\n\n // get currently login user details => /api/v1/me\n exports.getUserProfile = catchAsyncErrors (async (req, res, next) => {\n const user = await User.findById(req.user.id)\n\n res.status(200).json({\n success: true,\n user\n })\n })\n\n\n // Update password => /api/v1/password/update\n exports.updatePassword = catchAsyncErrors (async (req, res, next) => {\n\n const user = await User.findById(req.user.id).select('+password');\n //check previous user password\n const isMatch = await user.comparePassword(req.body.oldPassword);\n if(!isMatch){\n return next(new ErrorHandler('Old password is incorrect'))\n }\n user.password = ;\n await user.save();\n\n sendToken(user, 200, res);\n\n })\n\n // update user profile => /api/v1/me/update\n exports.updateProfile = catchAsyncErrors (async (req, res, next) => {\n\n const newUserData = {\n name: req.body.name, \n email:req.body.email\n\n }\n // update avator (profile picture) : todo\n if (req.body.avator !== '') {\n const user = await User.findById(req.user.id)\n \n const image_id = user.avator.public_id;\n const res = await cloudinary.v2.uploader.destroy(image_id);\n \n const result = await cloudinary.v2.uploader.upload(req.body.avator, {\n folder: 'avators',\n width: 150,\n crop: \"scale\"\n })\n \n newUserData.avator = {\n public_id: result.public_id,\n url: result.secure_url\n }\n }\n\n const user = await User.findByIdAndUpdate(req.user.id, newUserData, {\n new: true,\n runValidators: true,\n useFindAndModify: false\n })\n\n res.status(200).json({\n success: true,\n message:'profile updated successfully'\n \n\n })\n\n\n\n })\n\n\n //logout user => /api/v1/logout\n\n exports.logout = catchAsyncErrors(async (req, res, next) => {\n\n res.cookie('token', null, {\n expires: new Date(Date.now()),\n httpOnly: true\n } )\n\n res.status(200).json({\n success: true,\n message: 'Logged out'\n })\n })\n\n\n\n //Admin routes \n \n\n // get all users\n\n exports.getAllUsers = catchAsyncErrors (async (req, res, next) => {\n const users = await User.find();\n\n res.status(200).json({\n success: true,\n users\n })\n })\n\n\n // get user details => /api/v1/admin/user/:id\n exports.getUserDetails = catchAsyncErrors (async (req, res, next) => {\n const user = await User.findById(req.params.id);\n\n if(!user){\n return next(new ErrorHandler(`user is not found with id:${req.params.id}`))\n }\n res.status(200).json({\n success: true,\n user\n })\n })\n\n\n \n // update user profile => /api/v1/admin/user/:id\n exports.updateUser = catchAsyncErrors (async (req, res, next) => {\n\n const newUserData = {\n name: req.body.name, \n email:req.body.email,\n role:req.body.role\n\n }\n // update avator (profile picture) : todo\n\n const user = await User.findByIdAndUpdate(req.params.id, newUserData, {\n new: true,\n runValidators: true,\n useFindAndModify: false\n })\n\n res.status(200).json({\n success: true,\n message:'profile updated successfully',\n user\n })\n\n })\n\n //delete user => /api/v1/admin/user/:id\n exports.deleteUser = catchAsyncErrors (async (req, res, next) => {\n const user = await User.findById(req.params.id);\n\n if(!user){\n return next(new ErrorHandler(`user is not found with id:${req.params.id}`))\n }\n // remove avator from cloudinary\n const image_id = user.avator.public_id;\n await cloudinary.v2.uploader.destroy(image_id);\n\n await user.remove();\n res.status(200).json({\n success: true,\n message: 'user deleted successfully',\n user\n })\n })", "dangerousExampleEn": "1. const crypto = require(\"crypto\");\n2. const dan_hash_content = crypto.createHash('sha256').update(content).digest('hex');\nLine 2: This is insecure because data without a salt value is used for the hash function.", "safeExampleEn": "1. const crypto = require(\"crypto\");\n2. \n3. const randomBytes = new Uint32Array(1);\n4. crypto.randomFillSync(randomBytes);\n5. const safe_salt1 = randomBytes[0].toString();\n6. const safe_hash_content1 = crypto.createHash('sha256').update(orgin_content+safe_salt1).digest('hex');\n7. \n8. const safe_salt2 = crypto.randomBytes(4).toString('hex');\n9. const safe_hash_content2 = crypto.createHash('sha256').update(orgin_content+safe_salt2).digest('hex');\nLine 6, 9: This is secure because a hash function with a salt value is used.", "contexts": [{"lineNo": 108, "eventType": "sink", "messageKey": "jschk.WEAK_HASH.JS.defect.salt", "params": {"arg0": "sha256"}}]}} {"id": "39bb2d386163332751d28c7f3eed1dfa723ab62128aa4354527c9a49bf9c9bae", "license": {"spdx": ["MIT"], "repo": "julioacontreras/ncaptcha", "path": "lib/ncaptcha.js", "repo_head_hexsha": "3163cc94c903636b4c7d2e0c9e5e3a7d3c397fa8", "stack_hexsha": "06a52dc1b1d215850b73b0d4750cf56d46552630", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "One-way Hash Function Used Without Salt", "issueDescriptionEn": "When storing sensitive information such as passwords, it is recommended to use a one-way hash function that converts data of any length into a fixed-sized hash value. If sensitive information is stored without using salt in a one-way hash function, an attacker may identify the hash value using a pre-calculated rainbow table.\nWhen storing sensitive information such as passwords, it is secure to use a one-way hash function that converts data of any length into a fixed-sized hash value. In addition, it is necessary to generate a unique salt value for each user. To accomplish this, the salt value should be stored separately for each user. The latest hash functions, such as bcrypt and PBKDF2, support this process. However, if you use a hash function that does not support it, you will need to manually provide the salt value.", "issueLineNumber": 29, "entireCode": "'use strict';\n\nconst { createCanvas } = require('canvas');\n\nconst crypto = require('crypto');\n\nclass NCaptcha {\n constructor(params) {\n if (!params) {\n params = {};\n }\n params.color = params.color || 'rgb(0,100,100)';\n params.background = params.background || 'rgb(255, 255, 255)';\n params.lineWidth = params.lineWidth || 8;\n params.fontSize = params.fontSize || 80;\n params.codeLength = params.codeLength || 6;\n params.canvasWidth = params.canvasWidth || 400;\n params.canvasHeight = params.canvasHeight || 150;\n params.expireInMinute = params.expireInMinute || 10;\n params.numberOfLines = params.numberOfLines || 2;\n\n this.params = params;\n }\n\n generate() {\n if (!this.params.text) {\n this.params.text = Math.random().toString(36).substr(2, 6);\n }\n var key = crypto.createHash('sha256').update(this.params.text).digest('hex');\n const canvas = createCanvas(this.params.canvasWidth, this.params.canvasHeight);\n const ctx = canvas.getContext('2d');\n\n ctx.antialias = 'gray';\n ctx.fillStyle = this.params.background;\n ctx.fillRect(0, 0, this.params.canvasWidth, this.params.canvasHeight);\n ctx.fillStyle = this.params.color;\n ctx.lineWidth = this.params.lineWidth;\n ctx.strokeStyle = this.params.color;\n ctx.font = `${this.params.fontSize}px sans`;\n\n // draw two curve lines:\n for (var i = 0; i < this.params.numberOfLines; i++) {\n ctx.moveTo(Math.floor(0.08 * this.params.canvasWidth), Math.random() * this.params.canvasHeight);\n ctx.bezierCurveTo(\n Math.floor(0.32 * this.params.canvasWidth),\n Math.random() * this.params.canvasHeight,\n Math.floor(1.07 * this.params.canvasHeight),\n Math.random() * this.params.canvasHeight,\n Math.floor(0.92 * this.params.canvasWidth),\n Math.random() * this.params.canvasHeight\n );\n ctx.stroke();\n }\n\n // draw text:\n this.params.text.split('').forEach((char, i) => {\n ctx.setTransform(\n Math.random() * 0.2 + 1,\n Math.random() * 0.1,\n Math.random() * 0.1,\n Math.random() * 0.2 + 1, //v scale\n Math.floor(0.75 * this.params.fontSize) * i + Math.floor(0.25 * this.params.fontSize),\n Math.floor((Math.random() * 0.2 + 1) * this.params.fontSize) //v move\n );\n ctx.fillText(char, 0, 0);\n });\n return {\n image: 'data:image/png;base64,' + canvas.toBuffer().toString('base64'),\n key: key + '-' + new Date().getTime() / 2,\n };\n }\n\n check(keyToCheck, text) {\n var toCheckTime = new Date(parseInt(keyToCheck.split('-')[1]) * 2);\n var nowTime = new Date();\n\n var difference = (nowTime - toCheckTime) / (1000 * 60);\n return keyToCheck.split('-')[0] == crypto.createHash('sha256').update(text).digest('hex') && difference < this.params.expireInMinute;\n }\n}\nmodule.exports = NCaptcha;", "dangerousExampleEn": "1. const crypto = require(\"crypto\");\n2. const dan_hash_content = crypto.createHash('sha256').update(content).digest('hex');\nLine 2: This is insecure because data without a salt value is used for the hash function.", "safeExampleEn": "1. const crypto = require(\"crypto\");\n2. \n3. const randomBytes = new Uint32Array(1);\n4. crypto.randomFillSync(randomBytes);\n5. const safe_salt1 = randomBytes[0].toString();\n6. const safe_hash_content1 = crypto.createHash('sha256').update(orgin_content+safe_salt1).digest('hex');\n7. \n8. const safe_salt2 = crypto.randomBytes(4).toString('hex');\n9. const safe_hash_content2 = crypto.createHash('sha256').update(orgin_content+safe_salt2).digest('hex');\nLine 6, 9: This is secure because a hash function with a salt value is used.", "contexts": [{"lineNo": 29, "eventType": "sink", "messageKey": "jschk.WEAK_HASH.JS.defect.salt", "params": {"arg0": "sha256"}}]}} {"id": "9d73ea5901f2edbfbb60787b3a1aa868c2bf52e1fbb43ac912cef8db3dd0db43", "license": {"spdx": ["MIT"], "repo": "aequabit/ayyware-web", "path": "web/server.js", "repo_head_hexsha": "de06d0c95ffc926caee654fa6d98c83fe3670534", "stack_hexsha": "d5551acd15738fa527139050e12391ceb78e9c5e", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "One-way Hash Function Used Without Salt", "issueDescriptionEn": "When storing sensitive information such as passwords, it is recommended to use a one-way hash function that converts data of any length into a fixed-sized hash value. If sensitive information is stored without using salt in a one-way hash function, an attacker may identify the hash value using a pre-calculated rainbow table.\nWhen storing sensitive information such as passwords, it is secure to use a one-way hash function that converts data of any length into a fixed-sized hash value. In addition, it is necessary to generate a unique salt value for each user. To accomplish this, the salt value should be stored separately for each user. The latest hash functions, such as bcrypt and PBKDF2, support this process. However, if you use a hash function that does not support it, you will need to manually provide the salt value.", "issueLineNumber": 93, "entireCode": "const config = require('./config'),\n helper = require('./helper'),\n express = require('express'),\n app = express(),\n util = require('util'),\n fs = require('fs-extra'),\n randomstring = require('randomstring'),\n moment = require('moment'),\n ncp = require('ncp'),\n sha256 = require('sha256'),\n sprintf = require('sprintf-js').sprintf,\n vsprintf = require('sprintf-js').vsprintf,\n child = require('child_process');\n\n/**\n * Express setup.\n */\napp.use('/static', express.static(__dirname + '/static'));\n//app.use('/bin', express.static(__dirname + '/bin'));\n\napp.get('/', (req, res) => {\n res.sendFile(__dirname + '/templates/index.html');\n});\n\napp.get('/bin/:name', (req, res) => {\n if (!fs.existsSync(__dirname + '/bin/' + req.params.name)) {\n return res.redirect('/');\n }\n res.sendFile(__dirname + '/bin/' + req.params.name);\n console.log('[bin] %s requested %s', (req.headers['x-forwarded-for'] || req.connection.remoteAddress).replace('::ffff:', ''), req.params.name);\n});\n\nvar server = app.listen(config.http.port, () => {\n console.log('[http] listening on %d', config.http.port);\n});\n\nvar current = 0;\n\n/**\n * Socket.io setup.\n */\nconst io = require('socket.io').listen(server);\n\nio.on('connection', socket => {\n //console.log('[socket] client connected');\n socket.on('build', data => {\n if (!data || !data.name || typeof data.name != 'string' || data.name.length < 1 || data.name.length > 32 || data.name.match(/^[\\w\\s-_]+$/i) === null ||\n !data.ct || !data.ct.visible || !data.ct.invisible || typeof data.ct.visible != 'object' || typeof data.ct.invisible != 'object' ||\n !data.t || !data.t.visible || !data.t.invisible || typeof data.t.visible != 'object' || typeof data.t.invisible != 'object' ||\n data.ct.visible.length != 3 || data.ct.invisible.length != 3 ||\n !helper.IsValidRgbColor(data.ct.visible) || !helper.IsValidRgbColor(data.ct.invisible) ||\n data.t.visible.length != 3 || data.t.invisible.length != 3 ||\n !helper.IsValidRgbColor(data.t.visible) || !helper.IsValidRgbColor(data.t.invisible)\n ) return console.log('[build] received invalid data: %s', util.inspect(data));\n\n\tif (current >= 5) return socket.emit('errormsg', { message: 'The build queue is currently full. Please try again later. ' });\n\n\tfs.readFile(__dirname + '/buildcount.txt', (err, data) => {\n\t if (err) return;\n fs.writeFile(__dirname + '/buildcount.txt', parseInt(data.toString()) + 1, 'utf8', err => {\n\t if (err) return;\n\t });\n io.emit('buildcount', { count: parseInt(data) + 1 });\n\t});\n\n var buildname = sha256(data.name + '-' + moment().unix() + '-' + randomstring.generate());\n\n\tcurrent++;\n\n ncp(__dirname + '/../cheat', __dirname + '/cache/' + buildname, err => {\n if (err) return console.log('[build] %s (%s): error while copying source', data.name, buildname);\n console.log('[build] %s (%s): copied source', data.name, buildname)\n\n console.log('[build] %s (%s): replacing name and colors', data.name, buildname);\n\n fs.readFile(__dirname + '/cache/' + buildname + '/MetaInfo.h', (err, metainfo) => {\n if (err) return console.log('[build] %s (%s): failed to open MetaInfo.h', data.name, buildname);\n\n var final = metainfo.toString()\n .split('{NAME}').join(data.name)\n .split('{CTVIS}').join(vsprintf('%d, %d, %d', data.ct.visible))\n .split('{CTINVIS}').join(vsprintf('%d, %d, %d', data.ct.invisible))\n .split('{TVIS}').join(vsprintf('%d, %d, %d', data.t.visible))\n .split('{TINVIS}').join(vsprintf('%d, %d, %d', data.t.invisible));\n\n fs.writeFile(__dirname + '/cache/' + buildname + '/MetaInfo.h', final, 'utf8', err => {\n if (err) console.log('[build] %s (%s): failed to save MetaInfo.h', data.name, buildname);\n\n console.log('[build] %s (%s): starting build', data.name, buildname);\n var build = child.spawn('msbuild', [__dirname + '/cache/' + buildname + '/AYYWARE CSGO.vcxproj', '/p:Configuration=Release'])\n build.on('close', code => {\n console.log('[build] %s (%s): build finished', data.name, buildname);\n var dllname = sha256(buildname) + '.dll';\n fs.move(\n __dirname + '/cache/' + buildname + '/Release/ayyware.dll',\n __dirname + '/bin/' + dllname,\n err => {\n if (err) return console.log('[build] %s (%s): renaming DLL failed.', data.name, buildname);\n\n console.log('[build] %s (%s): deleting source', data.name, buildname);\n\n\t\t\t\ttry {\n fs.removeSync(__dirname + '/cache/' + buildname);\n\t\t\t\t} catch (e) {}\n\n socket.emit('build', {\n url: '/bin/' + dllname\n });\n\t\t\t\tcurrent--;\n setTimeout(() => {\n fs.unlinkSync(__dirname + '/bin/' + dllname);\n }, 15000);\n });\n });\n });\n })\n });\n });\n socket.on('buildcount', () => {\n fs.readFile(__dirname + '/buildcount.txt', (err, data) => {\n if (err) return;\n socket.emit('buildcount', { count: data.toString() });\n });\n });\n});", "dangerousExampleEn": "1. const crypto = require(\"crypto\");\n2. const dan_hash_content = crypto.createHash('sha256').update(content).digest('hex');\nLine 2: This is insecure because data without a salt value is used for the hash function.", "safeExampleEn": "1. const crypto = require(\"crypto\");\n2. \n3. const randomBytes = new Uint32Array(1);\n4. crypto.randomFillSync(randomBytes);\n5. const safe_salt1 = randomBytes[0].toString();\n6. const safe_hash_content1 = crypto.createHash('sha256').update(orgin_content+safe_salt1).digest('hex');\n7. \n8. const safe_salt2 = crypto.randomBytes(4).toString('hex');\n9. const safe_hash_content2 = crypto.createHash('sha256').update(orgin_content+safe_salt2).digest('hex');\nLine 6, 9: This is secure because a hash function with a salt value is used.", "contexts": [{"lineNo": 93, "eventType": "sink", "messageKey": "jschk.WEAK_HASH.JS.defect.salt", "params": {"arg0": "sha256"}}]}} {"id": "6687543d0e0eb23a12fe919e1e8175e80b765df3f2c79ee9f566eb2395ecd987", "license": {"spdx": ["MIT"], "repo": "samnguyen102/rescue", "path": "scripts/manual_prod_deploy.js", "repo_head_hexsha": "f82ab336a7bd05f67c5d5523350f4b645072fa2a", "stack_hexsha": "b0f3d907dc8201fbeaf93f3be76e078bdf4ec583", "match": "repo_path"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "One-way Hash Function Used Without Salt", "issueDescriptionEn": "When storing sensitive information such as passwords, it is recommended to use a one-way hash function that converts data of any length into a fixed-sized hash value. If sensitive information is stored without using salt in a one-way hash function, an attacker may identify the hash value using a pre-calculated rainbow table.\nWhen storing sensitive information such as passwords, it is secure to use a one-way hash function that converts data of any length into a fixed-sized hash value. In addition, it is necessary to generate a unique salt value for each user. To accomplish this, the salt value should be stored separately for each user. The latest hash functions, such as bcrypt and PBKDF2, support this process. However, if you use a hash function that does not support it, you will need to manually provide the salt value.", "issueLineNumber": 87, "entireCode": "const { exec } = require('child_process')\nconst crypto = require('crypto')\nconst colors = require('colors')\nconst { series } = require('async')\nconst git = require('git-state')\n\nrequire('dotenv').config({ path: 'environments/.env.prod' }) // eslint-disable-line\n\nconst ENCODED_PASS_CODE =\n ''\n\nfunction getVersion() {\n // eslint-disable-next-line\n var pjson = require('../package.json')\n console.log(pjson.version)\n return pjson.version\n}\n\nasync function confirmVersion() {\n console.log(`\\n\\nCurrent Version is: ${getVersion()}`)\n // eslint-disable-next-line\n const rl = require('readline').createInterface({\n input: process.stdin,\n output: process.stdout,\n })\n\n return new Promise(resolve => {\n rl.question(\n colors.cyan('\\n\\nEnter \"yee\" to confirm this is a new version number: '),\n res => {\n rl.close()\n const input = res.toLowerCase()\n resolve(input === 'yee')\n }\n )\n })\n}\n\nasync function validateGitState() {\n return new Promise(res => {\n git.isGit('.', function (exists) {\n if (!exists) return false\n git.check('.', (err, result) => {\n if (err) throw err\n console.log(colors.yellow.bold('Validating Git State:\\n'), result, '\\n')\n if (result.branch !== 'master') {\n console.error(\n colors.red.bold(\n 'Cannot deploy to production from branch other than master. Exiting...\\n'\n )\n )\n res(false)\n } else if (result.ahead > 0) {\n console.error(\n colors.red.bold(\n 'Cannot deploy to production with un-pushed commits. Exiting...\\n'\n )\n )\n res(false)\n } else if (result.dirty > 0) {\n console.error(\n colors.red.bold(\n 'Cannot deploy to production with un-committed changes. Exiting...\\n'\n )\n )\n res(false)\n } else {\n console.log(colors.green('\\nGit state validated.'))\n res(true)\n }\n })\n })\n })\n}\n\nasync function requestPassCodeAuthorization() {\n const rl = require('readline').createInterface({\n input: process.stdin,\n output: process.stdout,\n })\n\n return new Promise(resolve => {\n rl.question(\n colors.cyan('\\n\\nEnter security pass code to continue '),\n res => {\n rl.close()\n const encoded_input = crypto\n .createHash('sha256')\n .update(res.toLowerCase())\n .digest('hex')\n resolve(encoded_input === ENCODED_PASS_CODE)\n }\n )\n })\n}\n\nasync function runCommand(command, callback) {\n console.log(colors.yellow('\\n\\nRUNNING:', command))\n const process = exec(command, error => {\n console.log(colors.green('\\n\\nCOMPLETED:', command))\n if (error) console.error(error)\n else callback()\n })\n process.stdout.on('data', data => {\n console.log(data.toString())\n })\n}\n\nasync function main() {\n if (await confirmVersion()) {\n if (await validateGitState()) {\n if (await requestPassCodeAuthorization()) {\n series(\n [\n callback =>\n runCommand(\n 'cp environments/.env.prod .env.production.local',\n callback\n ),\n callback => runCommand('rm -rf build', callback),\n callback => runCommand('rm -rf node_modules', callback),\n callback => runCommand('npm ci', callback),\n callback => runCommand('npm run build', callback),\n callback => runCommand('rm .env.production.local', callback),\n callback =>\n runCommand(\n 'cp environments/firebase.prod.json firebase.json',\n callback\n ),\n callback => runCommand('firebase use prod', callback),\n callback =>\n runCommand(\n 'firebase deploy --only hosting:sharingexcess',\n callback\n ),\n callback =>\n runCommand(\n 'cp environments/firebase.dev.json firebase.json',\n callback\n ),\n callback => runCommand('firebase use default', callback),\n callback =>\n runCommand(\n `SENTRY_AUTH_TOKEN=${\n process.env.SENTRY_AUTH_TOKEN\n } sentry-cli releases --org sharingexcess -p rescue new ${getVersion()}`,\n callback\n ),\n callback =>\n runCommand(\n `SENTRY_AUTH_TOKEN=${\n process.env.SENTRY_AUTH_TOKEN\n } sentry-cli releases --org sharingexcess -p rescue deploys ${getVersion()} new -e production`,\n callback\n ),\n callback =>\n runCommand(\n `SENTRY_AUTH_TOKEN=${\n process.env.SENTRY_AUTH_TOKEN\n } sentry-cli releases --org sharingexcess -p rescue finalize ${getVersion()}`,\n callback\n ),\n ],\n err => {\n err\n ? console.error('Error in deployment:', err)\n : console.log(colors.green.bold('\\n\\nDEPLOYMENT SUCCESSFUL!\\n'))\n }\n )\n }\n } else console.log('Invalid pass code. Exiting...')\n } else console.log('No worries fam, cancelling deploy...')\n}\n\nmain()", "dangerousExampleEn": "1. const crypto = require(\"crypto\");\n2. const dan_hash_content = crypto.createHash('sha256').update(content).digest('hex');\nLine 2: This is insecure because data without a salt value is used for the hash function.", "safeExampleEn": "1. const crypto = require(\"crypto\");\n2. \n3. const randomBytes = new Uint32Array(1);\n4. crypto.randomFillSync(randomBytes);\n5. const safe_salt1 = randomBytes[0].toString();\n6. const safe_hash_content1 = crypto.createHash('sha256').update(orgin_content+safe_salt1).digest('hex');\n7. \n8. const safe_salt2 = crypto.randomBytes(4).toString('hex');\n9. const safe_hash_content2 = crypto.createHash('sha256').update(orgin_content+safe_salt2).digest('hex');\nLine 6, 9: This is secure because a hash function with a salt value is used.", "contexts": [{"lineNo": 87, "eventType": "sink", "messageKey": "jschk.WEAK_HASH.JS.defect.salt", "params": {"arg0": "sha256"}}]}} {"id": "da3a5ea203d17ae8608be4685f6504bb6b09aa0533367c93c2711f8c570611d9", "license": {"spdx": ["MIT"], "repo": "spaceify/spaceify", "path": "code/securitymodel.js", "repo_head_hexsha": "4296d6c93cad32bb735cefc9b8157570f18ffee4", "stack_hexsha": "1d0ea279dff0f9d2499c8cd1357ce895fe4bbf61", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "One-way Hash Function Used Without Salt", "issueDescriptionEn": "When storing sensitive information such as passwords, it is recommended to use a one-way hash function that converts data of any length into a fixed-sized hash value. If sensitive information is stored without using salt in a one-way hash function, an attacker may identify the hash value using a pre-calculated rainbow table.\nWhen storing sensitive information such as passwords, it is secure to use a one-way hash function that converts data of any length into a fixed-sized hash value. In addition, it is necessary to generate a unique salt value for each user. To accomplish this, the salt value should be stored separately for each user. The latest hash functions, such as bcrypt and PBKDF2, support this process. However, if you use a hash function that does not support it, you will need to manually provide the salt value.", "issueLineNumber": 105, "entireCode": "\"use strict\";\n\n/**\n * Service model, 20.7.2015 Spaceify Oy\n * \n * @class SecurityModel\n */\n\nvar fs = require(\"fs\");\nvar url = require(\"url\");\nvar crypto = require(\"crypto\");\nvar fibrous = require(\"fibrous\");\nvar rangeCheck = require(\"range_check\");\nvar language = require(\"./language\");\nvar Database = require(\"./database\");\nvar SpaceifyError = require(\"./spaceifyerror\");\nvar SpaceifyConfig = require(\"./spaceifyconfig\");\nvar SpaceifyUtility = require(\"./spaceifyutility\");\nvar WebSocketRpcConnection = require(\"./websocketrpcconnection\");\n\nfunction SecurityModel()\n{\nvar self = this;\n\nvar errorc = new SpaceifyError();\nvar config = new SpaceifyConfig();\nvar utility = new SpaceifyUtility();\n\nvar sessions = {};\nvar coreSettings = null;\nvar caCrt = config.SPACEIFY_WWW_PATH + config.SPACEIFY_CRT;\n\nvar adminLastLogin = null;\n\n\t// NETWORK -- -- -- -- -- -- -- -- -- -- //\nself.isLocalIP = function(ip)\n\t{\n\t/*if(!ip.match(new RegExp(config.IP_REGX)))\n\t\treturn false;\n\n\tvar parts = ip.split(\".\");\n\tif(parts[0] == \"127\" || ip == config.EDGE_IP)\n\t\treturn true;*/\n\n\tif(ip == \"127.0.0.1\" || ip == \"::ffff:127.0.0.1\" || ip == \"::ffff:7f00:1\")\n\t\treturn true;\n\n\treturn false;\n\t}\n\nself.isApplicationIP = function(ip)\n\t{\n\treturn rangeCheck.inRange(ip, config.APPLICATION_SUBNET);\n\t}\n\nself.getEdgeURL = function()\n\t{\n\treturn config.EDGE_HOSTNAME;\n\t}\n\nself.getApplicationURL = function(isSecure)\n\t{\n\treturn (isSecure ? \"http://\" : \"https://\") + config.EDGE_HOSTNAME + \":\" + (isSecure ? \"80\" : \"443\");\n\t}\n\n\t// AUTHENTICATION -- -- -- -- -- -- -- -- -- -- //\nself.adminLogIn = fibrous( function(password, remoteAddress)\n\t{\n\tcheckSessionTTL();\n\n\tvar user;\n\tvar shasum;\n\tvar result;\n\tvar timestamp;\n\tvar password_hash;\n\tvar adminLastLogin;\n\tvar sessionId = null;\n\tvar database = new Database();\n\n\ttry {\n\t\tself.sync.isLocalSession(remoteAddress, null, true);\n\n\t\t// CHECK THE PASSWORD - UPDATE DATABASE\n\t\tuser = database.sync.getEdgeSettings();\n\n\t\tif(typeof user == \"undefined\")\n\t\t\tthrow language.E_ADMIN_LOGIN_EDGE_SETTING.pre(\"SecurityModel::adminLogIn\");\n\n\t\tadminLastLogin = user.admin_last_login\n\t\t\t\n\t\tshasum = crypto.createHash(\"sha512\");\n\t\tshasum.update(password + user.admin_salt);\n\t\tpassword_hash = shasum.digest(\"hex\").toString();\n\n\t\tif(password_hash != user.admin_password)\n\t\t\tthrow language.E_ADMIN_LOG_IN_FAILED.pre(\"SecurityModel::adminLogIn\");\n\n\t\ttimestamp = Date.now();\n\n\t\tdatabase.sync.adminLoggedIn([timestamp]);\n\n\t\t// START A NEW SESSION\n\t\tshasum = crypto.createHash(\"sha512\");\n\t\tresult = utility.bytesToHexString(crypto.randomBytes(32));\n\t\tshasum.update(result);\n\t\tsessionId = shasum.digest(\"hex\").toString();\n\n\t\tsessions[sessionId] = {timestamp: timestamp, remoteAddress: remoteAddress};\n\t\t}\n\tcatch(err)\n\t\t{\n\t\tthrow errorc.make(err);\n\t\t}\n\tfinally\n\t\t{\n\t\tdatabase.close();\n\t\t}\n\n\treturn sessionId;\n\t});\n\nself.adminLogOut = fibrous( function(sessionId, remoteAddress)\n\t{\n\tself.sync.isLocalSession(remoteAddress, null, true);\n\n\tif(sessionId in sessions)\n\t\tdelete sessions[sessionId];\n\n\tcheckSessionTTL();\n\t});\n\nself.getAdminLastLogin = function()\n\t{\n\tvar user;\n\tvar adminLastLogin_ = null;\n\tvar database = new Database();\n\n\ttry {\n\t\tif(adminLastLogin)\n\t\t\tadminLastLogin_ = adminLastLogin;\n\t\telse\n\t\t\t{\n\t\t\tif((user = database.sync.getEdgeSettings()))\n\t\t\t\tadminLastLogin = adminLastLogin_ = user.admin_last_login;\n\t\t\t}\n\t\t}\n\tcatch(err)\n\t\t{\n\t\t}\n\tfinally\n\t\t{\n\t\tdatabase.close();\n\t\t}\n\n\treturn adminLastLogin_;\n\t}\n\t\nself.findSession = fibrous( function(sessionId)\n\t{\n\tvar session;\n\n\t// Check temporary session\n\tif(utility.sync.isLocal(config.SPACEIFY_TEMP_SESSIONID, \"file\"))\n\t\t{\n\t\tsession = fs.sync.readFile(config.SPACEIFY_TEMP_SESSIONID, \"utf8\");\n\n\t\tsession = utility.parseJSON(session, true);\n\n\t\tif(session.sessionId == sessionId)\n\t\t\treturn session;\n\t\t}\n\n\t// Check log in sessions\n\tcheckSessionTTL();\n\n\tif(sessionId in sessions)\n\t\treturn sessions[sessionId];\n\n\treturn null;\n\t});\n\nself.createTemporarySession = fibrous( function(remoteAddress)\n\t{\n\tvar session\t=\t{\n\t\t\t\t\tremoteAddress: remoteAddress,\n\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\tsessionId: utility.randomString(64, true),\n\t\t\t\t\t};\n\n\tfs.sync.writeFile(config.SPACEIFY_TEMP_SESSIONID, JSON.stringify(session), \"utf8\");\n\n\treturn session.sessionId;\n\t});\n\nself.destroyTemporarySession = fibrous( function()\n\t{\n\tif(utility.sync.isLocal(config.SPACEIFY_TEMP_SESSIONID, \"file\"))\n\t\tfs.sync.unlink(config.SPACEIFY_TEMP_SESSIONID);\n\t});\n\nself.isLocalSession = fibrous( function(remoteAddress, sessionId, throws)\n\t{\n\tvar isLocSes = false;\n\n\ttry {\n\t\tif(!self.isLocalIP(remoteAddress))\n\t\t\tthrow language.E_IS_LOCAL_SESSION_NON_EDGE_CALLER.pre(\"SecurityModel::isLocalSession\");\t\n\n\t\tif(sessionId && !self.sync.findSession(sessionId))\n\t\t\tthrow language.E_ADMIN_NOT_LOGGED_IN.pre(\"SecurityModel::isLocalSession\");\n\n\t\tisLocSes = true;\n\t\t}\n\tcatch(err)\n\t\t{\n\t\tif(throws)\n\t\t\tthrow err;\n\t\t}\n\n\treturn isLocSes;\n\t});\n\nvar checkSessionTTL = function()\n\t{ // Remove expired sessions (= garbage collection)\n\tvar now = Date.now();\n\n\tfor(var i in sessions)\n\t\t{\n\t\tif((now - sessions[i].timestamp) > coreSettings.log_in_session_ttl)\n\t\t\tdelete sessions[i];\n\t\t}\n\t}\n\nself.refreshLogInSession = function(sessionId)\n\t{\n\tif(sessionId in sessions)\n\t\tsessions[sessionId].timestamp = Date.now();\n\t}\n\n\t// SAME ORIGIN POLICY -- -- -- -- -- -- -- -- -- -- //\nself.sameOriginPolicyStartSpacelet = function(manifest, URL)\n\t{\n\tvar matches = 0;\n\tvar origins = manifest.origins;\n\tvar hostname = url.parse(URL).hostname;\n//console.log(\"++++++++++++++++++++++++++\", manifest.unique_name, origins, URL);\nreturn true;\n\tfor(var i = 0; i < origins.length; i++)\n\t\t{\n\t\tif(matchOrigin(origins[i], hostname))\n\t\t\tmatches++;\n\t\t}\n\n\treturn (matches > 0 ? true : false);\n\t}\n\nvar matchOrigin = function(origin, hostname)\n\t{\n\tvar rex;\n\tvar matched;\n\tvar cgs = \"\";\n\t\t\n\t// Get origin components, e.g. *.example.* -> [ '*', '.example.', '*', '' ]\n\tmatched = origin.match(/\\*|[^\\*]*/g);\n\n\t// Make a capture grouped regular expression of the components, e.g. *.example.* -> (.*)(\\.example\\.)(.*)\n\tfor(var i = 0; i < matched.length; i++)\n\t\t{\n\t\tif(matched[i] == \"*\")\n\t\t\tcgs\t+= \"(.*)\";\n\t\telse if(matched[i] != \"\")\n\t\t\tcgs\t+= \"(\" + matched[i].replace(/\\./g, \"\\\\.\") + \")\";\n\t\t}\n\n\t// Match the hostname - the match must be complete (...)\n\trex = new RegExp(\"(\" + cgs + \")\");\n\tmatched = rex.exec(hostname);\n\n\treturn (matched && matched[0] == hostname ? true : false);\n\t}\n\n\t// REGISTER, UNREGISTER, GET SERVICES -- -- -- -- -- -- -- -- -- -- //\nself.registerService = function(application, service_name)\n\t{\n\treturn application.registerService(service_name, true);\n\t}\n\nself.unregisterService = function(application, service_name)\n\t{\n\treturn application.registerService(service_name, false);\n\t}\n\nself.getOpenServices = function(services, remoteAddress)\n\t{\n\tvar result = [];\n\n\tif(services)\n\t\t{\n\t\tfor(var i = 0; i < services.length; i++)\n\t\t\t{ // Web pages get only OPEN services, applications and spacelets get also OPEN_LOCAL services\n\t\t\tif(services[i].service_type == config.OPEN)\n\t\t\t\tresult.push(self.makePublicService(services[i]));\n\t\t\telse if(self.isApplicationIP(remoteAddress) && services[i].service_type == config.OPEN_LOCAL)\n\t\t\t\tresult.push(self.makePublicService(services[i]));\n\t\t\t}\n\t\t}\n\n\treturn result;\n\t}\n\nself.getService = function(service, application, remoteAddress)\n\t{\n\tvar requiresServices;\n\tvar serviceReturn = null;\n\n\tif(!service.isRegistered)\n\t\tthrow language.E_GET_SERVICE_UNREGISTERED.preFmt(\"SecurityModel::getService\", {\"~name\": service.service_name});\n\n\tif(service.service_type == config.OPEN || service.service_type == config.HTTP)\t\t\t\t\t// Service is open for all\n\t\tserviceReturn = self.makePublicService(service);\n\telse if(self.isApplicationIP(remoteAddress))\t\t\t\t\t\t\t\t\t\t\t\t\t// Caller is an application or a spacelet\n\t\t{\n\t\tif(!application)\n\t\t\tthrow language.E_GET_SERVICE_APPLICATION_NOT_FOUND.pre(\"SecurityModel::getService\");\n\n\t\tif(service.service_type == config.OPEN_LOCAL)\t\t\t\t\t\t\t\t\t\t\t\t// Service is open for all application and spacelets\n\t\t\tserviceReturn = self.makePublicService(service);\n\t\telse\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Open only if service is listed in the required list\n\t\t\t{\n\t\t\trequiresServices = application.getRequiresServices();\n\t\t\tif(!requiresServices)\n\t\t\t\tthrow language.E_GET_SERVICE_APPLICATION_REQUIRES_SERVICES_NOT_DEFINED.preFmt(\"SecurityModel::getService\", {\"unique_name\": application.getUniqueName()});\n\n\t\t\tfor(var i = 0; i < requiresServices.length; i++)\n\t\t\t\t{\n\t\t\t\tif(requiresServices[i].service_name == service.service_name)\n\t\t\t\t\t{ serviceReturn = self.makePublicService(service); break; }\n\t\t\t\t}\n\n\t\t\tif(!serviceReturn)\n\t\t\t\tthrow language.E_GET_SERVICE_FORBIDDEN.preFmt(\"SecurityModel::getService\", {\"~name\": service.service_name});\n\t\t\t}\n\t\t}\n\n\t// ToDo: create iptable rule to allow or block traffic.\n\n\treturn serviceReturn;\n\t}\n\nself.makePublicService = function(service)\n\t{ // Only some of the service fields are passed to external callers (web page, applications, spacelets)\n\tvar publicService = {};\n\n\tpublicService.service_name = service.service_name;\n\tpublicService.service_type = service.service_type;\n\tpublicService.port = service.port;\n\tpublicService.securePort = service.securePort;\n\tpublicService.ip = service.ip;\n\tpublicService.unique_name = service.unique_name;\n\tpublicService.type = service.type;\n\n\treturn publicService;\n\t}\n\n\t// ADMIN SESSION MANAGEMENT HELPERS -- -- -- -- -- -- -- -- -- -- //\nself.isAdminLoggedIn = fibrous( function(sessionId, throws)\n\t{\n\tvar coreRPC = null;\n\tvar isLoggedIn = false;\n\n\ttry {\n\t\tcoreRPC = new WebSocketRpcConnection();\n\t\tcoreRPC.sync.connect({hostname: config.CONNECTION_HOSTNAME, port: config.CORE_PORT_SECURE, isSecure: true, caCrt: caCrt});\n\n\t\tisLoggedIn = coreRPC.sync.callRpc(\"isAdminLoggedIn\", [sessionId], self);\n\n\t\tif(!isLoggedIn && throws)\n\t\t\tthrow language.E_ADMIN_NOT_LOGGED_IN.pre(\"SecurityModel::isAdminLoggedIn\");\n\t\t}\n\tcatch(err)\n\t\t{\n\t\tthrow err;\n\t\t}\n\tfinally\n\t\t{\n\t\tif(coreRPC)\n\t\t\tcoreRPC.close();\n\t\t}\n\n\treturn isLoggedIn;\n\t});\n\n\t// CORE SETTINGS -- -- -- -- -- -- -- -- -- -- //\nself.setCoreSettings = function(settings)\n\t{\n\tcoreSettings = settings;\n\t}\n\n}\n\nmodule.exports = SecurityModel;", "dangerousExampleEn": "1. const crypto = require(\"crypto\");\n2. const dan_hash_content = crypto.createHash('sha256').update(content).digest('hex');\nLine 2: This is insecure because data without a salt value is used for the hash function.", "safeExampleEn": "1. const crypto = require(\"crypto\");\n2. \n3. const randomBytes = new Uint32Array(1);\n4. crypto.randomFillSync(randomBytes);\n5. const safe_salt1 = randomBytes[0].toString();\n6. const safe_hash_content1 = crypto.createHash('sha256').update(orgin_content+safe_salt1).digest('hex');\n7. \n8. const safe_salt2 = crypto.randomBytes(4).toString('hex');\n9. const safe_hash_content2 = crypto.createHash('sha256').update(orgin_content+safe_salt2).digest('hex');\nLine 6, 9: This is secure because a hash function with a salt value is used.", "contexts": [{"lineNo": 105, "eventType": "sink", "messageKey": "jschk.WEAK_HASH.JS.defect.salt", "params": {"arg0": "sha512"}}]}} {"id": "606ead404ba4aa615406492dc9b6543c598c5b389269d26664d4329f8c723a10", "license": {"spdx": ["MIT"], "repo": "aleksandra-b-t/FightPandemics", "path": "backend/lib/components/Veriff.js", "repo_head_hexsha": "7ad430f2ede42e39c52ed111448121a4ae414cd2", "stack_hexsha": "dbcbb95ed2cee24bf099359ca87af6baa7c80342", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "One-way Hash Function Used Without Salt", "issueDescriptionEn": "When storing sensitive information such as passwords, it is recommended to use a one-way hash function that converts data of any length into a fixed-sized hash value. If sensitive information is stored without using salt in a one-way hash function, an attacker may identify the hash value using a pre-calculated rainbow table.\nWhen storing sensitive information such as passwords, it is secure to use a one-way hash function that converts data of any length into a fixed-sized hash value. In addition, it is necessary to generate a unique salt value for each user. To accomplish this, the salt value should be stored separately for each user. The latest hash functions, such as bcrypt and PBKDF2, support this process. However, if you use a hash function that does not support it, you will need to manually provide the salt value.", "issueLineNumber": 11, "entireCode": "const axios = require(\"axios\");\nconst crypto = require(\"crypto\");\nconst { config } = require(\"../../config\");\n\nconst {\n veriff: { baseUrl: BASE_URL, publicKey: PUBLIC_KEY, privateKey: PRIVATE_KEY },\n} = config;\n\nconst generateXSignature = async (payload) => {\n const signature = crypto.createHash(\"sha256\");\n signature.update(new Buffer.from(payload, \"utf8\"));\n signature.update(new Buffer.from(PRIVATE_KEY, \"utf8\"));\n return signature.digest(\"hex\");\n};\n\nconst createSessionUrl = async (user) => {\n const body = {\n verification: {\n callback: `https://fightpandemics.com/${\n user.ownerId ? \"organisation\" : \"profile\"\n }/${user._id}`,\n person: {\n firstName: user.name || user.firstName,\n lastName: user.lastName,\n },\n vendorData: user._id,\n lang: \"en\",\n timestamp: new Date(),\n },\n };\n\n try {\n const res = await axios({\n url: \"/v1/sessions/\",\n method: \"POST\",\n baseURL: BASE_URL,\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-AUTH-CLIENT\": PUBLIC_KEY,\n },\n data: body,\n });\n\n if (res.data.status === \"success\") return res.data.verification.url;\n return null;\n } catch (err) {\n return null;\n }\n};\n\nconst validateWebhookEvent = async (req, reply) => {\n const incomingXAuthClient = req.headers[\"x-auth-client\"];\n // reject if \"x-auth-client\" is not equal to PUBLIC_KEY\n if (PUBLIC_KEY !== incomingXAuthClient) {\n req.log.error(`staging debug: 403 details 1 - ${PUBLIC_KEY}, ${incomingXAuthClient}`);\n throw false;\n }\n req.log.error(`staging debug: working 1 - ${PUBLIC_KEY}, ${incomingXAuthClient}`);\n\n // use rawBody + PRIVATE_KEY to build the xSignature\n // and compare it to \"x-signature\" header.\n const rawBody = JSON.stringify(req.body);\n const incomingXSignature = req.headers[\"x-signature\"];\n const xSignature = await generateXSignature(rawBody);\n\n if (xSignature != incomingXSignature) {\n req.log.error(`staging debug: 403 details 2 - ${xSignature}, ${incomingXSignature}`);\n throw false;\n }\n req.log.error(`staging debug: working 2 - ${xSignature}, ${incomingXSignature}`);\n};\n\nmodule.exports = {\n createSessionUrl,\n validateWebhookEvent,\n};", "dangerousExampleEn": "1. const crypto = require(\"crypto\");\n2. const dan_hash_content = crypto.createHash('sha256').update(content).digest('hex');\nLine 2: This is insecure because data without a salt value is used for the hash function.", "safeExampleEn": "1. const crypto = require(\"crypto\");\n2. \n3. const randomBytes = new Uint32Array(1);\n4. crypto.randomFillSync(randomBytes);\n5. const safe_salt1 = randomBytes[0].toString();\n6. const safe_hash_content1 = crypto.createHash('sha256').update(orgin_content+safe_salt1).digest('hex');\n7. \n8. const safe_salt2 = crypto.randomBytes(4).toString('hex');\n9. const safe_hash_content2 = crypto.createHash('sha256').update(orgin_content+safe_salt2).digest('hex');\nLine 6, 9: This is secure because a hash function with a salt value is used.", "contexts": [{"lineNo": 11, "eventType": "sink", "messageKey": "jschk.WEAK_HASH.JS.defect.salt", "params": {"arg0": "sha256"}}]}} {"id": "d2e4e0e66b26e1fb6f2df75dfc55bda7c0f5605b882a2841d47a5d78b075f988", "license": {"spdx": ["MIT"], "repo": "veres7/Tuchat", "path": "server/controllers/auth.js", "repo_head_hexsha": "d9d844ffa84efc39ea602d87d6ed417e2e4362a3", "stack_hexsha": "c02a1e03f94de4d84d788e6341c07881f1cad53b", "match": "repo_path"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "One-way Hash Function Used Without Salt", "issueDescriptionEn": "When storing sensitive information such as passwords, it is recommended to use a one-way hash function that converts data of any length into a fixed-sized hash value. If sensitive information is stored without using salt in a one-way hash function, an attacker may identify the hash value using a pre-calculated rainbow table.\nWhen storing sensitive information such as passwords, it is secure to use a one-way hash function that converts data of any length into a fixed-sized hash value. In addition, it is necessary to generate a unique salt value for each user. To accomplish this, the salt value should be stored separately for each user. The latest hash functions, such as bcrypt and PBKDF2, support this process. However, if you use a hash function that does not support it, you will need to manually provide the salt value.", "issueLineNumber": 116, "entireCode": "const crypto = require(\"crypto\");\nconst User = require(\"../models/User\");\nconst ErrorResponse = require(\"../utils/errorResponse\");\nconst sendEmail = require(\"../utils/sendEmail\");\n\nfunction emailIsValid(email) {\n return /\\S+@\\S+\\.\\S+/.test(email);\n}\n\nexports.register = async (req, res, next) => {\n const { username, email, password } = req.body;\n if (!username || !email || !password) {\n return next(new ErrorResponse(\"Please enter credentials\", 400));\n }\n\n try {\n if (await User.findOne({ email })) {\n return next(new ErrorResponse(\"E-mail already exists\", 400));\n }\n if (await User.findOne({ username })) {\n return next(new ErrorResponse(\"Username already exists\", 400));\n }\n\n await User.create({\n username,\n email,\n password,\n });\n res.status(200).json({\n success: true,\n data: \"Registered successfully!\",\n });\n } catch (error) {\n next(error);\n }\n};\n\nexports.login = async (req, res, next) => {\n const { username, email, password } = req.body;\n if (!username || !email || !password) {\n return next(new ErrorResponse(\"Please enter credentials\", 400));\n }\n\n try {\n const userByUsername = await User.findOne({ username }).select(\"+password\");\n\n if (!userByUsername) {\n const userByMail = await User.findOne({ email }).select(\"+password\");\n if (userByMail) {\n const isMatch = await userByMail.matchPasswords(password);\n if (!isMatch) {\n return next(new ErrorResponse(\"Invalid credentials\", 401));\n }\n return sendToken(userByMail, 200, res);\n }\n\n return next(new ErrorResponse(\"Invalid credentials\", 401));\n }\n\n const isMatch = await userByUsername.matchPasswords(password);\n\n if (!isMatch) {\n return next(new ErrorResponse(\"Invalid credentials\", 401));\n }\n\n sendToken(userByUsername, 200, res);\n } catch (error) {\n next(error);\n }\n};\n\n// Forgot password\n\nexports.fpassword = async (req, res, next) => {\n const { email } = req.body;\n if (!emailIsValid(email)) {\n return next(new ErrorResponse(\"Please enter valid e-mail address\"), 404);\n }\n try {\n const user = await User.findOne({ email });\n\n if (!user) {\n return next(new ErrorResponse(\"E-mail could not be sent\"), 404);\n }\n const resetToken = user.getResetPasswordToken();\n\n await user.save();\n\n const resetUrl = `http://localhost:3000/resetpassword/${resetToken}`;\n\n const message = `

    Password reset requested.

    \n

    Click here to reset your password

    \n \n Reset password`;\n try {\n await sendEmail({\n to: user.email,\n subject: \"Password reset request\",\n text: message,\n });\n res.status(200).json({ success: true, data: \"Email sent\" });\n } catch (error) {\n user.resetPasswordToken = ;\n user.resetPasswordExpire = undefined;\n\n await user.save();\n\n return next(new ErrorResponse(\"Email couldn't be send\"), 500);\n }\n } catch (error) {\n next(error);\n }\n};\n\nexports.resetpassword = async (req, res, next) => {\n const resetPasswordToken = crypto\n .createHash(\"sha256\")\n .update(req.params.resetToken)\n .digest(\"hex\");\n\n try {\n const user = await User.findOne({\n resetPasswordToken,\n resetPasswordExpire: { $gt: Date.now() },\n });\n if (!user) {\n return next(new ErrorResponse(\"Invalid Reset Token\"), 400);\n }\n user.password = ;\n user.resetPasswordToken = ;\n user.resetPasswordExpire = ;\n\n await user.save();\n\n res.status(201).json({ success: true, data: \"Password reset success\" });\n } catch (error) {\n next(error);\n }\n};\n\nconst sendToken = (user, statusCode, res) => {\n const token = user.getSignedToken();\n const userId = user._id;\n const username = user.username;\n return res\n .status(statusCode)\n .json({ success: true, token, userId, username });\n};", "dangerousExampleEn": "1. const crypto = require(\"crypto\");\n2. const dan_hash_content = crypto.createHash('sha256').update(content).digest('hex');\nLine 2: This is insecure because data without a salt value is used for the hash function.", "safeExampleEn": "1. const crypto = require(\"crypto\");\n2. \n3. const randomBytes = new Uint32Array(1);\n4. crypto.randomFillSync(randomBytes);\n5. const safe_salt1 = randomBytes[0].toString();\n6. const safe_hash_content1 = crypto.createHash('sha256').update(orgin_content+safe_salt1).digest('hex');\n7. \n8. const safe_salt2 = crypto.randomBytes(4).toString('hex');\n9. const safe_hash_content2 = crypto.createHash('sha256').update(orgin_content+safe_salt2).digest('hex');\nLine 6, 9: This is secure because a hash function with a salt value is used.", "contexts": [{"lineNo": 116, "eventType": "sink", "messageKey": "jschk.WEAK_HASH.JS.defect.salt", "params": {"arg0": "sha256"}}]}} {"id": "af3135c46b2fabf9e9b2cfe867660a4d1de30623f054435d5ba1a33ef29645fe", "license": {"spdx": ["BSD-3-Clause"], "repo": "Argsen/tkiee", "path": "api/controllers/EvaluationController.js", "repo_head_hexsha": "9f49ef1c5eed730e6c48cc37ac556811a2522f70", "stack_hexsha": "6d9d8c1b19c09713bcc89ada87fa49363ec56147", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "One-way Hash Function Used Without Salt", "issueDescriptionEn": "When storing sensitive information such as passwords, it is recommended to use a one-way hash function that converts data of any length into a fixed-sized hash value. If sensitive information is stored without using salt in a one-way hash function, an attacker may identify the hash value using a pre-calculated rainbow table.\nWhen storing sensitive information such as passwords, it is secure to use a one-way hash function that converts data of any length into a fixed-sized hash value. In addition, it is necessary to generate a unique salt value for each user. To accomplish this, the salt value should be stored separately for each user. The latest hash functions, such as bcrypt and PBKDF2, support this process. However, if you use a hash function that does not support it, you will need to manually provide the salt value.", "issueLineNumber": 346, "entireCode": "/**\n * QuizController\n *\n * @module :: Controller\n * @description :: A set of functions called `actions`.\n *\n * Actions contain code telling Sails how to respond to a certain type of request.\n * (i.e. do stuff, then send some JSON, show an HTML page, or redirect to another URL)\n *\n * You can configure the blueprint URLs which trigger these actions (`config/controllers.js`)\n * and/or override them with custom routes (`config/routes.js`)\n *\n * NOTE: The code you write here supports both HTTP and Socket.io automatically.\n *\n * @docs :: http://sailsjs.org/#!documentation/controllers\n */\nvar fs = require('fs'),\n crypto = require('crypto'),\n platform = require('platform');\n\nmodule.exports = {\n\n /**\n * Overrides for the settings in `config/controllers.js`\n * (specific to QuizController)\n */\n _config: {},\n\t\n\tfind: function (req, res) {\n if (req.method === 'POST') {\n var sessionId = req.session.sSessionId || req.param('sessionId') || 0,\n room = _getRoom(req, res);\n\n Evaluation.find({'sessionId': sessionId}).exec(function (err, evaluation) {\n if (err) return res.json({'error': err});\n if (evaluation.length == 0) return res.json({'error': \"No evaluation with that sessionId exists!\"});\n\n return res.json(evaluation);\n });\n } else {\n sails.log.info(\"[EvaluationController.find] Bad request, please use POST method.\");\n return res.json({'error': \"Bad request for /evaluation/find, please use POST method.\"});\n }\t\t\n\t},\n\n start: function (req, res) {\n if (req.method === 'POST') {\n var sessionId = req.session.sSessionId || req.param('sessionId') || 0,\n room = _getRoom(req, res);\n\n\t\t\tEvaluation.find({'sessionId': sessionId}).exec(function (err, evaluation) {\n if (err) return res.json({'error': err});\n if (evaluation.length == 0) return res.json({'error': \"No evaluation with that sessionId exists!\"});\n\n sails.io.sockets.in(room).emit('evaluationStart', evaluation);\n return res.json(evaluation);\n });\n } else {\n sails.log.info(\"[EvaluationController.start] Bad request, please use POST method.\");\n return res.json({'error': \"Bad request for /evaluation/start, please use POST method.\"});\n }\n },\n\t\n\tsubmit: function (req, res) {\n\t\tif (req.method === 'POST') {\n var userId = req.param('userId') || req.session.userId || 0,\n evaluationId = req.param('evaluationId') || 0,\n feedback = req.param('feedback') || '',\n room = _getRoom(req, res),\n hostRoom = room + '-host';\n\t\t\t\n if (evaluationId == 0) {\n return res.json({'error': 'a quiz id should be given'});\n }\n if (feedback == '') {\n return res.json({'message': 'feedback is empty'});\n }\n\n var evaluationAnswer = {\n 'userId': userId,\n 'evaluationId': evaluationId,\n 'feedback': feedback\n };\n\n EvaluationAnswer.create(evaluationAnswer).done(function (err, evaluationA) {\n if (err) {\n sails.log.warn(err);\n return res.json({'error': \"cannot create evaluation answer\"});\n }\n\n sails.log.info(\"New evaluation answer created:\", evaluationA);\n return res.json(evaluationA);\n });\t\n\t\t\t\t\n\t\t} else {\n sails.log.info(\"[EvaluationController.submit] Bad request, please use POST method.\");\n return res.json({'error': \"Bad request for /evaluation/submit, please use POST method.\"});\n }\n\t},\n\t\n\tgetData: function (req, res) {\n var sessionId = req.session.sSessionId || req.param(\"sessionId\") || 0,\n keyPhase = req.session.sKeyPhase || req.param('session') || \"\",\n userId = req.session.sUserId || req.param('userId') || 0;\n\t\t\n\t\tvar Obj = {},\n\t\t\tcontent = [],\n\t\t\tm = 0;\n\n\t\t_findEvaluationObject(sessionId, function (err, evaluation) {\n\t\t\tconsole.log(\"evaluaton.length: \" + evaluation.length);\n\t\t\tif (evaluation.length == 0) {\n\t\t\t\treturn res.json({'result': 'There is no evaluation.'});\n\t\t\t} else {\n\t\t\t\tvar stat = evaluation;\n\t\t\t\tfor (var key in stat) {\n\t\t\t\t\tif (key == \"question\") {\n\t\t\t\t\t\tcontent.push(stat[key]);\n\t\t\t\t\t\tcontent.push(\" \");\n\t\t\t\t\t} else {\t\n\t\t\t\t\t\tfor (var key1 in stat[key]) {\n\t\t\t\t\t\t\tcontent.push(key1 + \" : \" + stat[key][key1]);\n\t\t\t\t\t\t\tcontent.push(\" \");\t\t\t\t\t\t\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tm++;\t\t\t\t\n\n\t\t\t\tif (m == evaluation.length) {\n\t\t\t\t\t_exportTxt(sessionId, userId, keyPhase, content, _windowsSystemCheck(req.headers['user-agent']) ? \"\\r\\n\" : \"\\n\"); \n\t\t\t\t\treturn res.json({'result': \"success\"});\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\t\n },\n \n delete: function (req, res) {\n if (req.method === 'POST') {\n var evaluationId = req.param('evaluationId') || 0;\n Evaluation.destroy({'id': evaluationId}).done(function (err) {\n if (err) {\n return console.log(err);\n } else {\n console.log(\"Evaluation \" + evaluationId + \" deleted\");\n }\n });\n EvaluationAnswer.destroy({'evaluationId': evaluationId}).done(function (err) {\n if (err) {\n return console.log(err);\n } else {\n console.log(\"Evaluation \" + evaluationId + \" deleted\");\n }\n });\n } else {\n sails.log.info(\"[UserController.find] Bad request, please use GET method.\");\n return res.json({'error': \"Bad request for /comment/find, please use GET method.\"});\n }\n },\n\n add: function (req, res) {\n if (req.method === 'POST') {\n var sessionId = req.param('sessionId') || req.session.sSessionId || 0,\n question = req.param('question'),\n options = req.param('options'),\n room = _getRoom(req, res),\n hostRoom = room + '-host';\n\n if (sessionId == 0) {\n return res.json({'error': 'a session id should be given'});\n }\n if (question == '') {\n return res.json({'message': 'question is empty'});\n }\n\n var evaluation = {\n 'sessionId': sessionId,\n 'question': question,\n 'options': options\n };\n\n Evaluation.create(evaluation).done(function (err, evaluationA) {\n if (err) {\n sails.log.warn(err);\n return res.json({'error': \"cannot create evaluation answer\"});\n }\n\n return res.json(evaluationA);\n });\n\n } else {\n sails.log.info(\"[EvaluationController.add] Bad request, please use POST method.\");\n return res.json({'error': \"Bad request for /evaluation/add, please use POST method.\"});\n }\n },\n\n update: function (req, res) {\n if (req.method === 'POST') {\n var sessionId = req.param('sessionId') || req.session.sSessionId || 0,\n question = req.param('question'),\n options = req.param('options'),\n evaluationId = req.param('evaluationId') ? parseInt(req.param('evaluationId')) : 0;\n\n if (sessionId == 0) {\n return res.json({'error': 'a session id should be given'});\n }\n if (question == '') {\n return res.json({'message': 'question is empty'});\n }\n\n var evaluation = {\n 'id': evaluationId,\n 'sessionId': sessionId,\n 'question': question,\n 'options': options\n };\n\n Evaluation.update({'id': evaluationId}, evaluation, function (err, evaluationA) {\n if (err) {\n sails.log.warn(err);\n return res.json({'error': \"cannot create quiz answer\"});\n }\n return res.json(evaluationA);\n });\n\n } else {\n sails.log.info(\"[EvaluationController.add] Bad request, please use POST method.\");\n return res.json({'error': \"Bad request for /evaluation/add, please use POST method.\"});\n }\n } \n};\n\nfunction _exportTxt(sessionId, userId, keyPhase, stat, newlineChar) {\n var filePath = sails.config.CONSTANT.UPLOAD_PATH + sails.config.CONSTANT.SEPERATOR + keyPhase + sails.config.CONSTANT.SEPERATOR + \"Evaluation_Result.txt\";\n\t\n fs.appendFile(filePath, stat.join(newlineChar), function (err) {\n if (err) {\n sails.log.warn('exec error: ' + err);\n }\n\n _generateHash({'path': filePath}, function (err, hash) {\n if (err) {\n sails.log.error(err);\n } else {\n fs.readFile(filePath, function (err, data) {\n if (err) {\n sails.log.error(err);\n } else {\n var now = new Date(),\n stats = fs.statSync(filePath),\n statFileName = [\"evaluation\", now.getFullYear(), (\"0\" + (now.getMonth() + 1)).slice(-2),\n (\"0\" + now.getDate()).slice(-2), keyPhase, hash.md5].join(\"-\") + \".txt\";\n\n S3Service.put({\n Key: statFileName,\n Body: data,\n ContentMD5: hash.base64,\n ContentLength: stats[\"size\"],\n ContentType: 'text/plain'\n }, function (err, result) {\n if (err) {\n console.log(\"Error uploading data: \", err);\n } else {\n File.create({\n 'sessionId': sessionId,\n 'userId': userId,\n 'name': statFileName,\n 'location': sails.config.CONSTANT.S3_BUCKET + '.s3.amazonaws.com/' + statFileName,\n 'size': stats[\"size\"],\n 'type': 'text'\n }).done(function (err, newFile) {\n fs.unlink(filePath, function (err) {\n if (err) sails.log.error(err);\n });\n });\n }\n });\n }\n });\n }\n });\n });\n} \n\nfunction _findEvaluationObject(sessionId, cb) {\n Quiz.find({'sessionId': sessionId, \"page\": 9999}).exec(function (err, evaluation) {\n\t\tif (err) {\n cb(err);\n } else {\n\t\t\tvar evaluationResult = {};\n\t\t\tif (evaluation.length > 0) {\n\t\t\t\tfor (var i=0; i {\n console.error(err);\n});\n\nrun(process.argv);", "dangerousExampleEn": "1. process.on(\"uncaughtException\", function(err) {\n2. // log necessary error details to log files\n3. //process.exit();\n4. });\nLine 1: uncaughtException was used but the current status of the program is unknown because the process has not been terminated explicitly.", "safeExampleEn": "1. process.on(\"uncaughtException\", function(err) {\n2. // log necessary error details to log files\n3. process.exit();\n4. });\nLine 3: This is secure because the process is terminated after the errors are logged.", "contexts": [{"lineNo": 5, "eventType": "sink", "messageKey": "jschk.UNCAUGHT_EXCEPTION.JS.defect", "params": {}}]}} {"id": "41d6b562aa5d652fe951c95f78d6c033a77c70e36222ca93002c6814a6a09f6a", "license": {"spdx": ["MIT"], "repo": "dd-center/SuperSpider", "path": "packages/superspider-mdb/index.js", "repo_head_hexsha": "825651b7dff30d27fe4578f3f1f9e8010f0dfecd", "stack_hexsha": "ae1b6f98be38321803678ebc879b1d76fcd5113a", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of uncaughtException", "issueDescriptionEn": "Using uncaughtException enables a developer to handle errors that could not be addressed by a developer beforehand. However, the official node document specifies that it should only be used as a last resort. This is because uncaughtException cannot guarantee a program will close after an error occurs.\nuncaughtException should be used for logging purposes. After logging the errors, the process needs to be terminated using process.exit();.", "issueLineNumber": 24, "entireCode": "const Koa = require('koa')\nconst app = new Koa()\nconst Router = require('koa-router')\nconst router = new Router()\n\nconst fs = require('fs')\n// const schedule = require('node-schedule')\nconst bodyParser = require('koa-bodyparser')\n\nconst delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms))\n\nconst rdb = require('./modules/rdb')\n\nconst MongoClient = require('mongodb').MongoClient\n\n// global.adbRunning = false\nglobal.amdb = false\nglobal.utrdb = false\n// global.rmdb = false\n// global.umdb = false\n\nglobal.usingAtHome = process.env.USINGATHOME\n\nprocess.on('uncaughtException', (err) => {\n console.log('ERR unc expt')\n console.log(err)\n})\n\n// schedule.scheduleJob('*/5 * * * *', adb)\n;(async () => {\n // Koa Init\n\n app.use(bodyParser())\n\n // // 其他页面通过 router 加载\n // let api = fs.readdirSync(__dirname + '/api')\n // api.forEach((element) => {\n // let module = require(__dirname + '/api/' + element)\n // /*\n // api 下面的每个文件负责一个特定的功能,分开管理\n // 通过 fs.readdirSync 读取 api 目录下的所有文件名,挂载到 router 上面\n // */\n // router.use(\n // '/' + element.replace('.js', ''),\n // module.routes(),\n // module.allowedMethods()\n // )\n // })\n // app.use(router.routes())\n\n app.listen(2166)\n\n // DB Init\n\n const client = new MongoClient(\n process.env.NODE_ENV == 'development'\n ? 'mongodb://localhost:27017/amdb'\n : 'mongodb://admin:' +\n process.env.MONGODB_PASS +\n '@' +\n process.env.MONGODB_IP +\n ':27017/admin?authMechanism=DEFAULT',\n { useNewUrlParser: true }\n )\n\n try {\n await client.connect()\n\n global.amdb = client.db('amdb').collection('maindb')\n global.utrdb = client.db('amdb').collection('utrdb')\n } catch (err) {\n console.log('ERR when connect to AMDB')\n console.log(err)\n process.exit(1)\n }\n global.amdb.createIndex(\n {\n // _id: -1,\n roomid: -1,\n livets: -1\n // ts: -1\n },\n (e, s) => {}\n )\n global.amdb.createIndex(\n {\n _id: -1\n },\n (e, s) => {}\n )\n global.amdb.createIndex(\n {\n roomid: -1\n },\n (e, s) => {}\n )\n global.amdb.createIndex(\n {\n ts: -1\n },\n (e, s) => {}\n )\n global.utrdb.createIndex(\n {\n uname: -1\n },\n (e, s) => {}\n )\n // global.amdb.createIndex(\n // {\n // _id: -1,\n // status: -1\n // },\n // (e, s) => {}\n // )\n\n // await adb()\n await delay(5000)\n console.log('RDB STARTED')\n await rdb()\n // await trdb()\n})()", "dangerousExampleEn": "1. process.on(\"uncaughtException\", function(err) {\n2. // log necessary error details to log files\n3. //process.exit();\n4. });\nLine 1: uncaughtException was used but the current status of the program is unknown because the process has not been terminated explicitly.", "safeExampleEn": "1. process.on(\"uncaughtException\", function(err) {\n2. // log necessary error details to log files\n3. process.exit();\n4. });\nLine 3: This is secure because the process is terminated after the errors are logged.", "contexts": [{"lineNo": 24, "eventType": "sink", "messageKey": "jschk.UNCAUGHT_EXCEPTION.JS.defect", "params": {}}]}} {"id": "b502c0dd1777a02178905d455b2adc8c6a3e32706b602210d33a9bcb4b0102bd", "license": {"spdx": ["MIT"], "repo": "ShinoXLP/gta-roleplay-discord-bot", "path": "index.js", "repo_head_hexsha": "0e7d1edc80af86f7b75fc203c8ff1b9d528e2bae", "stack_hexsha": "37720bfe293b92ba288e1a3d2eaefc3d1832323e", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of uncaughtException", "issueDescriptionEn": "Using uncaughtException enables a developer to handle errors that could not be addressed by a developer beforehand. However, the official node document specifies that it should only be used as a last resort. This is because uncaughtException cannot guarantee a program will close after an error occurs.\nuncaughtException should be used for logging purposes. After logging the errors, the process needs to be terminated using process.exit();.", "issueLineNumber": 1, "entireCode": "process.on('uncaughtException', function (err) {\n console.log('Caught exception: ', err);\n});\n\nconst Discord = require('discord.js');\n\nconst fs = require('fs');\n\nconst logFunctions = require('./functions/logFunctions.js');\n\nconst config = require('./config.json');\nconst client = new Discord.Client({\n partials: [\"MESSAGE\", \"CHANNEL\", \"REACTION\"]\n});\n\nclient.commands = new Discord.Collection();\n\nconst commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));\nfor (const file of commandFiles) {\n const command = require(`./commands/${file}`);\n\n console.log(file + \" has been successfully loaded!\");\n client.commands.set(command.name, command);\n}\n\nfs.readdir('./events/', (err, files) => {\n if (err) return console.error(err);\n files.forEach(file => {\n const eventFunction = require(`./events/${file}`);\n if (eventFunction.disabled) return;\n\n const event = eventFunction.event || file.split('.')[0];\n const emitter = (typeof eventFunction.emitter === 'string' ? client[eventFunction.emitter] : eventFunction.emitter) || client;\n const once = eventFunction.once;\n\n try {\n emitter[once ? 'once' : 'on'](event, (...args) => eventFunction.run(...args));\n console.log(file + \" successfully loaded!\");\n } catch (error) {\n console.error(error.stack);\n }\n });\n});\n\nclient.on('ready', () => {\n new logFunctions().sendLog(config.oxince.logs.start, \"Bot started!\")\n client.user.setUsername(\"[GTA-Roleplay] System\")\n\n if (config.activity.type !== \"STREAMING\") {\n client.user.setActivity({\n type: config.activity.type,\n name: config.activity.name\n })\n } else {\n client.user.setActivity({\n type: config.activity.type,\n name: config.activity.name,\n url: config.activity.streamURL\n })\n\n }\n})\n\nclient.on('message', message => {\n if (message.author.bot) return;\n\n if (message.channel.id === \"Token\" && !message.content.startsWith(\"!\")) {\n message.channel.send(\"@everyone\", {\n embed: {\n \"title\": \"GTA Roleplay - Informationen\",\n \"description\": message.content,\n\n \"color\": config.embeds.body.color,\n \"author\": {\n \"name\": config.embeds.author.name,\n \"url\": config.embeds.author.url,\n \"icon_url\": config.embeds.author.icon\n },\n \"footer\": {\n \"text\": \"Sent by \" + message.author.tag,\n \"icon_url\": config.embeds.footer.icon\n },\n \"timestamp\": Date.now(),\n \"thumbnail\": {\n \"url\": config.embeds.body.thumbnail\n }\n }\n })\n\n message.delete()\n }\n\n const args = message.content.slice(config.prefix.length).split(/ +/);\n const command = args.shift().toLowerCase();\n\n if (!message.content.startsWith(config.prefix)) return;\n\n if (command === 'ticket') {\n client.commands.get('ticket').execute(message, args, Discord, client);\n sendCommandLog(message.author, message.content);\n }\n\n if (command === 'close') {\n client.commands.get('close').execute(message, args, Discord, client);\n sendCommandLog(message.author, message.content);\n }\n\n if (command === 'delete') {\n client.commands.get('close').execute(message, args, Discord, client);\n sendCommandLog(message.author, message.content);\n }\n\n if (command === 'rename') {\n client.commands.get('rename').execute(message, args, Discord, client);\n sendCommandLog(message.author, message.content);\n }\n\n if (command === 'purge') {\n client.commands.get('purge').execute(message, args, Discord, client);\n sendCommandLog(message.author, message.content);\n }\n\n if (command === 'kick') {\n client.commands.get('kick').execute(message, args, Discord, client);\n sendCommandLog(message.author, message.content);\n }\n\n if (command === 'ban') {\n client.commands.get('ban').execute(message, args, Discord, client);\n sendCommandLog(message.author, message.content);\n }\n\n if (command === 'add') {\n client.commands.get('add').execute(message, args, Discord, client);\n sendCommandLog(message.author, message.content);\n }\n})\n\nfunction sendCommandLog(user, command) {\n new logFunctions().sendLog(config.oxince.logs.commands, \"`\" + user.tag + \"` led the command `\" + command + \"` the end!\")\n}\n\nclient.login(config.token);", "dangerousExampleEn": "1. process.on(\"uncaughtException\", function(err) {\n2. // log necessary error details to log files\n3. //process.exit();\n4. });\nLine 1: uncaughtException was used but the current status of the program is unknown because the process has not been terminated explicitly.", "safeExampleEn": "1. process.on(\"uncaughtException\", function(err) {\n2. // log necessary error details to log files\n3. process.exit();\n4. });\nLine 3: This is secure because the process is terminated after the errors are logged.", "contexts": [{"lineNo": 1, "eventType": "sink", "messageKey": "jschk.UNCAUGHT_EXCEPTION.JS.defect", "params": {}}]}} {"id": "cb9aa3ec72b010070b3c12ac14bf8e458adb873191662109a70d040daacf88dd", "license": {"spdx": ["MIT"], "repo": "joshjung/skyduel", "path": "game-server/app.js", "repo_head_hexsha": "100e5de414ffe8c1d2c645e42cef844c2d83194e", "stack_hexsha": "56adf079feecfa30d4b7b243730b7d5712748584", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of uncaughtException", "issueDescriptionEn": "Using uncaughtException enables a developer to handle errors that could not be addressed by a developer beforehand. However, the official node document specifies that it should only be used as a last resort. This is because uncaughtException cannot guarantee a program will close after an error occurs.\nuncaughtException should be used for logging purposes. After logging the errors, the process needs to be terminated using process.exit();.", "issueLineNumber": 51, "entireCode": "var fs = require('fs'),\n pomelo = require('pomelo'),\n routeUtil = require('./app/util/routeUtil'),\n SkyDuelService = require('./app/services/SkyDuelService'),\n MessagingService = require('./app/services/MessagingService'),\n GitService = require('./GitService'),\n\tHashArray = require('hasharray');\n\nvar app = pomelo.createApp(),\n gitService = new GitService();\n\ngitService.log(10, function (entries) {\n fs.writeFileSync('../shared/gitEntries.json', JSON.stringify(entries));\n});\n\nglobal.isClient = false;\n\napp.set('name', 'skyduel');\n\napp.configure('production|development|staging', 'connector', function() {\n app.set('connectorConfig', {\n connector: pomelo.connectors.hybridconnector,\n heartbeat: 3,\n useDict: true,\n useProtobuf: true\n });\n});\n\napp.configure('production|development|staging', 'gate', function() {\n app.set('connectorConfig', {\n connector: pomelo.connectors.hybridconnector,\n useProtobuf: true\n });\n});\n\napp.configure('production|development|staging', 'skyduel', function() {\n app.set('messagingService', new MessagingService(app));\n app.set('gitService', gitService);\n app.set('skyduelService', new SkyDuelService(app));\n});\n\napp.configure('production|development|staging', function() {\n fs.appendFileSync('../pid', process.pid.toString() + '\\n');\n \n app.route('skyduel', routeUtil.skyduel);\n app.filter(pomelo.timeout());\n});\n\napp.start();\n\nprocess.on('uncaughtException', function(err) {\n console.error(' SkyDuel Caught exception: ' + err.stack);\n});", "dangerousExampleEn": "1. process.on(\"uncaughtException\", function(err) {\n2. // log necessary error details to log files\n3. //process.exit();\n4. });\nLine 1: uncaughtException was used but the current status of the program is unknown because the process has not been terminated explicitly.", "safeExampleEn": "1. process.on(\"uncaughtException\", function(err) {\n2. // log necessary error details to log files\n3. process.exit();\n4. });\nLine 3: This is secure because the process is terminated after the errors are logged.", "contexts": [{"lineNo": 51, "eventType": "sink", "messageKey": "jschk.UNCAUGHT_EXCEPTION.JS.defect", "params": {}}]}} {"id": "5bea92456b08e858c40b4e306154eddc14f32d7dc9ec81e88ef8bbca78a11399", "license": {"spdx": ["MIT"], "repo": "johankj/TallyArbiter", "path": "index.js", "repo_head_hexsha": "810de44e41bc57d8f00cbdba1eef9911d1edb1f0", "stack_hexsha": "1e8e2f7d20a806cdadf09e3f6184fe5f908211d7", "match": "repo_path"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of uncaughtException", "issueDescriptionEn": "Using uncaughtException enables a developer to handle errors that could not be addressed by a developer beforehand. However, the official node document specifies that it should only be used as a last resort. This is because uncaughtException cannot guarantee a program will close after an error occurs.\nuncaughtException should be used for logging purposes. After logging the errors, the process needs to be terminated using process.exit();.", "issueLineNumber": 217, "entireCode": "/* Tally Arbiter */\n\n//Protocol, Network, Socket, Server libraries/variables\nconst net \t\t\t= require('net');\nconst packet \t\t= require('packet');\nconst TSLUMD \t\t= require('tsl-umd'); // TSL UDP package\nconst dgram \t\t= require('dgram');\nconst ATEM \t\t\t= require('atem');\nconst OBS \t\t\t= require('obs-websocket-js');\nconst fs \t\t\t= require('fs');\nconst path \t\t\t= require('path');\nconst {version} \t= require('./package.json');\nconst isPi \t\t\t= require('detect-rpi');\nconst clc \t\t\t= require('cli-color');\nconst util \t\t\t= require ('util');\nconst express \t\t= require('express');\nconst bodyParser \t= require('body-parser');\nconst app \t\t\t= express();\nconst axios \t\t= require('axios');\nconst httpServer \t= require('http').Server(app);\nconst io \t\t\t= require('socket.io')(httpServer);\nconst osc \t\t\t= require('osc');\n\n//Tally Arbiter variables\nconst listenPort \t= 4455;\nconst oscPort \t\t= 5958;\nvar oscUDP\t\t\t= null;\nconst config_file \t= './config.json'; //local storage JSON file\nvar Clients \t\t= []; //array of connected listener clients (web, python, relay, etc.)\nvar Logs \t\t\t= []; //array of actions, information, and errors\nvar OBStallyData \t= []; //array of OBS sources and current tally data\nvar PortsInUse\t\t= []; //array of UDP/TCP ports in use, includes reserved ports\n\nlet portObj = {};\nportObj.port = '9910'; //ATEM\nportObj.sourceId = 'reserved';\nPortsInUse.push(portObj);\n\nportObj = {};\nportObj.port = '8099'; //VMix\nportObj.sourceId = 'reserved';\nPortsInUse.push(portObj);\n\nportObj = {};\nportObj.port = oscPort.toString(); //OSC Broadcast\nportObj.sourceId = 'reserved';\nPortsInUse.push(portObj);\n\nportObj = {};\nportObj.port = listenPort.toString(); //Tally Arbiter\nportObj.sourceId = 'reserved';\nPortsInUse.push(portObj);\n\nvar source_types \t= [ //available tally source types\n\t{ id: '5e0a1d8c', label: 'TSL 3.1 UDP', type: 'tsl_31_udp', enabled: true, help: ''},\n\t{ id: 'dc75100e', label: 'TSL 3.1 TCP', type: 'tsl_31_tcp', enabled: true , help: ''},\n\t{ id: '44b8bc4f', label: 'Blackmagic ATEM', type: 'atem', enabled: true, help: 'Uses Port 9910.' },\n\t{ id: '4eb73542', label: 'OBS Studio', type: 'obs', enabled: true, help: 'The OBS Websocket plugin must be installed on the source.'},\n\t{ id: '58b6af42', label: 'VMix', type: 'vmix', enabled: true, help: 'Uses Port 8099.'},\n\t{ id: '4a58f00f', label: 'Roland Smart Tally', type: 'roland', enabled: true, help: ''},\n\t{ id: '05d6bce1', label: 'Open Sound Control (OSC)', type: 'osc', enabled: true, help: ''},\n\t{ id: 'cf51e3c9', label: 'Incoming Webhook', type: 'webhook', enabled: false, help: ''}\n];\n\nvar source_types_datafields = [ //data fields for the tally source types\n\t{ sourceTypeId: '5e0a1d8c', fields: [ //TSL 3.1 UDP\n\t\t\t{ fieldName: 'port', fieldLabel: 'Port', fieldType: 'port' }\n\t\t]\n\t},\n\t{ sourceTypeId: 'dc75100e', fields: [ //TSL 3.1 TCP\n\t\t\t{ fieldName: 'port', fieldLabel: 'Port', fieldType: 'port' }\n\t\t]\n\t},\n\t{ sourceTypeId: '44b8bc4f', fields: [ //Blackmagic ATEM\n\t\t\t{ fieldName: 'ip', fieldLabel: 'IP Address', fieldType: 'text' }\n\t\t]\n\t},\n\t{ sourceTypeId: '4eb73542', fields: [ // OBS Studio\n\t\t\t{ fieldName: 'ip', fieldLabel: 'IP Address', fieldType: 'text' },\n\t\t\t{ fieldName: 'port', fieldLabel: 'Port', fieldType: 'port' },\n\t\t\t{ fieldName: 'password', fieldLabel: 'Password', fieldType: 'text' }\n\t\t]\n\t},\n\t{ sourceTypeId: '58b6af42', fields: [ // VMix\n\t\t\t{ fieldName: 'ip', fieldLabel: 'IP Address', fieldType: 'text' }\n\t\t]\n\t},\n\t{ sourceTypeId: '4a58f00f', fields: [ // Roland Smart Tally\n\t\t\t{ fieldName: 'ip', fieldLabel: 'IP Address', fieldType: 'text' }\n\t\t]\n\t},\n\t{ sourceTypeId: '05d6bce1', fields: [ // OSC Listener\n\t\t\t{ fieldName: 'port', fieldLabel: 'Port', fieldType: 'port' },\n\t\t\t{ fieldName: 'info', fieldLabel: 'Information', text: 'The device source address should be sent as an integer or a string to the server\\'s IP address on the specified port. Sending to /tally/preview_on designates it as a Preview command, and /tally/program_on designates it as a Program command. To turn off a preview or program, use preview_off and program_off. The first OSC argument received will be used for the device source address.', fieldType: 'info' }\n\t\t]\n\t},\n\t{ sourceTypeId: 'cf51e3c9', fields: [ //Incoming Webhook\n\t\t\t{ fieldName: 'path', fieldLabel: 'Webhook path', fieldType: 'text' }\n\t\t]\n\t}\n];\n\nif (isPi()) {\n\t//adds the GPIO input type option if the software is running on a Raspberry Pi\n\tlet sourceTypeObj = {};\n\tsourceTypeObj.id = 'bc0d5c91';\n\tsourceTypeObj.label = 'Local GPIO';\n\tsourceTypeObj.type = 'gpio';\n\tsourceTypeObj.enabled = false;\n\tsource_types.push(sourceTypeObj);\n\n\tlet sourceTypeDataFieldObj = {};\n\tsourceTypeDataFieldObj.sourceTypeId = sourceTypeObj.id;\n\tlet fields = [\n\t\t{ fieldName: 'pins', fieldLabel: 'GPIO Pins', fieldType: 'text' }\n\t];\n\tsourceTypeDataFieldObj.fields = fields;\n\tsource_types_datafields.push(sourceTypeDataFieldObj);\n}\n\nvar output_types = [ //output actions that Tally Arbiter can perform\n\t{ id: '7dcd66b5', label: 'TSL 3.1 UDP', type: 'tsl_31_udp', enabled: true},\n\t{ id: '276a8dcc', label: 'TSL 3.1 TCP', type: 'tsl_31_tcp', enabled: true },\n\t{ id: 'ffe2b0b6', label: 'Outgoing Webhook', type: 'webhook', enabled: true},\n\t{ id: '6dbb7bf7', label: 'Local Console Output', type: 'console', enabled: true },\n\t{ id: '58da987d', label: 'OSC Message', type: 'osc', enabled: true }\n];\n\nvar output_types_datafields = [ //data fields for the outgoing actions\n\t{ outputTypeId: '7dcd66b5', fields: [ //TSL 3.1 UDP\n\t\t\t{ fieldName: 'ip', fieldLabel: 'IP Address', fieldType: 'text' },\n\t\t\t{ fieldName: 'port', fieldLabel: 'Port', fieldType: 'port' },\n\t\t\t{ fieldName: 'address', fieldLabel: 'Address', fieldType: 'number' },\n\t\t\t{ fieldName: 'label', fieldLabel: 'Label', fieldType: 'text' },\n\t\t\t{ fieldName: 'tally1', fieldLabel: 'Tally 1 (PVW)', fieldType: 'bool' },\n\t\t\t{ fieldName: 'tally2', fieldLabel: 'Tally 2 (PGM)', fieldType: 'bool' },\n\t\t\t{ fieldName: 'tally3', fieldLabel: 'Tally 3', fieldType: 'bool' },\n\t\t\t{ fieldName: 'tally4', fieldLabel: 'Tally 4', fieldType: 'bool' }\n\t\t]\n\t},\n\t{ outputTypeId: '276a8dcc', fields: [ //TSL 3.1 TCP\n\t\t\t{ fieldName: 'ip', fieldLabel: 'IP Address', fieldType: 'text' },\n\t\t\t{ fieldName: 'port', fieldLabel: 'Port', fieldType: 'port' },\n\t\t\t{ fieldName: 'address', fieldLabel: 'Address', fieldType: 'number' },\n\t\t\t{ fieldName: 'label', fieldLabel: 'Label', fieldType: 'text' },\n\t\t\t{ fieldName: 'tally1', fieldLabel: 'Tally 1 (PVW)', fieldType: 'bool' },\n\t\t\t{ fieldName: 'tally2', fieldLabel: 'Tally 2 (PGM)', fieldType: 'bool' },\n\t\t\t{ fieldName: 'tally3', fieldLabel: 'Tally 3', fieldType: 'bool' },\n\t\t\t{ fieldName: 'tally4', fieldLabel: 'Tally 4', fieldType: 'bool' }\n\t\t]\n\t},\n\t{ outputTypeId: 'ffe2b0b6', fields: [ //Outgoing Webhook\n\t\t\t{ fieldName: 'ip', fieldLabel: 'IP Address', fieldType: 'text' },\n\t\t\t{ fieldName: 'port', fieldLabel: 'Port', fieldType: 'port' },\n\t\t\t{ fieldName: 'path', fieldLabel: 'Path', fieldType: 'text' },\n\t\t\t{ fieldName: 'method', fieldLabel: 'Method', fieldType: 'dropdown', options: [ { id: 'GET', label: 'GET' }, { id: 'POST', label: 'POST'} ] },\n\t\t\t{ fieldName: 'postdata', fieldLabel: 'POST Data', fieldType: 'text' }\n\t\t]\n\t},\n\t{ outputTypeId: '6dbb7bf7', fields: [ //Local Console Output\n\t\t\t{ fieldName: 'text', fieldLabel: 'Text', fieldType: 'text'}\n\t\t]\n\t},\n\t{ outputTypeId: '58da987d', fields: [ //OSC\n\t\t\t{ fieldName: 'ip', fieldLabel: 'IP Address', fieldType: 'text' },\n\t\t\t{ fieldName: 'port', fieldLabel: 'Port', fieldType: 'port' },\n\t\t\t{ fieldName: 'path', fieldLabel: 'Path', fieldType: 'text' },\n\t\t\t{ fieldName: 'args', fieldLabel: 'Arguments', fieldType: 'text', help: 'Separate multiple argments with a space. Strings must be encapsulated by double quotes.'}\n\t\t]\n\t}\n];\n\nif (isPi()) {\n\t//adds the GPIO output type option if the software is running on a Raspberry Pi\n\tlet outputTypeObj = {};\n\toutputTypeObj.id = '73815fc2';\n\toutputTypeObj.label = 'Local GPIO';\n\toutputTypeObj.type = 'gpio';\n\toutputTypeObj.enabled = false;\n\toutput_types.push(outputTypeObj);\n\n\tlet outputTypeDataFieldObj = {};\n\toutputTypeDataFieldObj.outputTypeId = outputTypeObj.id;\n\tlet fields = [\n\t\t{ fieldName: 'pins', fieldLabel: 'GPIO Pins', fieldType: 'text' }\n\t];\n\toutputTypeDataFieldObj.fields = fields;\n\toutput_types_datafields.push(outputTypeDataFieldObj);\n}\n\nconst bus_options = [ // the busses available to monitor in Tally Arbiter\n\t{ id: 'e393251c', label: 'Preview', type: 'preview'},\n\t{ id: '334e4eda', label: 'Program', type: 'program'}\n\t/* { id: '12c8d698', label: 'Preview + Program', type: 'previewprogram'}*/\n]\n\nvar sources \t\t\t= []; // the configured tally sources\nvar devices \t\t\t= []; // the configured tally devices\nvar device_sources\t\t= []; // the configured tally device-source mappings\nvar device_actions\t\t= []; // the configured device output actions\nvar device_states\t\t= []; // array of tally data as it has come in and the known state\nvar source_connections\t= []; // array of source connections/servers as they are established\n\nfunction uuidv4() //unique UUID generator for IDs\n{\n\treturn 'xxxxxxxx'.replace(/[xy]/g, function(c) {\n\t\tlet r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);\n\t\treturn v.toString(16);\n\t});\n}\n\nfunction startUp() {\n\tloadConfig();\n\tinitialSetup();\n\tDeleteInactiveClients();\n\n\tprocess.on('uncaughtException', function (err) {\n\t\tlogger(`Caught exception: ${err}`, 'error');\n\t});\n}\n\n//sets up the REST API and GUI pages and starts the Express server that will listen for incoming requests\nfunction initialSetup() {\n\tlogger('Setting up the REST API.', 'info-quiet');\n\n\tapp.use(bodyParser.json({ type: 'application/json' }));\n\n\t//about the author, this program, etc.\n\tapp.get('/', function (req, res) {\n\t\tres.sendFile('views/index.html', { root: __dirname });\n\t});\n\n\t//settings page - add sources, devices, actions, etc.\n\tapp.get('/settings', function (req, res) {\n\t\tres.sendFile('views/settings.html', { root: __dirname });\n\t});\n\n\t//tally page - view tally state of any device\n\tapp.get('/tally', function (req, res) {\n\t\tres.sendFile('views/tally.html', { root: __dirname });\n\t});\n\n\t//producer page - view tally states of all devices\n\tapp.get('/producer', function (req, res) {\n\t\tres.sendFile('views/producer.html', { root: __dirname });\n\t});\n\n\tapp.get('/source_types', function (req, res) {\n\t\t//gets all Tally Source Types\n\t\tres.send(source_types);\n\t});\n\n\tapp.get('/source_types_datafields', function (req, res) {\n\t\t//gets all Tally Source Types Data Fields\n\t\tres.send(source_types_datafields);\n\t});\n\n\tapp.get('/output_types', function (req, res) {\n\t\t//gets all Tally Output Types\n\t\tres.send(output_types);\n\t});\n\n\tapp.get('/output_types_datafields', function (req, res) {\n\t\t//gets all Tally Output Types Data Fields\n\t\tres.send(output_types_datafields);\n\t});\n\n\tapp.get('/bus_options', function (req, res) {\n\t\t//gets all Tally Bus Options\n\t\tres.send(bus_options);\n\t});\n\n\tapp.get('/sources', function (req, res) {\n\t\t//gets all Tally Sources\n\t\tres.send(sources);\n\t});\n\n\tapp.get('/devices', function (req, res) {\n\t\t//gets all Tally Devices\n\t\tres.send(devices);\n\t});\n\n\tapp.get('/device_sources', function (req, res) {\n\t\t//gets all Tally Device Sources\n\t\tres.send(device_sources);\n\t});\n\n\tapp.get('/device_actions', function (req, res) {\n\t\t//gets all Tally Device Actions\n\t\tres.send(device_actions);\n\t});\n\n\tapp.get('/device_states', function (req, res) {\n\t\t//gets all Tally Device States\n\t\tres.send(device_states);\n\t});\n\n\tapp.get('/clients', function (req, res) {\n\t\t//gets all Listener Clients\n\t\tres.send(Clients);\n\t});\n\n\tapp.get('/flash/:clientid', function (req, res) {\n\t\t//sends a flash command to the listener\n\t\tlet clientId = req.params.clientid;\n\t\tlet result = FlashClient(clientId);\n\t\tres.send(result);\n\t});\n\n\tapp.get('/version', function (req, res) {\n\t\t//gets the version of the software\n\t\tres.send(version);\n\t});\n\n\tapp.post('/manage', function (req, res) {\n\t\t//adds the item based on the type defined in the object\n\t\tlet obj = req.body;\n\t\t\n\t\tlet result = TallyArbiter_Manage(obj);\n\t\tres.send(result);\n\t});\n\n\t//serve up any files in the static folder like images, CSS, client-side JS, etc.\n\tapp.use(express.static(path.join(__dirname, 'views/static')));\n\n\t//serve up jQuery from the Node module\n\tapp.use('/js/jquery', express.static(path.join(__dirname, 'node_modules/jquery/dist')));\n\n\tapp.use(function (req, res) {\n\t\tres.status(404).send({error: true, url: req.originalUrl + ' not found.'});\n\t});\n\n\tlogger('REST API Setup Complete.', 'info-quiet');\n\n\tlogger('Starting socket.IO Setup.', 'info-quiet');\n\n\tio.sockets.on('connection', function(socket) {\n\n\t\tsocket.on('version', function() {\n\t\t\tsocket.emit('version', version);\n\t\t});\n\n\t\tsocket.on('devices', function() { // sends the configured Devices to the socket\n\t\t\tsocket.emit('devices', devices);\n\t\t});\n\n\t\tsocket.on('bus_options', function() { // sends the Bus Options (preview, program) to the socket\n\t\t\tsocket.emit('bus_options', bus_options);\n\t\t});\n\n\t\tsocket.on('device_listen', function(deviceId, listenerType) { // emitted by a socket (tally page) that has selected a Device to listen for state information\n\t\t\tlet device = GetDeviceByDeviceId(deviceId);\n\t\t\tif ((deviceId === 'null') || (!device)) {\n\t\t\t\tdeviceId = devices[0].id;\n\t\t\t}\n\n\t\t\tsocket.join('device-' + deviceId);\n\t\t\tlet deviceName = GetDeviceByDeviceId(deviceId).name;\n\t\t\tlogger(`Listener Client Connected. Type: ${listenerType} Device: ${deviceName}`, 'info');\n\t\t\t\n\t\t\tlet ipAddress = socket.request.connection.remoteAddress;\n\t\t\tlet datetimeConnected = new Date().getTime();\n\t\t\t\n\t\t\tlet clientId = AddClient(socket.id, deviceId, listenerType, ipAddress, datetimeConnected);\n\t\t\tsocket.emit('device_states', GetDeviceStatesByDeviceId(deviceId));\n\t\t});\n\n\t\tsocket.on('device_listen_blink', function(obj) { // emitted by the Python blink(1) client that has selected a Device to listen for state information\n\t\t\tlet deviceId = obj.deviceId;\n\t\t\tlet device = GetDeviceByDeviceId(deviceId);\n\t\t\tif ((deviceId === 'null') || (!device)) {\n\t\t\t\tdeviceId = devices[0].id;\n\t\t\t}\n\n\t\t\tlet listenerType = 'blink(1)';\n\n\t\t\tsocket.join('device-' + deviceId);\n\t\t\tlet deviceName = GetDeviceByDeviceId(deviceId).name;\n\t\t\tlogger(`Listener Client Connected. Type: ${listenerType} Device: ${deviceName}`, 'info');\n\t\t\t\n\t\t\tlet ipAddress = socket.request.connection.remoteAddress;\n\t\t\tlet datetimeConnected = new Date().getTime();\n\t\t\t\n\t\t\tlet clientId = AddClient(socket.id, deviceId, listenerType, ipAddress, datetimeConnected);\n\t\t\tsocket.emit('device_states', GetDeviceStatesByDeviceId(deviceId));\n\t\t});\n\n\t\tsocket.on('device_listen_relay', function(relayGroupId, deviceId) { // emitted by the Relay Controller accessory program that has selected a Device to listen for state information\n\t\t\tlet device = GetDeviceByDeviceId(deviceId);\n\t\t\tif (!device) {\n\t\t\t\tdeviceId = devices[0].id;\n\t\t\t}\n\n\t\t\tlet listenerType = 'relay';\n\n\t\t\tsocket.join('device-' + deviceId);\n\t\t\tlet deviceName = GetDeviceByDeviceId(deviceId).name;\n\t\t\tlogger(`Listener Client Connected. Type: ${listenerType} Device: ${deviceName}`, 'info');\n\t\t\t\n\t\t\tlet ipAddress = socket.request.connection.remoteAddress;\n\t\t\tlet datetimeConnected = new Date().getTime();\n\t\t\t\n\t\t\tlet clientId = AddClient(socket.id, deviceId, listenerType, ipAddress, datetimeConnected);\n\t\t\t//add relayGroupId to client\n\t\t\tfor (let i = 0; i < Clients.length; i++) {\n\t\t\t\tif (Clients[i].id === clientId) {\n\t\t\t\t\tClients[i].relayGroupId = relayGroupId;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tsocket.emit('listener_relay_assignment', relayGroupId, deviceId);\n\t\t});\n\n\t\tsocket.on('device_listen_gpio', function(obj) { // emitted by the Python GPIO client that has selected a Device to listen for state information\n\t\t\tlet deviceId = obj.deviceId;\n\t\t\tlet device = GetDeviceByDeviceId(deviceId);\n\t\t\tif ((deviceId === 'null') || (!device)) {\n\t\t\t\tdeviceId = devices[0].id;\n\t\t\t}\n\n\t\t\tlet listenerType = 'gpio';\n\n\t\t\tsocket.join('device-' + deviceId);\n\t\t\tlet deviceName = GetDeviceByDeviceId(deviceId).name;\n\t\t\tlogger(`Listener Client Connected. Type: ${listenerType} Device: ${deviceName}`, 'info');\n\t\t\t\n\t\t\tlet ipAddress = socket.request.connection.remoteAddress;\n\t\t\tlet datetimeConnected = new Date().getTime();\n\t\t\t\n\t\t\tlet clientId = AddClient(socket.id, deviceId, listenerType, ipAddress, datetimeConnected);\n\t\t\tsocket.emit('device_states', GetDeviceStatesByDeviceId(deviceId));\n\t\t});\n\n\t\tsocket.on('device_states', function(deviceId) {\n\t\t\tsocket.emit('device_states', GetDeviceStatesByDeviceId(deviceId));\n\t\t});\n\n\t\tsocket.on('settings', function () {\n\t\t\tsocket.join('settings');\n\t\t\tsocket.emit('clients', Clients);\n\t\t\tsocket.emit('logs', Logs);\n\t\t\tsocket.emit('PortsInUse', PortsInUse);\n\t\t});\n\n\t\tsocket.on('producer', function () {\n\t\t\tsocket.join('producer');\n\t\t\tsocket.emit('clients', Clients);\n\t\t\tsocket.emit('devices', devices);\n\t\t\tsocket.emit('bus_options', bus_options);\n\t\t});\n\n\t\tsocket.on('flash', function(clientId) {\n\t\t\tfor (let i = 0; i < Clients.length; i++) {\n\t\t\t\tif (Clients[i].id === clientId) {\n\t\t\t\t\tif (Clients[i].relayGroupId) {\n\t\t\t\t\t\tio.to(Clients[i].socketId).emit('flash', Clients[i].relayGroupId);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tio.to(Clients[i].socketId).emit('flash');\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\tsocket.on('reassign', function(clientId, oldDeviceId, deviceId) {\n\t\t\tfor (let i = 0; i < Clients.length; i++) {\n\t\t\t\tif (Clients[i].id === clientId) {\n\t\t\t\t\tif (Clients[i].relayGroupId) {\n\t\t\t\t\t\tio.to(Clients[i].socketId).emit('reassign', Clients[i].relayGroupId, oldDeviceId, deviceId);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tio.to(Clients[i].socketId).emit('reassign', oldDeviceId, deviceId);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\tsocket.on('listener_reassign', function(oldDeviceId, deviceId) {\n\t\t\tsocket.leave('device-' + oldDeviceId);\n\t\t\tsocket.join('device-' + deviceId);\n\n\t\t\tfor (let i = 0; i < Clients.length; i++) {\n\t\t\t\tif (Clients[i].socketId === socket.id) {\n\t\t\t\t\tClients[i].deviceId = deviceId;\n\t\t\t\t\tClients[i].inactive = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlet oldDeviceName = GetDeviceByDeviceId(oldDeviceId).name;\n\t\t\tlet deviceName = GetDeviceByDeviceId(deviceId).name;\n\n\t\t\tlogger(`Listener Client reassigned from ${oldDeviceName} to ${deviceName}`, 'info');\n\t\t\tio.to('settings').emit('clients', Clients);\n\t\t\tsocket.emit('device_states', GetDeviceStatesByDeviceId(deviceId));\n\t\t});\n\n\t\tsocket.on('listener_reassign_relay', function(relayGroupId, oldDeviceId, deviceId) {\n\t\t\tlet canRemove = true;\n\t\t\tfor (let i = 0; i < Clients.length; i++) {\n\t\t\t\tif (Clients[i].socketId === socket.id) {\n\t\t\t\t\tif (Clients[i].deviceId === oldDeviceId) {\n\t\t\t\t\t\tif (Clients[i].relayGroupId !== relayGroupId) {\n\t\t\t\t\t\t\tcanRemove = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (canRemove) {\n\t\t\t\t//no other relay groups on this socket are using the old device ID, so we can safely leave that room\n\t\t\t\tsocket.leave('device-' + oldDeviceId);\n\t\t\t}\n\t\t\t\n\t\t\tsocket.join('device-' + deviceId);\n\n\t\t\tfor (let i = 0; i < Clients.length; i++) {\n\t\t\t\tif (Clients[i].relayGroupId === relayGroupId) {\n\t\t\t\t\tClients[i].deviceId = deviceId;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlet oldDeviceName = GetDeviceByDeviceId(oldDeviceId).name;\n\t\t\tlet deviceName = GetDeviceByDeviceId(deviceId).name;\n\n\t\t\tlogger(`Listener Client reassigned from ${oldDeviceName} to ${deviceName}`, 'info');\n\t\t\tio.to('settings').emit('clients', Clients);\n\t\t});\n\n\t\tsocket.on('listener_delete', function(clientId) { // emitted by the Settings page when an inactive client is being removed manually\n\t\t\tfor (let i = Clients.length - 1; i >= 0; i--) {\n\t\t\t\tif (Clients[i].id === clientId) {\n\t\t\t\t\tlogger(`Inactive Client removed: ${Clients[i].id}`, 'info');\n\t\t\t\t\tClients.splice(i, 1);\n\t\t\t\t}\n\t\t\t}\n\t\t\tio.to('settings').emit('clients', Clients);\n\t\t});\n\n\t\tsocket.on('disconnect', function() { // emitted when any listener client disconnects from the server\n\t\t\tDeactivateClient(socket.id);\n\t\t});\n\t});\n\n\tlogger('Socket.IO Setup Complete.', 'info-quiet');\n\n\tlogger('Starting OSC Setup.', 'info-quiet');\n\n\toscUDP = new osc.UDPPort({\n\t\tlocalAddress: '0.0.0.0',\n\t\tlocalPort: oscPort,\n\t\tbroadcast: true,\n\t\tmetadata: true\n\t});\n\n\toscUDP.on('error', function (error) {\n\t\tlogger(`An OSC error occurred: ${error.message}`, 'info-quiet');\n\t});\n\n\toscUDP.open();\n\n\toscUDP.on('ready', function () {\n\t\tlogger(`OSC Sending Port Ready. Broadcasting on Port: ${oscPort}`, 'info-quiet');\n\t});\n\n\tlogger('Starting HTTP Server.', 'info-quiet');\n\t\n\thttpServer.listen(listenPort, function () { // start up http server\n\t\tlogger(`Tally Arbiter running on port ${listenPort}`, 'info');\n\t});\n}\n\nfunction logger(log, type) { //logs the item to the console, to the log array, and sends the log item to the settings page\n\n\tlet dtNow = new Date();\n\n\tswitch(type) {\n\t\tcase 'info':\n\t\tcase 'info-quiet':\n\t\t\tconsole.log(clc.black(`[${dtNow}]`) + ' ' + clc.blue(log));\n\t\t\tbreak;\n\t\tcase 'error':\n\t\t\tconsole.log(clc.black(`[${dtNow}]`) + ' ' + clc.red.bold(log));\n\t\t\tbreak;\n\t\tcase 'console_action':\n\t\t\tconsole.log(clc.black(`[${dtNow}]`) + ' ' + clc.green(log.text));\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tconsole.log(clc.black(`[${dtNow}]`) + ' ' + util.inspect(log, {depth: null}));\n\t\t\tbreak;\n\t}\n\t\n\tif (type.indexOf('quiet') === -1) {\n\t\tlet logObj = {};\n\t\tlogObj.datetime = dtNow;\n\t\tlogObj.log = log;\n\t\tlogObj.type = type;\n\t\tLogs.push(logObj);\n\n\t\tio.to('settings').emit('log_item', logObj);\n\t}\n}\n\nfunction loadConfig() { // loads the JSON data from the config file to memory\n\tlogger('Loading the stored Tally Arbiter configuration file.', 'info-quiet');\n\n\ttry {\n\t\tlet rawdata = fs.readFileSync(config_file);\n\t\tlet configJson = JSON.parse(rawdata); \n\n\t\tif (configJson.sources) {\n\t\t\tfor (let i = 0; i < configJson.sources.length; i++) {\n\t\t\t\tconfigJson.sources[i].connected = false;\n\t\t\t}\n\t\t\tsources = configJson.sources;\n\t\t\tlogger('Tally Arbiter Sources loaded.', 'info');\n\t\t\tlogger(`${sources.length} Sources configured.`, 'info');\n\t\t}\n\t\telse {\n\t\t\tsources = [];\n\t\t\tlogger('Tally Arbiter Sources could not be loaded.', 'error');\n\t\t}\n\t\t\n\t\tif (configJson.devices) {\n\t\t\tdevices = configJson.devices;\n\t\t\tlogger('Tally Arbiter Devices loaded.', 'info');\n\t\t\tlogger(`${devices.length} Devices configured.`, 'info');\n\t\t}\n\t\telse {\n\t\t\tdevices = [];\n\t\t\tlogger('Tally Arbiter Devices could not be loaded.', 'error');\n\t\t}\n\t\t\n\t\tif (configJson.device_sources) {\n\t\t\tdevice_sources = configJson.device_sources;\n\t\t\tlogger('Tally Arbiter Device Sources loaded.', 'info');\n\t\t}\n\t\telse {\n\t\t\tdevice_sources = [];\n\t\t\tlogger('Tally Arbiter Device Sources could not be loaded.', 'error');\n\t\t}\n\n\t\tif (configJson.device_actions) {\n\t\t\tdevice_actions = configJson.device_actions;\n\t\t\tlogger('Tally Arbiter Device Actions loaded.', 'info');\n\t\t}\n\t\telse {\n\t\t\tdevice_actions = [];\n\t\t\tlogger('Tally Arbiter Device Actions could not be loaded.', 'error');\n\t\t}\n\t}\n\tcatch (error) {\n\t\tif (error.code === 'ENOENT') {\n\t\t\tlogger('The config file could not be found.', 'error');\n\t\t}\n\t\telse {\n\t\t\tlogger('An error occurred while loading the configuration file:', 'error');\n\t\t\tlogger(error, 'error');\n\t\t}\n\t}\n\n\tfor (let i = 0; i < sources.length; i++) {\n\t\tif (sources[i].enabled) {\n\t\t\tlet sourceType = source_types.find( ({ id }) => id === sources[i].sourceTypeId);\n\n\t\t\tlogger(`Initiating Setup for Source: ${sources[i].name}. Type: ${sourceType.label}`, 'info-quiet');\n\t\t\t\n\t\t\tswitch(sourceType.type) {\n\t\t\t\tcase 'tsl_31_udp':\n\t\t\t\t\tSetUpTSLServer_UDP(sources[i].id);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'tsl_31_tcp':\n\t\t\t\t\tSetUpTSLServer_TCP(sources[i].id);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'atem':\n\t\t\t\t\tSetUpATEMServer(sources[i].id);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'obs':\n\t\t\t\t\tSetUpOBSServer(sources[i].id);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'vmix':\n\t\t\t\t\tSetUpVMixServer(sources[i].id);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'roland':\n\t\t\t\t\tSetUpRolandSmartTally(sources[i].id);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'osc':\n\t\t\t\t\tSetUpOSCServer(sources[i].id);\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tlogger(`Error initiating connection for Source: ${sources[i].name}. The specified Source Type is not implemented at this time: ${sourceType.type}`, 'error');\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tlogger('Source Setup Complete.', 'info-quiet');\n\n\tinitializeDeviceStates();\n}\n\nfunction initializeDeviceStates() { // initializes each device state in the array upon server startup\n\tlogger('Initializing Device States.', 'info-quiet');\n\n\tlet busId_preview = null;\n\tlet busId_program = null;\n\t//let busId_previewprogram = null;\n\n\tfor (let i = 0; i < bus_options.length; i++) {\n\t\tswitch(bus_options[i].type) {\n\t\t\tcase 'preview':\n\t\t\t\tbusId_preview = bus_options[i].id;\n\t\t\t\tbreak;\n\t\t\tcase 'program':\n\t\t\t\tbusId_program = bus_options[i].id;\n\t\t\t\tbreak;\n\t\t\t/*case 'previewprogram':\n\t\t\t\tbusId_previewprogram = bus_options[i].id;\n\t\t\t\tbreak;*/\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tfor (let i = 0; i < devices.length; i++) {\n\t\tlet deviceStateObj_preview = {};\n\t\tdeviceStateObj_preview.deviceId = devices[i].id;\n\t\tdeviceStateObj_preview.busId = busId_preview;\n\t\tdeviceStateObj_preview.sources = [];\n\t\tdevice_states.push(deviceStateObj_preview);\n\n\t\tlet deviceStateObj_program = {};\n\t\tdeviceStateObj_program.deviceId = devices[i].id;\n\t\tdeviceStateObj_program.busId = busId_program;\n\t\tdeviceStateObj_program.sources = [];\n\t\tdevice_states.push(deviceStateObj_program);\n\n\t\t/*let deviceStateObj_previewprogram = {};\n\t\tdeviceStateObj_previewprogram.deviceId = devices[i].id;\n\t\tdeviceStateObj_previewprogram.busId = busId_previewprogram;\n\t\tdeviceStateObj_previewprogram.sources = [];\n\t\tdevice_states.push(deviceStateObj_previewprogram);*/\n\t}\n\n\tlogger('Device States Initialized.', 'info-quiet');\n}\n\nfunction SetUpTSLServer_UDP(sourceId)\n{\n\tlet source = sources.find( ({ id }) => id === sourceId);\n\tlet port = source.data.port;\n\n\ttry\n\t{\n\t\tlet sourceConnectionObj = {};\n\t\tsourceConnectionObj.sourceId = sourceId;\n\t\tsourceConnectionObj.server = null;\n\t\tsource_connections.push(sourceConnectionObj);\n\n\t\tfor (let i = 0; i < source_connections.length; i++) {\n\t\t\tif (source_connections[i].sourceId === sourceId) {\n\t\t\t\tAddPort(port, sourceId);\n\t\t\t\tlogger(`Source: ${source.name} Creating TSL UDP Connection.`, 'info-quiet');\n\t\t\t\tsource_connections[i].server = new TSLUMD(port);\n\n\t\t\t\tsource_connections[i].server.on('message', function (tally) {\n\t\t\t\t\tprocessTSLTally(sourceId, tally);\n\t\t\t\t});\n\t\t\n\t\t\t\tlogger(`Source: ${source.name} TSL 3.1 Server started. Listening for data on UDP Port: ${port}`, 'info');\n\t\t\t\tfor (let j = 0; j < sources.length; j++) {\n\t\t\t\t\tif (sources[j].id === sourceId) {\n\t\t\t\t\t\tsources[j].connected = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t} catch (error)\n\t{\n\t\tlogger(`Source: ${source.name} TSL 3.1 UDP Server Error occurred: ${error}`, 'error');\n\t}\n}\n\nfunction StopTSLServer_UDP(sourceId) {\n\tlet source = sources.find( ({ id }) => id === sourceId);\n\n\ttry\n\t{\n\t\tfor (let i = 0; i < source_connections.length; i++) {\n\t\t\tif (source_connections[i].sourceId === sourceId) {\n\t\t\t\tlogger(`Source: ${source.name} Closing TSL UDP Connection.`, 'info-quiet');\n\t\t\t\tsource_connections[i].server.server.close();\n\t\t\t\tDeletePort(source.data.port);\n\t\t\t\tlogger(`Source: ${source.name} TSL 3.1 UDP Server Stopped. Connection Closed.`, 'info');\n\t\t\t\tfor (let j = 0; j < sources.length; j++) {\n\t\t\t\t\tif (sources[j].id === sourceId) {\n\t\t\t\t\t\tsources[j].connected = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tio.to('settings').emit('sources', sources);\n\t}\n\tcatch (error) {\n\t\tlogger(`Source: ${source.name} TSL 3.1 UDP Server Error occurred: ${error}`, 'error');\n\t}\n}\n\nfunction SetUpTSLServer_TCP(sourceId)\n{\n\tlet source = sources.find( ({ id }) => id === sourceId);\n\tlet port = source.data.port;\n\n\ttry\n\t{\n\t\tlet parser = packet.createParser();\n\t\tparser.packet('tsl', 'b8{x1, b7 => address},b8{x2, b2 => brightness, b1 => tally4, b1 => tally3, b1 => tally2, b1 => tally1 }, b8[16] => label');\n\n\t\tlet sourceConnectionObj = {};\n\t\tsourceConnectionObj.sourceId = sourceId;\n\t\tsourceConnectionObj.server = null;\n\t\tsource_connections.push(sourceConnectionObj);\n\n\t\tfor (let i = 0; i < source_connections.length; i++) {\n\t\t\tif (source_connections[i].sourceId === sourceId) {\n\t\t\t\tAddPort(port, sourceId);\n\t\t\t\tlogger(`Source: ${source.name} Creating TSL TCP Connection.`, 'info-quiet');\n\t\t\t\tsource_connections[i].server = net.createServer(function (socket) {\n\t\t\t\t\t// Handle incoming messages\n\t\t\t\t\tsocket.on('data', function (data) {\n\t\t\t\t\t\tparser.extract('tsl', function (result) {\n\t\t\t\t\t\t\tresult.label = new Buffer(result.label).toString();\n\t\t\t\t\t\t\tprocessTSLTally(sourceId, result);\n\t\t\t\t\t\t});\n\t\t\t\t\t\tparser.parse(data);\n\t\t\t\t\t});\n\n\t\t\t\t\tsocket.on('close', function () {\n\t\t\t\t\t\tlogger(`Source: ${source.name} TSL 3.1 Server connection closed.`, 'info');\n\t\t\t\t\t});\n\n\t\t\t\t}).listen(port);\n\n\t\t\t\tlogger(`Source: ${source.name} TSL 3.1 Server started. Listening for data on TCP Port: ${port}`, 'info');\n\t\t\t\tfor (let j = 0; j < sources.length; j++) {\n\t\t\t\t\tif (sources[j].id === sourceId) {\n\t\t\t\t\t\tsources[j].connected = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tcatch (error) {\n\t\tlogger(`Source: ${source.name} TSL 3.1 TCP Server Error occurred: ${error}`, 'error');\n\t}\n}\n\nfunction StopTSLServer_TCP(sourceId) {\n\tlet source = sources.find( ({ id }) => id === sourceId);\n\n\ttry\n\t{\t\n\t\tfor (let i = 0; i < source_connections.length; i++) {\n\t\t\tif (source_connections[i].sourceId === sourceId) {\n\t\t\t\tsource_connections[i].server.close(function() {});\n\t\t\t\tDeletePort(source.data.port);\n\t\t\t\tlogger(`Source: ${source.name} TSL 3.1 TCP Server Stopped.`, 'info');\n\t\t\t\tfor (let j = 0; j < sources.length; j++) {\n\t\t\t\t\tif (sources[j].id === sourceId) {\n\t\t\t\t\t\tsources[j].connected = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tio.to('settings').emit('sources', sources);\n\t}\n\tcatch (error) {\n\t\tlogger(`Source: ${source.name} TSL 3.1 UDP Server Error occurred: ${error}`, 'error');\n\t}\n}\n\nfunction SetUpATEMServer(sourceId) {\n\tlet source = sources.find( ({ id }) => id === sourceId);\n\n\ttry {\n\t\tlet atemIP = source.data.ip;\n\n\t\tlet sourceConnectionObj = {};\n\t\tsourceConnectionObj.sourceId = sourceId;\n\t\tsourceConnectionObj.server = null;\n\t\tsource_connections.push(sourceConnectionObj);\n\n\t\tfor (let i = 0; i < source_connections.length; i++) {\n\t\t\tif (source_connections[i].sourceId === sourceId) {\n\t\t\t\ttry {\n\t\t\t\t\tlogger(`Source: ${source.name} Creating ATEM Connection.`, 'info-quiet');\n\t\t\t\t\tsource_connections[i].server = new ATEM();\n\t\t\t\t\tsource_connections[i].server.ip = atemIP;\n\t\t\t\t\tsource_connections[i].server.connect();\n\n\t\t\t\t\tsource_connections[i].server.on('connectionStateChange', function (state) {\n\t\t\t\t\t\tswitch (state.toString())\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcase 'closed':\n\t\t\t\t\t\t\t\tfor (let j = 0; j < sources.length; j++) {\n\t\t\t\t\t\t\t\t\tif (sources[j].id === sourceId) {\n\t\t\t\t\t\t\t\t\t\tsources[j].connected = false;\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tlogger(`Source: ${source.name} ATEM connection closed.`, 'info');\n\t\t\t\t\t\t\t\tio.to('settings').emit('sources', sources);\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase 'attempting':\n\t\t\t\t\t\t\t\tlogger(`Source: ${source.name} Initiating connection to ATEM: ${source.data.ip}`, 'info');\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase 'establishing':\n\t\t\t\t\t\t\t\tlogger(`Source: ${source.name} Establishing ATEM connection.`, 'info-quiet');\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase 'open':\n\t\t\t\t\t\t\t\tfor (let j = 0; j < sources.length; j++) {\n\t\t\t\t\t\t\t\t\tif (sources[j].id === sourceId) {\n\t\t\t\t\t\t\t\t\t\tsources[j].connected = true;\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tlogger(`Source: ${source.name} ATEM connection opened.`, 'info');\n\t\t\t\t\t\t\t\tio.to('settings').emit('sources', sources);\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\n\t\t\t\t\tsource_connections[i].server.on('connectionLost', function () {\n\t\t\t\t\t\tfor (let j = 0; j < sources.length; j++) {\n\t\t\t\t\t\t\tif (sources[j].id === sourceId) {\n\t\t\t\t\t\t\t\tsources[j].connected = false;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tlogger(`Source: ${source.name} Connection to ATEM lost.`, 'info-quiet');\n\n\t\t\t\t\t\tio.to('settings').emit('sources', sources);\n\t\t\t\t\t});\n\n\t\t\t\t\tsource_connections[i].server.on('sourceConfiguration', function (id, config, info) {\n\t\t\t\t\t\t\n\t\t\t\t\t});\n\n\t\t\t\t\tsource_connections[i].server.on('sourceTally', function (sourceNumber, tallyState) {\n\t\t\t\t\t\tlogger(`Source: ${source.name} ATEM Source Tally Data received.`, 'info-quiet');\n\t\t\t\t\t\t//build an object like the TSL module creates so we can use the same function to process it\n\t\t\t\t\t\tlet tallyObj = {};\n\t\t\t\t\t\ttallyObj.address = sourceNumber;\n\t\t\t\t\t\ttallyObj.brightness = 1;\n\t\t\t\t\t\ttallyObj.tally1 = (tallyState.preview ? 1 : 0);\n\t\t\t\t\t\ttallyObj.tally2 = (tallyState.program ? 1 : 0);\n\t\t\t\t\t\ttallyObj.tally3 = 0;\n\t\t\t\t\t\ttallyObj.tally4 = 0;\n\t\t\t\t\t\ttallyObj.label = `Source ${sourceNumber}`;\n\t\t\t\t\t\tprocessTSLTally(sourceId, tallyObj);\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tcatch(error) {\n\t\t\t\t\tlogger(`ATEM Error: ${error}`, 'error');\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tcatch (error) {\n\n\t}\n}\n\nfunction StopATEMServer(sourceId) {\n\tlet source = GetSourceBySourceId(sourceId);\n\n\tfor (let i = 0; i < source_connections.length; i++) {\n\t\tif (source_connections[i].sourceId === sourceId) {\n\t\t\tsource_connections[i].server.disconnect(null);\n\t\t\tlogger(`Source: ${source.name} ATEM connection closed.`, 'info');\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\nfunction SetUpOBSServer(sourceId) {\n\tlet source = sources.find( ({ id }) => id === sourceId);\n\n\ttry\n\t{\n\t\tlet ip = source.data.ip;\n\t\tlet port = source.data.port;\n\t\tlet password = .data.password;\n\t\n\t\tlet sourceConnectionObj = {};\n\t\tsourceConnectionObj.sourceId = sourceId;\n\t\tsourceConnectionObj.server = null;\n\t\tsource_connections.push(sourceConnectionObj);\n\n\t\tfor (let i = 0; i < source_connections.length; i++) {\n\t\t\tif (source_connections[i].sourceId === sourceId) {\n\t\t\t\ttry {\n\t\t\t\t\tAddPort(port, sourceId);\n\t\t\t\t\tlogger(`Source: ${source.name} Creating OBS Websocket connection.`, 'info-quiet');\n\t\t\t\t\tsource_connections[i].server = new OBS();\n\t\t\t\t\tsource_connections[i].server.ip = ip;\n\t\t\t\t\tsource_connections[i].server.connect({address: ip + ':' + port, password: password}, function (data) {\n\t\t\t\t\t\tlogger(`Source: ${source.name} Connected to OBS @ ${ip}:${port}`, 'info');\n\t\t\t\t\t});\n\n\t\t\t\t\tsource_connections[i].server.on('error', err => {\n\t\t\t\t\t\tlogger(`Source: ${source.name} OBS websocket error: ${err}`, 'error');\n\t\t\t\t\t});\n\n\t\t\t\t\tsource_connections[i].server.on('ConnectionOpened', function (data) {\n\t\t\t\t\t\tlogger(`Source: ${source.name} OBS Connection opened.`, 'info');\n\t\t\t\t\t\tfor (let j = 0; j < sources.length; j++) {\n\t\t\t\t\t\t\tif (sources[j].id === sourceId) {\n\t\t\t\t\t\t\t\tsources[j].connected = true;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tio.to('settings').emit('sources', sources);\n\t\t\t\t\t});\n\n\t\t\t\t\tsource_connections[i].server.on('ConnectionClosed', function (data) {\n\t\t\t\t\t\tlogger(`Source: ${source.name} OBS Connection closed.`, 'info');\n\t\t\t\t\t\tfor (let j = 0; j < sources.length; j++) {\n\t\t\t\t\t\t\tif (sources[j].id === sourceId) {\n\t\t\t\t\t\t\t\tsources[j].connected = false;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tDeletePort(source.data.port);\n\t\t\t\t\t\tio.to('settings').emit('sources', sources);\n\t\t\t\t\t});\n\n\t\t\t\t\tsource_connections[i].server.on('AuthenticationSuccess', function (data) {\n\t\t\t\t\t\tlogger(`Source: ${source.name} OBS Authenticated.`, 'info');\n\t\t\t\t\t});\n\n\t\t\t\t\tsource_connections[i].server.on('AuthenticationFailure', function (data) {\n\t\t\t\t\t\tlogger(`Source: ${source.name} Invalid OBS Password.`, 'info');\n\t\t\t\t\t});\n\n\t\t\t\t\tsource_connections[i].server.on('PreviewSceneChanged', function (data) {\n\t\t\t\t\t\tlogger(`Source: ${source.name} Preview Scene Changed.`, 'info-quiet');\n\t\t\t\t\t\tif (data)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (data.sources)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tprocessOBSTally(sourceId, data.sources, 'preview');\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\n\t\t\t\t\tsource_connections[i].server.on('SwitchScenes', function (data) {\n\t\t\t\t\t\tlogger(`Source: ${source.name} Program Scene Changed.`, 'info-quiet');\n\t\t\t\t\t\tif (data)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (data.sources)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tprocessOBSTally(sourceId, data.sources, 'program');\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tcatch(error) {\n\t\t\t\t\tlogger(`Source: ${source.name} OBS Error: ${error}`, 'error');\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tcatch (error) {\n\t\tlogger(`Source: ${source.name} OBS Error: ${error}`, 'error');\n\t}\n}\n\nfunction processOBSTally(sourceId, sourceArray, tallyType) {\n\tconsole.log(sourceArray);\n\n\tfor (let i = 0; i < sourceArray.length; i++) {\n\t\tlet obsSourceFound = false;\n\t\tfor (let j = 0; j < OBStallyData.length; j++) {\n\t\t\tif (OBStallyData[j].address === sourceArray[i].name) {\n\t\t\t\tobsSourceFound = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (!obsSourceFound) {\n\t\t\t//the source is not in the OBS array, we don't know anything about it, so add it to the array\n\t\t\tlet obsTallyObj = {};\n\t\t\tobsTallyObj.label = sourceArray[i].name;\n\t\t\tobsTallyObj.address = sourceArray[i].name;\n\t\t\tobsTallyObj.tally4 = 0;\n\t\t\tobsTallyObj.tally3 = 0;\n\t\t\tobsTallyObj.tally2 = 0; // PGM\n\t\t\tobsTallyObj.tally1 = 0; // PVW\n\t\t\tOBStallyData.push(obsTallyObj);\n\t\t}\n\t}\n\n\tfor (let i = 0; i < OBStallyData.length; i++) {\n\t\tlet obsSourceFound = false;\n\t\tfor (let j = 0; j < sourceArray.length; j++) {\n\t\t\tif (OBStallyData[i].address === sourceArray[j].name) {\n\t\t\t\tobsSourceFound = true;\n\t\t\t\t//update the tally state because OBS is saying this source is not in the current scene\n\t\t\t\tswitch(tallyType) {\n\t\t\t\t\tcase 'preview':\n\t\t\t\t\t\tOBStallyData[i].tally1 = ((sourceArray[j].render) ? 1 : 0);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'program':\n\t\t\t\t\t\tOBStallyData[i].tally2 = ((sourceArray[j].render) ? 1 : 0);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tprocessTSLTally(sourceId, OBStallyData[i]);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (!obsSourceFound) {\n\t\t\t//it is no longer in the bus, mark it as such\n\t\t\tswitch(tallyType) {\n\t\t\t\tcase 'preview':\n\t\t\t\t\tOBStallyData[i].tally1 = 0;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'program':\n\t\t\t\t\tOBStallyData[i].tally2 = 0;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tprocessTSLTally(sourceId, OBStallyData[i]);\n\t\t}\n\t}\n\n\tconsole.log(\"OBStallyData\");\n\tconsole.log(OBStallyData);\n}\n\nfunction StopOBSServer(sourceId) {\n\tlet source = GetSourceBySourceId(sourceId);\n\t\n\tfor (let i = 0; i < source_connections.length; i++) {\n\t\tif (source_connections[i].sourceId === sourceId) {\n\t\t\tlogger(`Source: ${source.name} Closing OBS connection.`, 'info-quiet');\n\t\t\tsource_connections[i].server.disconnect();\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\nfunction SetUpVMixServer(sourceId) {\n\tlet source = sources.find( ({ id }) => id === sourceId);\n\tlet ip = source.data.ip;\n\tlet port = 8099;\n\n\ttry\n\t{\n\t\tlet sourceConnectionObj = {};\n\t\tsourceConnectionObj.sourceId = sourceId;\n\t\tsourceConnectionObj.server = null;\n\t\tsource_connections.push(sourceConnectionObj);\n\n\t\tfor (let i = 0; i < source_connections.length; i++) {\n\t\t\tif (source_connections[i].sourceId === sourceId) {\n\t\t\t\tlogger(`Source: ${source.name} Creating VMix connection.`, 'info-quiet');\n\t\t\t\tsource_connections[i].server = new net.Socket();\n\t\t\t\tsource_connections[i].server.connect(port, ip, function() {\n\t\t\t\t\tlogger(`Source: ${source.name} VMix Connection Opened.`, 'info');\n\t\t\t\t\tsource_connections[i].server.write('SUBSCRIBE TALLY\\r\\n');\n\t\t\t\t\tfor (let j = 0; j < sources.length; j++) {\n\t\t\t\t\t\tif (sources[j].id === sourceId) {\n\t\t\t\t\t\t\tsources[j].connected = true;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tio.to('settings').emit('sources', sources);\n\t\t\t\t});\n\n\t\t\t\tsource_connections[i].server.on('data', function (data) {\n\t\t\t\t\tlogger(`Source: ${source.name} VMix data received.`, 'info-quiet');\n\t\t\t\t\tdata = data\n\t\t\t\t\t.toString()\n\t\t\t\t\t.split(/\\r?\\n/);\n\n\t\t\t\t\ttallyData = data.filter(text => text.startsWith('TALLY OK'));\n\n\t\t\t\t\tif (tallyData.length > 0) {\n\t\t\t\t\t\tlogger(`Source: ${source.name} VMix tally data received.`, 'info-quiet');\n\t\t\t\t\t\tfor (let j = 9; j < tallyData[0].length; j++) {\n\t\t\t\t\t\t\tlet address = j-9+1;\n\t\t\t\t\t\t\tlet value = tallyData[0].charAt(j);\n\n\t\t\t\t\t\t\t//build an object like the TSL module creates so we can use the same function to process it\n\t\t\t\t\t\t\tlet tallyObj = {};\n\t\t\t\t\t\t\ttallyObj.address = address.toString();\n\t\t\t\t\t\t\ttallyObj.brightness = 1;\n\t\t\t\t\t\t\ttallyObj.tally1 = ((value === '2') ? 1 : 0);\n\t\t\t\t\t\t\ttallyObj.tally2 = ((value === '1') ? 1 : 0);\n\t\t\t\t\t\t\ttallyObj.tally3 = 0;\n\t\t\t\t\t\t\ttallyObj.tally4 = 0;\n\t\t\t\t\t\t\ttallyObj.label = `Input ${address}`;\n\t\t\t\t\t\t\tprocessTSLTally(sourceId, tallyObj);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tsource_connections[i].server.on('close', function () {\n\t\t\t\t\tlogger(`Source: ${source.name} VMix Connection closed.`, 'info');\n\t\t\t\t\tfor (let j = 0; j < sources.length; j++) {\n\t\t\t\t\t\tif (sources[j].id === sourceId) {\n\t\t\t\t\t\t\tsources[j].connected = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tio.to('settings').emit('sources', sources);\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tcatch (error) {\n\t\tlogger(`Source: ${source.name}. VMix Error Occurred: ${error}`, 'error');\n\t}\n}\n\nfunction StopVMixServer(sourceId) {\n\tlet source = GetSourceBySourceId(sourceId);\n\t\n\tfor (let i = 0; i < source_connections.length; i++) {\n\t\tif (source_connections[i].sourceId === sourceId) {\n\t\t\tlogger(`Source: ${source.name} Closing VMix connection.`, 'info-quiet');\n\t\t\tsource_connections[i].server.write('QUIT\\r\\n');\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\nfunction SetUpRolandSmartTally(sourceId) {\n\tlet source = sources.find( ({ id }) => id === sourceId);\n\tlet ip = source.data.ip;\n\n\ttry {\n\t\tlet sourceConnectionObj = {};\n\t\tsourceConnectionObj.sourceId = sourceId;\n\t\tsourceConnectionObj.server = null;\n\t\tsource_connections.push(sourceConnectionObj);\n\n\t\tfor (let i = 0; i < source_connections.length; i++) {\n\t\t\tif (source_connections[i].sourceId === sourceId) {\n\t\t\t\tlogger(`Source: ${source.name} Opening Roland Smart Tally connection.`, 'info-quiet');\n\t\t\t\tsource_connections[i].server = setInterval(function() {\n\t\t\t\t\tfor (let j = 0; j < device_sources.length; j++) {\n\t\t\t\t\t\tif (device_sources[j].sourceId === sourceId) {\n\t\t\t\t\t\t\tlet address = device_sources[j].address;\n\t\t\t\t\t\t\taxios.get(`http://${ip}/tally/${address}/status`)\n\t\t\t\t\t\t\t.then(function (response) {\n\t\t\t\t\t\t\t\tlet tallyObj = {};\n\t\t\t\t\t\t\t\ttallyObj.address = address;\n\t\t\t\t\t\t\t\ttallyObj.label = \"Input \" + address;\n\t\t\t\t\t\t\t\ttallyObj.tally4 = 0;\n\t\t\t\t\t\t\t\ttallyObj.tally3 = 0;\n\t\t\t\t\t\t\t\ttallyObj.tally2 = 0;\n\t\t\t\t\t\t\t\ttallyObj.tally1 = 0;\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tswitch(response)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tcase \"onair\":\n\t\t\t\t\t\t\t\t\t\ttallyObj.tally2 = 1;\n\t\t\t\t\t\t\t\t\t\ttallyObj.tally1 = 0;\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\tcase \"selected\":\n\t\t\t\t\t\t\t\t\t\ttallyObj.tally2 = 0;\n\t\t\t\t\t\t\t\t\t\ttallyObj.tally1 = 1;\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\tcase \"unselected\":\n\t\t\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\t\t\ttallyObj.tally2 = 0;\n\t\t\t\t\t\t\t\t\t\ttallyObj.tally1 = 0;\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tprocessTSLTally(sourceId, tallyObj);\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t.catch(function (error) {\n\t\t\t\t\t\t\t\tlogger(`Source: ${source.name} Roland Smart Tally Error: ${error}`, 'error');\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}, 1000, sourceId);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tio.to('settings').emit('sources', sources);\n\t}\n\tcatch (error) {\n\t\tlogger(`Source: ${source.name}. Roland Smart Tally Error: ${error}`, 'error');\n\t}\n}\n\nfunction StopRolandSmartTally(sourceId) {\n\tlet source = GetSourceBySourceId(sourceId);\n\t\n\tfor (let i = 0; i < source_connections.length; i++) {\n\t\tif (source_connections[i].sourceId === sourceId) {\n\t\t\tclearInterval(source_connections[i].server);\n\t\t\tlogger(`Source: ${source.name} Roland Smart Tally connection closed`, 'info');\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tfor (let j = 0; j < sources.length; j++) {\n\t\tif (sources[j].id === sourceId) {\n\t\t\tsources[j].connected = false;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tio.to('settings').emit('sources', sources);\n}\n\nfunction SetUpOSCServer(sourceId) {\n\tlet source = sources.find( ({ id }) => id === sourceId);\n\n\ttry {\n\t\tlet sourceConnectionObj = {};\n\t\tsourceConnectionObj.sourceId = sourceId;\n\t\tsourceConnectionObj.server = null;\n\t\tsource_connections.push(sourceConnectionObj);\n\n\t\tfor (let i = 0; i < source_connections.length; i++) {\n\t\t\tif (source_connections[i].sourceId === sourceId) {\n\t\t\t\tAddPort(source.data.port, sourceId);\n\t\t\t\tlogger(`Source: ${source.name} Creating new OSC connection.`, 'info-quiet');\n\t\t\t\tsource_connections[i].server = new osc.UDPPort({\n\t\t\t\t\tlocalAddress: '0.0.0.0',\n\t\t\t\t\tlocalPort: source.data.port,\n\t\t\t\t\tmetadata: true\n\t\t\t\t});\n\t\t\t\n\t\t\t\tsource_connections[i].server.on('message', function (oscMsg, timeTag, info) {\n\t\t\t\t\tlogger(`Source: ${source.name} OSC message received: ${oscMsg.address} ${oscMsg.args[0].value.toString()}`, 'info-quiet');\n\t\t\t\t\tlet tallyObj = {};\n\t\t\t\t\ttallyObj.address = oscMsg.args[0].value.toString();\n\t\t\t\t\ttallyObj.label = tallyObj.address;\n\t\t\t\t\tswitch(oscMsg.address) {\n\t\t\t\t\t\tcase '/tally/preview_on':\n\t\t\t\t\t\t\ttallyObj.tally1 = 1;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase '/tally/preview_off':\n\t\t\t\t\t\t\ttallyObj.tally1 = 0;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase '/tally/program_on':\n\t\t\t\t\t\t\ttallyObj.tally2 = 1;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase '/tally/program_off':\n\t\t\t\t\t\t\ttallyObj.tally2 = 0;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tprocessTSLTally(source.id, tallyObj);\n\t\t\t\t});\n\t\t\t\n\t\t\t\tsource_connections[i].server.on('error', function (error) {\n\t\t\t\t\tconsole.log('An error occurred: ', error.message);\n\t\t\t\t});\n\n\t\t\t\tsource_connections[i].server.on('ready', function () {\n\t\t\t\t\tlogger(`Source: ${source.name} OSC port ${source.data.port} ready.`, 'info-quiet');\n\t\t\t\t\tfor (let j = 0; j < sources.length; j++) {\n\t\t\t\t\t\tif (sources[j].id === sourceId) {\n\t\t\t\t\t\t\tsources[j].connected = true;\n\t\t\t\t\t\t\tio.to('settings').emit('sources', sources);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\n\t\t\t\tsource_connections[i].server.open();\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tcatch (error) {\n\t\tlogger(`Source: ${source.name} OSC Error: ${error}`, 'error');\n\t}\n}\n\nfunction StopOSCServer(sourceId) {\n\tlet source = GetSourceBySourceId(sourceId);\n\n\tfor (let i = 0; i < source_connections.length; i++) {\n\t\tif (source_connections[i].sourceId === sourceId) {\n\t\t\tsource_connections[i].server.close();\n\t\t\tDeletePort(source.data.port);\n\t\t\tlogger(`Source: ${source.name} OSC connection closed.`, 'info');\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tfor (let j = 0; j < sources.length; j++) {\n\t\tif (sources[j].id === sourceId) {\n\t\t\tsources[j].connected = false;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tio.to('settings').emit('sources', sources);\n}\n\nfunction processTSLTally(sourceId, tallyObj) // Processes the TSL Data\n{\n\tlogger(`Processing new tally object.`, 'info-quiet');\n\n\tio.to('settings').emit('tally_data', sourceId, tallyObj);\n\n\tlet deviceId = null;\n\n\tfor (let i = 0; i < device_sources.length; i++) {\n\t\tif ((device_sources[i].sourceId === sourceId) && (device_sources[i].address === tallyObj.address.toString())) {\n\t\t\tdeviceId = device_sources[i].deviceId;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tlet busId_preview = null;\n\tlet busId_program = null;\n\t//let busId_previewprogram = null;\n\n\tfor (let i = 0; i < bus_options.length; i++) {\n\t\tswitch(bus_options[i].type) {\n\t\t\tcase 'preview':\n\t\t\t\tbusId_preview = bus_options[i].id;\n\t\t\t\tbreak;\n\t\t\tcase 'program':\n\t\t\t\tbusId_program = bus_options[i].id;\n\t\t\t\tbreak;\n\t\t\t/*case 'previewprogram':\n\t\t\t\tbusId_previewprogram = bus_options[i].id;\n\t\t\t\tbreak;*/\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (deviceId !== null) {\n\t\t//do something with the device given the current state\n\n\t\tlet inPreview = false;\n\t\tlet inProgram = false;\n\n\t\tfor (let i = 0; i < device_states.length; i++) {\n\t\t\tif (device_states[i].deviceId === deviceId) {\n\t\t\t\tif (device_states[i].busId === busId_preview) {\n\t\t\t\t\tif (device_states[i].sources.includes(sourceId)) {\n\t\t\t\t\t\t//if the device is currently marked as in preview, let's check and see if we should remove it\n\t\t\t\t\t\tif (!tallyObj.tally1) {\n\t\t\t\t\t\t\t//remove it, it's no longer in preview on that source\n\t\t\t\t\t\t\tdevice_states[i].sources.splice(device_states[i].sources.indexOf(sourceId));\n\t\t\t\t\t\t\tinPreview = false;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tinPreview = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\t//if the device is currently not marked as in preview, let's check and see if we should include it\n\t\t\t\t\t\tif (tallyObj.tally1) {\n\t\t\t\t\t\t\t//add it, it's not already in preview on this source\n\t\t\t\t\t\t\tdevice_states[i].sources.push(sourceId);\n\t\t\t\t\t\t\tinPreview = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (device_states[i].busId === busId_program) {\n\t\t\t\t\tif (device_states[i].sources.includes(sourceId)) {\n\t\t\t\t\t\t//if the device is currently marked as in program, let's check and see if we should remove it\n\t\t\t\t\t\tif (!tallyObj.tally2) {\n\t\t\t\t\t\t\t//remove it, it's no longer in program on that source\n\t\t\t\t\t\t\tdevice_states[i].sources.splice(device_states[i].sources.indexOf(sourceId));\n\t\t\t\t\t\t\tinProgram = false;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tinProgram = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\t//if the device is currently not marked as in program, let's check and see if we should include it\n\t\t\t\t\t\tif (tallyObj.tally2) {\n\t\t\t\t\t\t\t//add it, it's not already in program on this source\n\t\t\t\t\t\t\tdevice_states[i].sources.push(sourceId);\n\t\t\t\t\t\t\tinProgram = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t/*for (let i = 0; i < device_states.length; i++) {\n\t\t\tif (device_states[i].deviceId === deviceId) {\n\t\t\t\tif (device_states[i].busId === busId_previewprogram) {\n\t\t\t\t\tif (device_states[i].sources.includes(sourceId)) {\n\t\t\t\t\t\t//if the device is currently marked as in preview+program, let's check and see if we should remove it\n\t\t\t\t\t\tif ((!inPreview) && (!inProgram)) {\n\t\t\t\t\t\t\t//remove it, it's no longer in preview+program on that source\n\t\t\t\t\t\t\tdevice_states[i].sources.splice(device_states[i].sources.indexOf(sourceId));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\t//if the device is currently not marked as in preview+program, let's check and see if we should include it\n\t\t\t\t\t\tif ((inPreview) && (inProgram)) {\n\t\t\t\t\t\t\t//add it, it's not already in preview+program on this source\n\t\t\t\t\t\t\tdevice_states[i].sources.push(sourceId);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}*/\n\n\t\tUpdateDeviceState(deviceId);\n\t\tio.to('settings').emit('device_states', device_states);\n\t\tio.to('producer').emit('device_states', device_states);\n\t}\n}\n\nfunction UpdateDeviceState(deviceId) {\n\tlet busId_preview = null;\n\tlet busId_program = null;\n\t//let busId_previewprogram = null;\n\n\tfor (let i = 0; i < bus_options.length; i++) {\n\t\tswitch(bus_options[i].type) {\n\t\t\tcase 'preview':\n\t\t\t\tbusId_preview = bus_options[i].id;\n\t\t\t\tbreak;\n\t\t\tcase 'program':\n\t\t\t\tbusId_program = bus_options[i].id;\n\t\t\t\tbreak;\n\t\t\t/*case 'previewprogram':\n\t\t\t\tbusId_previewprogram = bus_options[i].id;\n\t\t\t\tbreak;*/\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tlet inPreview = null;\n\tlet inProgram = null;\n\n\tfor (let i = 0; i < device_states.length; i++) {\n\t\tif (device_states[i].deviceId === deviceId) {\n\t\t\tif (device_states[i].busId === busId_preview) {\n\t\t\t\tif ((device_states[i].sources.length > 0) && (!device_states[i].active)) {\n\t\t\t\t\t//if the sources list is now greater than zero and the state is not already marked active for this device, run the action and make it active\n\t\t\t\t\tRunAction(deviceId, device_states[i].busId, true);\n\t\t\t\t\tdevice_states[i].active = true;\n\t\t\t\t}\n\t\t\t\telse if ((device_states[i].sources.length < 1) && (device_states[i].active)) {\n\t\t\t\t\t//if the source list is now zero and the state is marked active, run the action and make it inactive\n\t\t\t\t\tRunAction(deviceId, device_states[i].busId, false);\n\t\t\t\t\tdevice_states[i].active = false;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (device_states[i].busId === busId_program) {\n\t\t\t\tif ((device_states[i].sources.length > 0) && (!device_states[i].active)) {\n\t\t\t\t\t//if the sources list is now greater than zero and the state is not already marked active for this device, run the action and make it active\n\t\t\t\t\tRunAction(deviceId, device_states[i].busId, true);\n\t\t\t\t\tdevice_states[i].active = true;\n\t\t\t\t}\n\t\t\t\telse if ((device_states[i].sources.length < 1) && (device_states[i].active)) {\n\t\t\t\t\t//if the source list is now zero and the state is marked active, run the action and make it inactive\n\t\t\t\t\tRunAction(deviceId, device_states[i].busId, false);\n\t\t\t\t\tdevice_states[i].active = false;\n\t\t\t\t}\n\t\t\t}\n\t\t\t/*else if (device_states[i].busId === busId_previewprogram) {\n\t\t\t\tif ((device_states[i].sources.length > 0) && (!device_states[i].active)) {\n\t\t\t\t\t//if the sources list is now greater than zero and the state is not already marked active for this device, run the action and make it active\n\t\t\t\t\tRunAction(deviceId, device_states[i].busId, true);\n\t\t\t\t\tdevice_states[i].active = true;\n\t\t\t\t}\n\t\t\t\telse if ((device_states[i].sources.length < 1) && (device_states[i].active)) {\n\t\t\t\t\t//if the source list is now zero and the state is marked active, run the action and make it inactive\n\t\t\t\t\tRunAction(deviceId, device_states[i].busId, false);\n\t\t\t\t\tdevice_states[i].active = false;\n\t\t\t\t}\n\t\t\t}*/\n\t\t}\n\t}\n}\n\nfunction RunAction(deviceId, busId, active) {\n\tlet actionObj = null;\n\n\tlet deviceObj = GetDeviceByDeviceId(deviceId);\n\n\tif (deviceObj.enabled === true) {\n\t\tlet filteredActions = device_actions.filter(obj => obj.deviceId === deviceId);\n\t\tif (filteredActions.length > 0) {\n\t\t\tlogger(`Running Actions for Device: ${deviceObj.name}`, 'info');\n\t\t\tfor (let i = 0; i < filteredActions.length; i++) {\n\t\t\t\tif ((filteredActions[i].busId === busId) && (filteredActions[i].active === active)) {\n\t\t\t\t\tactionObj = filteredActions[i];\n\t\t\t\t\t\n\t\t\t\t\tlet outputType = output_types.find( ({ id }) => id === actionObj.outputTypeId);\n\t\n\t\t\t\t\tlogger(`Running action: ${outputType.label} ${filteredActions[i].id}`, 'info');\n\t\n\t\t\t\t\tswitch(outputType.type) {\n\t\t\t\t\t\tcase 'tsl_31_udp':\n\t\t\t\t\t\t\tRunAction_TSL_31_UDP(actionObj.data);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 'tsl_31_tcp':\n\t\t\t\t\t\t\tRunAction_TSL_31_TCP(actionObj.data);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 'webhook':\n\t\t\t\t\t\t\tRunAction_Webhook(actionObj.data);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 'console':\n\t\t\t\t\t\t\tlogger(actionObj.data, 'console_action');\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 'osc':\n\t\t\t\t\t\t\tRunAction_OSC(actionObj.data);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tlogger(`Device Action: ${filteredActions[i].id} Error: Unsupported Output Type: ${outputType.type}`, 'error');\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\telse {\n\t\t//the device is disabled, so don't run any actions against it\n\t\tlogger(`Device: ${deviceObj.name} is not enabled, so no actions will be run.`, 'info');\n\t}\n\t\n\tlogger(`Sending device states for: ${deviceObj.id}`, 'info-quiet');\n\tio.to('device-' + deviceId).emit('device_states', GetDeviceStatesByDeviceId(deviceId));\n}\n\nfunction RunAction_TSL_31_UDP(data) {\n\ttry {\n\t\tlet bufUMD = Buffer.alloc(18, 0); //ignores spec and pad with 0 for better aligning on Decimator etc\n\t\tbufUMD[0] = 0x80 + parseInt(data.address);\n\t\tbufUMD.write(data.label, 2);\n\t\n\t\tlet bufTally = 0x30;\n\t\t\n\t\tif (data.tally1) {\n\t\t\tbufTally |= 1;\n\t\t}\n\t\tif (data.tally2) {\n\t\t\tbufTally |= 2;\n\t\t}\n\t\tif (data.tally3) {\n\t\t\tbufTally |= 4;\n\t\t}\n\t\tif (data.tally4) {\n\t\t\tbufTally |= 8;\n\t\t}\n\t\tbufUMD[1] = bufTally;\n\t\n\t\tlet client = dgram.createSocket('udp4');\n\t\tclient.on('message',function(msg,info){\n\t\t});\n\t\n\t\tclient.send(bufUMD, data.port, data.ip, function(error) {\n\t\t\tif (!error) {\n\t\t\t\tlogger(`TSL 3.1 UDP Data sent.`, 'info');\n\t\t\t}\n\t\t\tclient.close();\n\t\t});\n\t}\n\tcatch (error) {\n\t\tlogger(`An error occured sending the TCP 3.1 UDP Message: ${error}`, 'error');\n\t}\n}\n\nfunction RunAction_TSL_31_TCP(data) {\n\ttry {\n\t\tlet bufUMD = Buffer.alloc(18, 0); //ignore spec and pad with 0 for better aligning on Decimator, etc.\n\t\tbufUMD[0] = 0x80 + parseInt(data.address); //Address + 0x80\n\t\tbufUMD.write(data.label, 2);\n\t\n\t\tlet bufTally = 0x30;\n\t\t\n\t\tif (data.tally1) {\n\t\t\tbufTally |= 1;\n\t\t}\n\t\tif (data.tally2) {\n\t\t\tbufTally |= 2;\n\t\t}\n\t\tif (data.tally3) {\n\t\t\tbufTally |= 4;\n\t\t}\n\t\tif (data.tally4) {\n\t\t\tbufTally |= 8;\n\t\t}\n\t\tbufUMD[1] = bufTally;\n\t\t\n\t\tlet client = new net.Socket();\n\t\tclient.connect(data.port, data.ip, function() {\n\t\t\tclient.write(bufUMD);\n\t\t});\n\t\n\t\tclient.on('data', function(data) {\n\t\t\tclient.destroy(); // kill client after server's response\n\t\t});\n\t\n\t\tclient.on('close', function() {\n\t\t});\n\t}\n\tcatch (error) {\n\t\tlogger(`An error occured sending the TCP 3.1 TCP Message: ${error}`, 'error');\n\t}\n}\n\nfunction RunAction_Webhook(data) {\n\ttry {\n\t\tlet options = {\n\t\t\tmethod: data.method,\n\t\t\turl: 'http://' + data.ip + ':' + data.port + '/' + data.path\n\t\t};\n\n\t\tif (data.method === 'POST') {\n\t\t\tif (data.postdata !== '') {\n\t\t\t\toptions.data = data.postdata;\n\t\t\t}\n\t\t}\n\n\t\taxios(options)\n\t\t.then(function (response) {\n\t\t\tlogger(`Outgoing Webhook triggered.`, 'info');\n\t\t})\n\t\t.catch(function (error) {\n\t\t\tlogger(`An error occured triggering the Outgoing Webhook: ${error}`, 'error');\n\t\t});\n\t}\n\tcatch (error) {\n\t\tlogger(`An error occured sending the Outgoing Webhook: ${error}`, 'error');\n\t}\n}\n\nfunction RunAction_OSC(data) {\n\tlet arguments = data.args.split(' ');\n\n\tlet args = null;\n\n\tlet arg;\n\t\n\tif (arguments.length) {\n\t\targs = [];\n\t}\n\t\n\tfor (let i = 0; i < arguments.length; i++) {\n\t\tif (isNaN(arguments[i])) {\n\t\t\targ = {\n\t\t\t\ttype: 's',\n\t\t\t\tvalue: arguments[i].replace(/\"/g, '').replace(/'/g, '')\n\t\t\t};\n\t\t\targs.push(arg);\n\t\t}\n\t\telse if (arguments[i].indexOf('.') > -1) {\n\t\t\targ = {\n\t\t\t\ttype: 'f',\n\t\t\t\tvalue: parseFloat(arguments[i])\n\t\t\t};\n\t\t\targs.push(arg);\n\t\t}\n\t\telse {\n\t\t\targ = {\n\t\t\t\ttype: 'i',\n\t\t\t\tvalue: parseInt(arguments[i])\n\t\t\t};\n\t\t\targs.push(arg);\n\t\t}\n\t}\n\n\tlogger(`Sending OSC Message: ${data.ip}:${data.port} ${data.path} ${data.args}`, 'info');\n\toscUDP.send({address: data.path, args: args}, data.ip, data.port);\n}\n\nfunction TallyArbiter_Manage(obj) {\n\tswitch(obj.type) {\n\t\tcase 'source':\n\t\t\tif (obj.action === 'add') {\n\t\t\t\tresult = TallyArbiter_Add_Source(obj);\n\t\t\t}\n\t\t\telse if (obj.action === 'edit') {\n\t\t\t\tresult = TallyArbiter_Edit_Source(obj);\n\t\t\t}\n\t\t\telse if (obj.action === 'delete') {\n\t\t\t\tresult = TallyArbiter_Delete_Source(obj);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 'device':\n\t\t\tif (obj.action === 'add') {\n\t\t\t\tresult = TallyArbiter_Add_Device(obj);\n\t\t\t}\n\t\t\telse if (obj.action === 'edit') {\n\t\t\t\tresult = TallyArbiter_Edit_Device(obj);\n\t\t\t}\n\t\t\telse if (obj.action === 'delete') {\n\t\t\t\tresult = TallyArbiter_Delete_Device(obj);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 'device_source':\n\t\t\tif (obj.action === 'add') {\n\t\t\t\tresult = TallyArbiter_Add_Device_Source(obj);\n\t\t\t}\n\t\t\telse if (obj.action === 'edit') {\n\t\t\t\tresult = TallyArbiter_Edit_Device_Source(obj);\n\t\t\t}\n\t\t\telse if (obj.action === 'delete') {\n\t\t\t\tresult = TallyArbiter_Delete_Device_Source(obj);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 'device_action':\n\t\t\tif (obj.action === 'add') {\n\t\t\t\tresult = TallyArbiter_Add_Device_Action(obj);\n\t\t\t}\n\t\t\telse if (obj.action === 'edit') {\n\t\t\t\tresult = TallyArbiter_Edit_Device_Action(obj);\n\t\t\t}\n\t\t\telse if (obj.action === 'delete') {\n\t\t\t\tresult = TallyArbiter_Delete_Device_Action(obj);\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t}\n\n\ttry {\n\t\tlet configJson = {\n\t\t\tsources: sources,\n\t\t\tdevices: devices,\n\t\t\tdevice_sources: device_sources,\n\t\t\tdevice_actions: device_actions\n\t\t};\n\n\t\tfs.writeFileSync(config_file, JSON.stringify(configJson, null, 1), 'utf8', function(error) {\n\t\t\tif (error)\n\t\t\t{ \n\t\t\t\tresult.error = 'Error saving configuration to file: ' + error;\n\t\t\t}\n\t\t});\t\n\t}\n\tcatch (error) {\n\t\tresult.error = 'Error saving configuration to file: ' + error;\n\t}\n\tfinally {\n\t\t//sends a result object back\n\t\treturn result;\n\t}\n}\n\nfunction StartConnection(sourceId) {\n\tlet source = sources.find( ({ id }) => id === sourceId);\n\tlet sourceType = source_types.find( ({ id }) => id === source.sourceTypeId);\n\n\tswitch(sourceType.type) {\n\t\tcase 'tsl_31_udp':\n\t\t\tSetUpTSLServer_UDP(sourceId);\n\t\t\tbreak;\n\t\tcase 'tsl_31_tcp':\n\t\t\tSetUpTSLServer_TCP(sourceId);\n\t\t\tbreak;\n\t\tcase 'atem':\n\t\t\tSetUpATEMServer(sourceId);\n\t\t\tbreak;\n\t\tcase 'obs':\n\t\t\tSetUpOBSServer(sourceId);\n\t\t\tbreak;\n\t\tcase 'vmix':\n\t\t\tSetUpVMixServer(sourceId);\n\t\t\tbreak;\n\t\tcase 'roland':\n\t\t\tSetUpRolandSmartTally(sourceId);\n\t\t\tbreak;\n\t\tcase 'osc':\n\t\t\tSetUpOSCServer(sourceId);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t}\n}\n\nfunction StopConnection(sourceId) {\n\tlet source = sources.find( ({ id }) => id === sourceId);\n\tlet sourceType = source_types.find( ({ id }) => id === source.sourceTypeId);\n\n\tswitch(sourceType.type) {\n\t\tcase 'tsl_31_udp':\n\t\t\tStopTSLServer_UDP(sourceId);\n\t\t\tbreak;\n\t\tcase 'tsl_31_tcp':\n\t\t\tStopTSLServer_TCP(sourceId);\n\t\t\tbreak;\n\t\tcase 'atem':\n\t\t\tStopATEMServer(sourceId);\n\t\t\tbreak;\n\t\tcase 'obs':\n\t\t\tStopOBSServer(sourceId);\n\t\t\tbreak;\n\t\tcase 'vmix':\n\t\t\tStopVMixServer(sourceId);\n\t\t\tbreak;\n\t\tcase 'roland':\n\t\t\tStopRolandSmartTally(sourceId);\n\t\t\tbreak;\n\t\tcase 'osc':\n\t\t\tStopOSCServer(sourceId);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t}\n}\n\nfunction TallyArbiter_Add_Source(obj) {\n\tlet sourceObj = obj.source;\n\tsourceObj.id = uuidv4();\n\tsources.push(sourceObj);\n\n\tlogger(`Source Added: ${sourceObj.name}`, 'info');\n\n\tStartConnection(sourceObj.id);\n\n\treturn {result: 'source-added-successfully'};\n}\n\nfunction TallyArbiter_Edit_Source(obj) {\n\tlet sourceObj = obj.source;\n\tlet sourceTypeId = null;\n\tlet connected = false;\n\n\tfor (let i = 0; i < sources.length; i++) {\n\t\tif (sources[i].id === sourceObj.id) {\n\t\t\tsources[i].name = sourceObj.name;\n\t\t\tsources[i].enabled = sourceObj.enabled;\n\t\t\tsources[i].data = sourceObj.data;\n\t\t\tsourceTypeId = sources[i].sourceTypeId;\n\t\t\tconnected = sources[i].connected;\n\t\t}\n\t}\n\n\tlogger(`Source Edited: ${sourceObj.name}`, 'info');\n\n\tif (sourceObj.enabled === true) {\n\t\tif (!connected) {\n\t\t\tStartConnection(sourceObj.id);\n\t\t}\n\t}\n\telse {\n\t\tStopConnection(sourceObj.id);\n\t}\n\n\treturn {result: 'source-edited-successfully'};\n}\n\nfunction TallyArbiter_Delete_Source(obj) {\n\tlet sourceId = obj.sourceId;\n\tlet sourceName = null;\n\n\tfor (let i = 0; i < sources.length; i++) {\n\t\tif (sources[i].id === sourceId) {\n\t\t\tif (sources[i].connected === true) {\n\t\t\t\tStopConnection(sourceId);\n\t\t\t}\n\t\t\tsourceName = sources[i].name;\n\t\t\tsources.splice(i, 1);\n\t\t}\n\t}\n\n\tfor (let i = device_sources.length - 1; i >= 0; i--) {\n\t\tif (device_sources[i].sourceId === sourceId) {\n\t\t\tdevice_sources.splice(i, 1);\n\t\t}\n\t}\n\n\tfor (let i = device_states.length - 1; i >=0; i--) {\n\t\tfor (let j = device_states[i].sources.length - 1; j >=0; j--) {\n\t\t\tif (device_states[i].sources[j] === sourceId) {\n\t\t\t\tdevice_states[i].sources.splice(j, 1);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tio.to('settings').emit('device_states', device_states);\n\tio.to('producer').emit('device_states', device_states);\n\n\tlogger(`Source Deleted: ${sourceName}`, 'info');\n\n\treturn {result: 'source-deleted-successfully'};\n}\n\nfunction TallyArbiter_Add_Device(obj) {\n\tlet deviceObj = obj.device;\n\tdeviceObj.id = uuidv4();\n\tdevices.push(deviceObj);\n\n\tlet busId_preview = null;\n\tlet busId_program = null;\n\t//let busId_previewprogram = null;\n\n\tfor (let i = 0; i < bus_options.length; i++) {\n\t\tswitch(bus_options[i].type) {\n\t\t\tcase 'preview':\n\t\t\t\tbusId_preview = bus_options[i].id;\n\t\t\t\tbreak;\n\t\t\tcase 'program':\n\t\t\t\tbusId_program = bus_options[i].id;\n\t\t\t\tbreak;\n\t\t\t/*case 'previewprogram':\n\t\t\t\tbusId_previewprogram = bus_options[i].id;\n\t\t\t\tbreak;*/\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tlet deviceStateObj_preview = {};\n\tdeviceStateObj_preview.deviceId = deviceObj.id;\n\tdeviceStateObj_preview.busId = busId_preview;\n\tdeviceStateObj_preview.sources = [];\n\tdevice_states.push(deviceStateObj_preview);\n\n\tlet deviceStateObj_program = {};\n\tdeviceStateObj_program.deviceId = deviceObj.id;\n\tdeviceStateObj_program.busId = busId_program;\n\tdeviceStateObj_program.sources = [];\n\tdevice_states.push(deviceStateObj_program);\n\n\t/*let deviceStateObj_previewprogram = {};\n\tdeviceStateObj_previewprogram.deviceId = deviceObj.id;\n\tdeviceStateObj_previewprogram.busId = busId_previewprogram;\n\tdeviceStateObj_previewprogram.sources = [];\n\tdevice_states.push(deviceStateObj_previewprogram);*/\n\n\tlogger(`Device Added: ${deviceObj.name}`, 'info');\n\n\treturn {result: 'device-added-successfully'};\n}\n\nfunction TallyArbiter_Edit_Device(obj) {\n\tlet deviceObj = obj.device;\n\tfor (let i = 0; i < devices.length; i++) {\n\t\tif (devices[i].id === deviceObj.id) {\n\t\t\tdevices[i].name = deviceObj.name;\n\t\t\tdevices[i].description = deviceObj.description;\n\t\t\tdevices[i].enabled = deviceObj.enabled;\n\t\t}\n\t}\n\n\tlogger(`Device Edited: ${deviceObj.name}`, 'info');\n\n\treturn {result: 'device-edited-successfully'};\n}\n\nfunction TallyArbiter_Delete_Device(obj) {\n\tlet deviceId = obj.deviceId;\n\tlet deviceName = GetDeviceByDeviceId(deviceId).name;\n\n\tfor (let i = 0; i < devices.length; i++) {\n\t\tif (devices[i].id === deviceId) {\n\t\t\tdevices.splice(i, 1);\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tfor (let i = device_sources.length - 1; i >= 0; i--) {\n\t\tif (device_sources[i].deviceId === deviceId) {\n\t\t\tdevice_sources.splice(i, 1);\n\t\t}\n\t}\n\t\n\tfor (let i = device_actions.length - 1; i >= 0; i--) {\n\t\tif (device_actions[i].deviceId === deviceId) {\n\t\t\tdevice_actions.splice(i, 1);\n\t\t}\n\t}\n\n\tlogger(`Device Deleted: ${deviceName}`, 'info');\n\n\treturn {result: 'device-deleted-successfully'};\n}\n\nfunction TallyArbiter_Add_Device_Source(obj) {\n\tlet deviceSourceObj = obj.device_source;\n\tlet deviceId = deviceSourceObj.deviceId;\n\tdeviceSourceObj.id = uuidv4();\n\tdevice_sources.push(deviceSourceObj);\n\n\tlet deviceName = GetDeviceByDeviceId(deviceSourceObj.deviceId).name;\n\tlet sourceName = GetSourceBySourceId(deviceSourceObj.sourceId).name;\n\n\tlogger(`Device Source Added: ${deviceName} - ${sourceName}`, 'info');\n\n\treturn {result: 'device-source-added-successfully', deviceId: deviceId};\n}\n\nfunction TallyArbiter_Edit_Device_Source(obj) {\n\tlet deviceSourceObj = obj.device_source;\n\tlet deviceId = null;\n\tfor (let i = 0; i < device_sources.length; i++) {\n\t\tif (device_sources[i].id === deviceSourceObj.id) {\n\t\t\tdeviceId = device_sources[i].deviceId;\n\t\t\tdevice_sources[i].sourceId = deviceSourceObj.sourceId;\n\t\t\tdevice_sources[i].address = deviceSourceObj.address;\n\t\t}\n\t}\n\n\tlet deviceName = GetDeviceByDeviceId(deviceId).name;\n\tlet sourceName = GetSourceBySourceId(deviceSourceObj.sourceId).name;\n\n\tlogger(`Device Source Edited: ${deviceName} - ${sourceName}`, 'info');\n\n\treturn {result: 'device-source-edited-successfully', deviceId: deviceId};\n}\n\nfunction TallyArbiter_Delete_Device_Source(obj) {\n\tlet deviceSourceId = obj.device_source.id;\n\tlet deviceId = null;\n\tlet sourceId = null;\n\n\tfor (let i = 0; i < device_sources.length; i++) {\n\t\tif (device_sources[i].id === deviceSourceId) {\n\t\t\tdeviceId = device_sources[i].deviceId;\n\t\t\tsourceId = device_sources[i].sourceId;\n\t\t\tdevice_sources.splice(i, 1);\n\t\t}\n\t}\n\n\tlet deviceName = GetDeviceByDeviceId(deviceId).name;\n\tlet sourceName = GetSourceBySourceId(sourceId).name;\n\n\tlogger(`Device Source Deleted: ${deviceName} - ${sourceName}`, 'info');\n\n\treturn {result: 'device-source-deleted-successfully', deviceId: deviceId};\n}\n\nfunction TallyArbiter_Add_Device_Action(obj) {\n\tlet deviceActionObj = obj.device_action;\n\tlet deviceId = deviceActionObj.deviceId;\n\tdeviceActionObj.id = uuidv4();\n\tdevice_actions.push(deviceActionObj);\n\n\tlet deviceName = GetDeviceByDeviceId(deviceActionObj.deviceId).name;\n\tlet outputTypeName = GetOutputTypeByOutputTypeId(deviceActionObj.outputTypeId).label;\n\n\tlogger(`Device Action Added: ${deviceName} - ${outputTypeName}`, 'info');\n\n\treturn {result: 'device-action-added-successfully', deviceId: deviceId};\n}\n\nfunction TallyArbiter_Edit_Device_Action(obj) {\n\tlet deviceActionObj = obj.device_action;\n\tlet deviceId = null;\n\tfor (let i = 0; i < device_actions.length; i++) {\n\t\tif (device_actions[i].id === deviceActionObj.id) {\n\t\t\tdeviceId = device_actions[i].deviceId;\n\t\t\tdevice_actions[i].busId = deviceActionObj.busId;\n\t\t\tdevice_actions[i].active = deviceActionObj.active;\n\t\t\tdevice_actions[i].outputTypeId = deviceActionObj.outputTypeId;\n\t\t\tdevice_actions[i].data = deviceActionObj.data;\n\t\t}\n\t}\n\n\tlet deviceName = GetDeviceByDeviceId(deviceActionObj.deviceId).name;\n\tlet outputTypeName = GetOutputTypeByOutputTypeId(deviceActionObj.outputTypeId).label;\n\n\tlogger(`Device Action Edited: ${deviceName} - ${outputTypeName}`, 'info');\n\n\treturn {result: 'device-action-edited-successfully', deviceId: deviceId};\n}\n\nfunction TallyArbiter_Delete_Device_Action(obj) {\n\tlet deviceActionId = obj.device_action.id;\n\tlet deviceId = null;\n\tlet outputTypeId = null;\n\n\tfor (let i = 0; i < device_actions.length; i++) {\n\t\tif (device_actions[i].id === deviceActionId) {\n\t\t\tdeviceId = device_actions[i].deviceId;\n\t\t\toutputTypeId = device_actions[i].outputTypeId;\n\t\t\tdevice_actions.splice(i, 1);\n\t\t}\n\t}\n\n\tlet deviceName = GetDeviceByDeviceId(deviceId).name;\n\tlet outputTypeName = GetOutputTypeByOutputTypeId(outputTypeId).label;\n\n\tlogger(`Device Action Deleted: ${deviceName} - ${outputTypeName}`, 'info');\n\n\treturn {result: 'device-action-deleted-successfully', deviceId: deviceId};\n}\n\nfunction GetSourceBySourceId(sourceId) {\n\t//gets the Source object by id\n\treturn sources.find( ({ id }) => id === sourceId);\n}\n\nfunction GetSourceTypeBySourceTypeId(sourceTypeId) {\n\t//gets the Source Type object by id\n\treturn source_types.find( ({ id }) => id === sourceTypeId);\n}\n\nfunction GetBusByBusId(busId) {\n\t//gets the Bus object by id\n\treturn bus_options.find( ({ id }) => id === busId);\n}\n\nfunction GetDeviceByDeviceId(deviceId) {\n\t//gets the Device object by id\n\treturn devices.find( ({ id }) => id === deviceId);\n}\n\nfunction GetOutputTypeByOutputTypeId(outputTypeId) {\n\t//gets the Output Type object by id\n\treturn output_types.find( ({ id }) => id === outputTypeId);\n}\n\nfunction GetDeviceSourcesBySourceId(sourceId) {\n\treturn device_sources.filter(obj => obj.sourceId === sourceId);\n}\n\nfunction GetDeviceStatesByDeviceId(deviceId) {\n\t//gets the current tally data for the device and returns it\n\n\treturn device_states.filter(obj => obj.deviceId === deviceId);\n}\n\nfunction AddClient(socketId, deviceId, listenerType, ipAddress, datetimeConnected) {\n\tlet clientObj = {};\n\n\tclientObj.id = uuidv4();\n\tclientObj.socketId = socketId;\n\tclientObj.deviceId = deviceId;\n\tclientObj.listenerType = listenerType;\n\tclientObj.ipAddress = ipAddress;\n\tclientObj.datetime_connected = datetimeConnected;\n\tclientObj.inactive = false;\n\t\n\tClients.push(clientObj);\n\n\tio.to('settings').emit('clients', Clients);\n\tio.to('producer').emit('clients', Clients);\n\n\treturn clientObj.id;\n}\n\nfunction DeactivateClient(socketId) {\n\tfor (let i = 0; i < Clients.length; i++) {\n\t\tif (Clients[i].socketId === socketId) {\n\t\t\tClients[i].inactive = true;\n\t\t\tClients[i].datetime_inactive = new Date().getTime();\n\t\t}\n\t}\n\n\tio.to('settings').emit('clients', Clients);\n\tio.to('producer').emit('clients', Clients);\n}\n\nfunction DeleteInactiveClients() {\n\tlet changesMade = false;\n\tfor (let i = Clients.length - 1; i >= 0; i--) {\n\t\tif (Clients[i].inactive === true) {\n\t\t\tlet dtNow = new Date().getTime();\n\t\t\tif ((dtNow - Clients[i].datetime_inactive) > (1000 * 60 * 60)) { //1 hour\n\t\t\t\tlogger(`Inactive Client removed: ${Clients[i].id}`, 'info');\n\t\t\t\tClients.splice(i, 1);\n\t\t\t\tchangesMade = true;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (changesMade) {\n\t\tio.to('settings').emit('clients', Clients);\n\t\tio.to('producer').emit('clients', Clients);\n\t}\n\n\tsetTimeout(DeleteInactiveClients, 5 * 1000); // runs every 5 minutes\n}\n\nfunction FlashClient(clientId) {\n\tlet clientObj = Clients.find( ({ id }) => id === clientId);\n\n\tif (clientObj) {\n\t\tif (clientObj.relayGroupId) {\n\t\t\tio.to(clientObj.socketId).emit('flash', Clients[i].relayGroupId);\n\t\t}\n\t\telse {\n\t\t\tio.to(clientObj.socketId).emit('flash');\n\t\t}\n\t\treturn {result: 'flash-sent-successfully', cliendId: clientId};\n\t}\n\telse {\n\t\treturn {result: 'flash-not-sent', clientId: clientId, error: 'client id not found'};\n\t}\n}\n\nfunction AddPort(port, sourceId) { //Adds the port to the list of reserved or in-use ports\n\tlet portObj = {};\n\tportObj.port = port;\n\tportObj.sourceId = sourceId;\n\tPortsInUse.push(portObj);\n\tio.to('settings').emit('PortsInUse', PortsInUse);\n}\n\nfunction DeletePort(port) { //Deletes the port from the list of reserved or in-use ports\n\tfor (let i = 0; i < PortsInUse.length; i++) {\n\t\tif (PortsInUse[i].port === port.toString()) {\n\t\t\tPortsInUse.splice(i, 1);\n\t\t\tbreak;\n\t\t}\n\t}\n\tio.to('settings').emit('PortsInUse', PortsInUse);\n}\n\nstartUp();", "dangerousExampleEn": "1. process.on(\"uncaughtException\", function(err) {\n2. // log necessary error details to log files\n3. //process.exit();\n4. });\nLine 1: uncaughtException was used but the current status of the program is unknown because the process has not been terminated explicitly.", "safeExampleEn": "1. process.on(\"uncaughtException\", function(err) {\n2. // log necessary error details to log files\n3. process.exit();\n4. });\nLine 3: This is secure because the process is terminated after the errors are logged.", "contexts": [{"lineNo": 217, "eventType": "sink", "messageKey": "jschk.UNCAUGHT_EXCEPTION.JS.defect", "params": {}}]}} {"id": "d8827a5ad2ef786c3511dbe7dd567309084e6fc4318c4eab1ee64b29f7bd3ab0", "license": {"spdx": ["Apache-2.0"], "repo": "OB-POC/db-service", "path": "db.service.js", "repo_head_hexsha": "7a8ae0e06f0a6752e1377ab2963157155e87274a", "stack_hexsha": "85eb8b2a21674ec49384592e0175781111166caa", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of uncaughtException", "issueDescriptionEn": "Using uncaughtException enables a developer to handle errors that could not be addressed by a developer beforehand. However, the official node document specifies that it should only be used as a last resort. This is because uncaughtException cannot guarantee a program will close after an error occurs.\nuncaughtException should be used for logging purposes. After logging the errors, the process needs to be terminated using process.exit();.", "issueLineNumber": 41, "entireCode": "const path = require('path');\nconst fs = require('fs');\nconst {\n statusLogger\n} = require('./loggers');\n\nconst mockServer = require('./core');\n\nlet welcome = () => {\n let motdFile = path.resolve(__dirname, '.db-service.motd');\n const fs = require('fs');\n if (fs.existsSync(motdFile)) {\n let msg = fs.readFileSync(motdFile, 'utf-8');\n process.stdout.write('\\n' + msg + '\\n');\n } else {\n process.stdout.write('\\n=========== Mock DB service ===========\\n');\n }\n}\n\n\n\nlet initLog = () => {\n let logDirectory = path.join(__dirname, './', 'log');\n\n // ensure log directory exists\n fs.existsSync(logDirectory) || fs.mkdirSync(logDirectory);\n}\n\nlet startServer = () => {\n try {\n welcome();\n initLog();\n mockServer();\n } catch (err) {\n statusLogger.error(`Caught error in running DB service: ${err}`);\n }\n};\n\nstartServer();\n\nprocess.on('uncaughtException', function(err) {\n console.log('!!!!!!!!!!!!!!!!!!!!!! uncaughtException !!!!!!!!!!!!!!!!!!!');\n console.log(err);\n});", "dangerousExampleEn": "1. process.on(\"uncaughtException\", function(err) {\n2. // log necessary error details to log files\n3. //process.exit();\n4. });\nLine 1: uncaughtException was used but the current status of the program is unknown because the process has not been terminated explicitly.", "safeExampleEn": "1. process.on(\"uncaughtException\", function(err) {\n2. // log necessary error details to log files\n3. process.exit();\n4. });\nLine 3: This is secure because the process is terminated after the errors are logged.", "contexts": [{"lineNo": 41, "eventType": "sink", "messageKey": "jschk.UNCAUGHT_EXCEPTION.JS.defect", "params": {}}]}} {"id": "13f71f3e5432bfffd7cb7b1c6582ede4ee0b13633ed8f02a0f68774bc62f9980", "license": {"spdx": ["Apache-2.0"], "repo": "hurkanakbiyik/customer-solution-mean-es6", "path": "server.js", "repo_head_hexsha": "4b80d0bc20eb138fb53349e81819755aeccc347b", "stack_hexsha": "237d544d6b6e60a884b769eaecec21b311a269a6", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of uncaughtException", "issueDescriptionEn": "Using uncaughtException enables a developer to handle errors that could not be addressed by a developer beforehand. However, the official node document specifies that it should only be used as a last resort. This is because uncaughtException cannot guarantee a program will close after an error occurs.\nuncaughtException should be used for logging purposes. After logging the errors, the process needs to be terminated using process.exit();.", "issueLineNumber": 7, "entireCode": "const config = require('./config');\nconst express = require('express');\nconst bodyParser = require('body-parser');\nconst logger = require('./logger');\nconst auth = require('./security/auth');\n\nprocess.on('uncaughtException',function (error) {\n logger.error(error);\n});\n\n/** RUN */\nconst app = express();\nconst http = require('http').Server(app);\n\n/** socket run\n * very good for use websockets. I did not create any example for this.\n *\n */\nconst io = require('socket.io')(http);\nio.on('connection',function (client) {\n\n console.log(\"Client connection is ON!\");\n\n});\n\n/** mongo init */\nrequire(\"./databases/mongo/mongo-connect\");\n\n/**\n * CORS Handle\n * For client actions i need to define CORS.\n */\napp.all('*',function(req,res,next)\n{\n if (!req.get('Origin')) return next();\n res.set('Access-Control-Allow-Origin','*');\n res.set('Access-Control-Allow-Methods','GET,POST');\n res.set('Access-Control-Allow-Headers','X-Requested-With,Content-Type');\n if ('OPTIONS'.toLocaleLowerCase() === req.method.toLocaleLowerCase()) return res.sendStatus(200);\n next();\n});\n\n/**\n * Express.js need to use bodyparser for convert application/json data form.\n */\napp.use(bodyParser.json());\napp.use(bodyParser.urlencoded({ extended: false }));\n//app.use(express.static(__dirname + '/dist'));\n\n/**\n * AUTH CONTROL\n */\napp.use(auth({}));\n\n/**\n * ROUTES\n */\napp.get('/*', function(req, res){\n res.sendStatus(200);\n});\n\nlet companyRoute = require('./routes/company/company');\napp.use('/company', companyRoute);\n\n/**\n * ERROR HANDLING\n */\n\n// catch 404 and forward to error handler\napp.use(function (req, res, next) {\n let result = {\n error : new Error(req.originalUrl + \" not found.\" ),\n status : 500\n };\n next(result);\n});\n\n/**\n * RESULT FOR SERVICES\n */\napp.use(function(result, req, res, next) {\n if(result.error){\n res.status(500).send({\n status:500,\n message: result.error.message || 'server error',\n result : result.error,\n type:'internal'\n });\n }else{\n res.status(200);\n res.send(result);\n }\n\n});\n\n/**\n * START\n */\n\nhttp.listen(config.port,function (error) {\n if(error) logger.error(error);\n logger.info(\"Server running on http://localhost:\" + config.port);\n});", "dangerousExampleEn": "1. process.on(\"uncaughtException\", function(err) {\n2. // log necessary error details to log files\n3. //process.exit();\n4. });\nLine 1: uncaughtException was used but the current status of the program is unknown because the process has not been terminated explicitly.", "safeExampleEn": "1. process.on(\"uncaughtException\", function(err) {\n2. // log necessary error details to log files\n3. process.exit();\n4. });\nLine 3: This is secure because the process is terminated after the errors are logged.", "contexts": [{"lineNo": 7, "eventType": "sink", "messageKey": "jschk.UNCAUGHT_EXCEPTION.JS.defect", "params": {}}]}} {"id": "871335bdff5cf65d4d9ca70bf59ba141f82e0264e3db5af4b0ef5c5a1577493b", "license": {"spdx": ["MIT"], "repo": "tonite31/imboard", "path": "app.js", "repo_head_hexsha": "1587218ab9a186d60f99f0d08bbf3e3d1f417aa5", "stack_hexsha": "0e74b239b9935e0d94428971d73b53056f310226", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of uncaughtException", "issueDescriptionEn": "Using uncaughtException enables a developer to handle errors that could not be addressed by a developer beforehand. However, the official node document specifies that it should only be used as a last resort. This is because uncaughtException cannot guarantee a program will close after an error occurs.\nuncaughtException should be used for logging purposes. After logging the errors, the process needs to be terminated using process.exit();.", "issueLineNumber": 142, "entireCode": "global.useConsole = true;\nprocess.argv.forEach(function (val, index, array)\n{\n\tif(index == 2 && val == \"-deploy\")\n\t\tglobal.useConsole = false;\n});\n\nglobal._path =\n{\n\thome : __dirname,\n\tcontent : __dirname + \"/content\",\n\tsrc : __dirname + \"/src\",\n\tresources : __dirname + \"/resources\",\n\tlib : __dirname + \"/src/lib\",\n\tlog : __dirname + \"/logs\",\n\tuserdata : __dirname + \"/userdata\"\n};\n\t\nglobal._multipart = require('connect-multiparty');\nglobal._config = require(__dirname + '/resources/properties/config');\nglobal._aws = _config.aws;\nglobal._OAuth = _config.OAuth;\nglobal._code = _config.code;\n\nglobal._port = _config.server.port;\nglobal._modules = {};\n\n/**\n * \n */\nvar fs = require('fs');\nvar express = require('express');\nvar methodOverride = require('method-override');\nvar mysql = require('mysql');\nvar session = require('express-session');\nvar bodyParser = require(\"body-parser\");\nvar cookieParser = require(\"cookie-parser\");\nvar favicon = require('serve-favicon');\nvar https = require(\"https\");\n\nvar Immy = require(_path.lib + \"/Immy\");\nvar Logger = require(_path.lib + \"/Logger\");\nvar ModuleScanner = require(_path.lib + \"/ModuleScanner\");\nvar PropertyLoader = require(_path.lib + \"/PropertyLoader\");\nvar DataBindModuleLoader = require(_path.lib + \"/DataBindModuleLoader\");\nvar ServiceLoader = require(_path.lib + \"/ServiceLoader\");\n\nvar fs = require('fs');\nif(!fs.existsSync(_path.log))\n\tfs.mkdirSync(_path.log, 0777);\n\nif(!fs.existsSync(_path.userdata))\n\tfs.mkdirSync(_path.userdata, 0777);\n\n/**\n * global 객체 생성\n */\nglobal.pool = mysql.createPool(_config.jdbc);\nglobal._log = new Logger(_path.log + \"/debug.log\", _config.log.level, _config.log.colorize, useConsole);\nglobal._loge = new Logger(_path.log + \"/exception.log\", _config.log.level, _config.log.colorize, useConsole);\nglobal.ParameterBinder = require(_path.lib + \"/ParameterBinder.js\");\nglobal.Delegator = require(_path.lib + \"/Delegator.js\");\nglobal.Render = require(_path.lib + \"/Render.js\");\nglobal._async = require('async');\nglobal._utils = require(_path.lib + \"/Utils.js\");\nglobal._immy = new Immy(pool, _log, _loge);\n\n/**\n * 서버에 백그라운드로 올렸을때 오류 나는거때문에 콘솔 오버라이드\n */\nif(!global.useConsole)\n{\n\tconsole = {};\n\tfor(var key in _log)\n\t{\n\t\tconsole[key] = _log[key];\n\t}\n\n\tconsole.log = function()\n\t{\n\t\t_log.debug(arguments);\n\t};\n}\n\n/**\n * Express 설정\n */\nglobal.app = express();\n\nvar server = app.listen(_port, function()\n{\n\t_log.debug('Listening on port %d', server.address().port);\n});\n\napp.use('/content', express.static(_path.content));\napp.use('/resources', express.static(_path.userdata));\napp.use(bodyParser.urlencoded({extended: true}));\napp.use(bodyParser.json());\napp.use(cookieParser());\napp.use(session({ secret: 'imboard', resave: true, saveUninitialized: true}));\napp.use(methodOverride());\napp.use(require('express-domain-middleware'));\napp.use(function(req, res, next)\n{\n\tvar domain = require(\"domain\");\n\tvar reqDomain = domain.create();\n\n reqDomain.add(req);\n reqDomain.add(res);\n\n reqDomain.on('error', function (err)\n {\n \t_immy.releaseConnection();\n \t\n \t_loge.error(\"\\n\\n\");\n \t_loge.error(\"=================================================\");\n \t_loge.error(\"time : \" + new Date().toString());\n \t_loge.error(\"name : DomainException\");\n \t_loge.error(\"-------------------------------------------------\");\n \t_loge.error(err.stack);\n \t_loge.error(\"=================================================\\n\\n\");\n \t\n \tres.end(JSON.stringify({code : _code.EXCEPTION, message : err.stack}));\n });\n\n reqDomain.run(next);\n});\n\napp.use(function(err, req, res, next)\n{\n\t_loge.error(\"=================================================\");\n\t_loge.error(\"time : \" + new Date().toString());\n\t_loge.error(\"name : Exception\");\n\t_loge.error(\"-------------------------------------------------\");\n\t_loge.error(err.stack);\n\t_loge.error(\"=================================================\");\n\n\tres.statusCode = 500;\n\tres.end();\n});\n\nprocess.on('uncaughtException', function (err)\n{\n\t_loge.error(\"\\n\\n\");\n\t_loge.error(\"=================================================\");\n\t_loge.error(\"time : \" + new Date().toString());\n\t_loge.error(\"name : UncaughtException\");\n\t_loge.error(\"-------------------------------------------------\");\n\t_loge.error(err.stack);\n\t_loge.error(\"=================================================\\n\\n\");\n});\n\nvar FacebookIP = require(_path.lib + \"/IdentityProvider\").facebook;\nvar TwitterIP = require(_path.lib + \"/IdentityProvider\").twitter;\nvar GoogleIP = require(_path.lib + \"/IdentityProvider\").google;\n\nFacebookIP(app);\nTwitterIP(app);\nGoogleIP(app);\n\n_immy.scanTypeHandler(_path.src + \"/handler\");\n_immy.scanModel(_path.src + \"/vo\");\n_immy.scanQuery(_path.resources + \"/mybatis\");\n\nModuleScanner.setLogger(_log);\nModuleScanner.scanRouter(_path.src + \"/router\");\n\nDataBindModuleLoader.load(_path.src + \"/module\");\n\nif(fs.existsSync(_path.content + \"/frame/\" + _config.frame + \"/src/module\"))\n\tDataBindModuleLoader.load(_path.content + \"/frame/\" + _config.frame + \"/src/module\");\nif(fs.existsSync(_path.content + \"/frame/\" + _config.frame + \"/src/router\"))\n\tModuleScanner.scanRouter(_path.content + \"/frame/\" + _config.frame + \"/src/router\");\nif(fs.existsSync(_path.content + \"/frame/\" + _config.frame + \"/src/service\"))\n\tServiceLoader.load(_path.content + \"/frame/\" + _config.frame + \"/src/service\");\n\nPropertyLoader.load(__dirname);", "dangerousExampleEn": "1. process.on(\"uncaughtException\", function(err) {\n2. // log necessary error details to log files\n3. //process.exit();\n4. });\nLine 1: uncaughtException was used but the current status of the program is unknown because the process has not been terminated explicitly.", "safeExampleEn": "1. process.on(\"uncaughtException\", function(err) {\n2. // log necessary error details to log files\n3. process.exit();\n4. });\nLine 3: This is secure because the process is terminated after the errors are logged.", "contexts": [{"lineNo": 142, "eventType": "sink", "messageKey": "jschk.UNCAUGHT_EXCEPTION.JS.defect", "params": {}}]}} {"id": "327de556f50a47be1a72eb679db47b457c625f3b41c67821302d55e63a738317", "license": {"spdx": ["MIT"], "repo": "xiaoxunyao/veui-docs", "path": "app.js", "repo_head_hexsha": "0f7ef86edb988ec7ca8267fb9962b114b39593f3", "stack_hexsha": "29409ced05260d1507b94f1ac226c10ced5a37fa", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of uncaughtException", "issueDescriptionEn": "Using uncaughtException enables a developer to handle errors that could not be addressed by a developer beforehand. However, the official node document specifies that it should only be used as a last resort. This is because uncaughtException cannot guarantee a program will close after an error occurs.\nuncaughtException should be used for logging purposes. After logging the errors, the process needs to be terminated using process.exit();.", "issueLineNumber": 10, "entireCode": "const express = require('express')\nconst nuxt = require('nuxt')\nconst { Nuxt, Builder } = nuxt\n\nconst app = express()\nconst host = process.env.HOST || '127.0.0.1'\nconst port = process.env.PORT || 8080\n\n// uncaughtException 避免程序崩溃\nprocess.on('uncaughtException', function (err) {\n console.error(err)\n try {\n let killTimer = setTimeout(function () {\n process.exit(1)\n }, 10000)\n killTimer.unref()\n server.close()\n } catch (e) {\n console.error('Fail to close server safely. ', e.stack)\n }\n})\n\napp.set('port', port)\n\n// Import and Set Nuxt.js options\nconst config = require('./nuxt.config.js')\nconfig.dev = !(process.env.NODE_ENV === 'production')\n\n// Init Nuxt.js\nconst server = new Nuxt(config)\n\n// Build only in dev mode\nif (config.dev) {\n const builder = new Builder(server)\n builder.build()\n}\n\n// Give nuxt middleware to express\napp.use(server.render)\n\n// Listen the server\napp.listen(port, host)\nconsole.log('Server listening on ' + host + ':' + port) // eslint-disable-line no-console", "dangerousExampleEn": "1. process.on(\"uncaughtException\", function(err) {\n2. // log necessary error details to log files\n3. //process.exit();\n4. });\nLine 1: uncaughtException was used but the current status of the program is unknown because the process has not been terminated explicitly.", "safeExampleEn": "1. process.on(\"uncaughtException\", function(err) {\n2. // log necessary error details to log files\n3. process.exit();\n4. });\nLine 3: This is secure because the process is terminated after the errors are logged.", "contexts": [{"lineNo": 10, "eventType": "sink", "messageKey": "jschk.UNCAUGHT_EXCEPTION.JS.defect", "params": {}}]}} {"id": "5659f39e74d4671e2ccb457d6e333bc65980347f6daae7a679f36ff915f15e78", "license": {"spdx": ["MIT"], "repo": "andela-jejezie/peopleProject", "path": "node_modules/karma/node_modules/http-proxy/test/examples-test.js", "repo_head_hexsha": "25a056df5606e132387a5f8582b4e1d688cc080f", "stack_hexsha": "36beb89a99f7dd29cbbacb943f5145c1da2e6133", "match": "repo_path"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of uncaughtException", "issueDescriptionEn": "Using uncaughtException enables a developer to handle errors that could not be addressed by a developer beforehand. However, the official node document specifies that it should only be used as a last resort. This is because uncaughtException cannot guarantee a program will close after an error occurs.\nuncaughtException should be used for logging purposes. After logging the errors, the process needs to be terminated using process.exit();.", "issueLineNumber": 16, "entireCode": "/*\n * examples.js: Tests which ensure all examples do not throw errors.\n *\n * (C) 2010, \n *\n */\n\nvar vows = require('vows')\n macros = require('./macros'),\n examples = macros.examples;\n\n//\n// Suppress `EADDRINUSE` errors since\n// we are just checking for require-time errors\n//\nprocess.on('uncaughtException', function (err) {\n if (err.code !== 'EADDRINUSE') {\n throw err;\n }\n});\n\nvows.describe('node-http-proxy/examples').addBatch(\n examples.shouldHaveDeps()\n).addBatch(\n examples.shouldHaveNoErrors()\n).export(module);", "dangerousExampleEn": "1. process.on(\"uncaughtException\", function(err) {\n2. // log necessary error details to log files\n3. //process.exit();\n4. });\nLine 1: uncaughtException was used but the current status of the program is unknown because the process has not been terminated explicitly.", "safeExampleEn": "1. process.on(\"uncaughtException\", function(err) {\n2. // log necessary error details to log files\n3. process.exit();\n4. });\nLine 3: This is secure because the process is terminated after the errors are logged.", "contexts": [{"lineNo": 16, "eventType": "sink", "messageKey": "jschk.UNCAUGHT_EXCEPTION.JS.defect", "params": {}}]}} {"id": "973e01a4910ff0450275ee51c871219afbbe39c1b3fe2f74fa1a7ae3460c42ed", "license": {"spdx": ["Apache-2.0"], "repo": "facebookarchive/jsgamebench", "path": "lib/graph.js", "repo_head_hexsha": "81c470ed73bc368501e3a0bd54fea1656bf3e651", "stack_hexsha": "9a1efda084fe0cae58db0e2b6807159c0c01db5a", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of uncaughtException", "issueDescriptionEn": "Using uncaughtException enables a developer to handle errors that could not be addressed by a developer beforehand. However, the official node document specifies that it should only be used as a last resort. This is because uncaughtException cannot guarantee a program will close after an error occurs.\nuncaughtException should be used for logging purposes. After logging the errors, the process needs to be terminated using process.exit();.", "issueLineNumber": 1, "entireCode": "process.on('uncaughtException', function(err) {\n console.log(err);\n});\n\nvar base_url = 'pirateninjachess.com/chess';\n\nfunction str_from_req(req)\n{\n return \"req: method=\"+req.method+\" httpVersion=\"+req.httpVersion+\" url=\"+req.url+\"\\nheaders=\"+util.dir(req.headers) +\"\\nbody=\"+req.body;\n}\n\n\nfunction dict_from_keyvals_str(str, delim) {\n var res = [];\n for(var i = 0; i < str.length; ++i) {\n var tmp = str[i].split(delim);\n res[tmp[0]] = unescape(tmp[1]);\n }\n return res;\n}\n\nfunction fbinfo_from_cookie(c) {\n if(c) {\n console.log('cookie: ' + c);\n var d = c.substring(c.indexOf('=')+2,c.length-1);\n var e = d.split('&');\n return dict_from_keyvals_str(e,'=');\n }\n}\n\nexports.fbinfo_from_cookie = fbinfo_from_cookie;\n\n// url=/cheevo_update?cheevo=&score=\nfunction params_from_url(url)\n{\n var a = url.split('?')\n if(a.length <= 0)\n return null;\n var b = a[1].split('&')\n return dict_from_keyvals_str(b,'=');\n}\n\n\nfunction post_handler(request, callback) {\n var body = '';\n\n if (request.method == 'POST') {\n request.addListener('data', function(chunk)\t{\n body+= chunk;\n });\n\n request.addListener('end', function()\t{\n sys.debug(body); \n callback(body);\n });\n };\n}\n\nvar user_info = [];\n\n// use this to query data from open graph\nfunction graph_get(path,end_cb) {\n // sys.debug('graph_get:' + path);\n data = '';\n https.get(\n { \n host: 'graph.facebook.com', \n path: path \n }, \n function(res) {\n res.on(\n 'data',\n function(d) {\n data += d;\n }\n );\n res.on(\n 'end',\n function () \n {\n end_cb(data); \n }\n );\n }\n ).on(\n 'error', \n function(e) {\n console.error(e);\n }\n );\n}\n\nfunction graph_post(path, body, end_cb) {\n sys.debug('graph_post:' + path + ' body: ' + body);\n var data = '';\n var graph_req = https.request(\n { \n host: 'graph.facebook.com', \n method: 'POST',\n path: path\n }, \n function(res) {\n res.on(\n 'data',\n function(d) {\n //sys.debug('graph data:'+d);\n data += d;\n }\n );\n res.on(\n 'end',\n function () \n {\n end_cb(data); \n }\n );\n }\n )\n graph_req.on(\n 'error', \n function(e) {\n console.error(e);\n }\n );\n graph_req.end(body);\n}\n\n\nfunction og_action_get(res, action_name, access_token) \n{\n graph_get(\n '/me/superfbrps:'+action_name+'?access_token='+escape(access_token), \n function(d) {\n sys.debug('og_action_get:'+d);\n res.end ('og_action_get:'+d);\n } \n );\n}\n\nfunction og_action_create(res, action_name, object_name, access_token)\n{\n var body = 'to='+escape(base_url)+'/og/'+object_name+'.shtml'+'&'\n + 'access_token='+escape(access_token);\n\n graph_post(\n '/me/chess_ext:'+action_name,\n body,\n function(d) {\n sys.debug('og_action_create:'+action_name+':'+d);\n res.end ('og_action_create:'+action_name+':'+d);\n } \n );\n}\n\nfunction og_score_set(res, score, access_token, app_secret)\n{\n var body =\n 'score='+escape(score)\n + '&access_token='+escape(access_token)\n + '&client_secret='+app_secret;\n\n graph_post(\n '/me/games.scores?',\n body,\n function(d) {\n sys.debug('og_score_set:'+score+':'+d);\n res.end ('og_score_set:'+score+':'+d);\n } \n );\n}\n\nfunction og_score_delete_all(access_token)\n{\n}\n\nfunction getCheevos(fb_info, res) {\n graph_get(\n '/me/games.achieves?access_token='+escape(fb_info.access_token),\n function (data) {\n console.log('data: ' + data);\n res.end(data);\n }\n );\n return;\n}\n\nfunction addCheevo(fb_info, res, cheevo) {\n var cheevo_url = escape(base_url + '/chess/cheevo/' + cheevo +'.shtml');\n var path = '/me/games.achieves?';\n var body = 'achievement='+cheevo_url+'&access_token='+escape(fb_info.access_token)+'&client_secret='+Server.fb_app_info.chess.secret;\n var graph_req = graph_post(\n path,\n body,\n function(d) {\n sys.debug('og achieves response:'+d);\n res.end('og achieves response: '+cheevo+' response: '+d);\n getCheevos(fb_info, res);\n }\n );\n}\n\nfunction handler(fb_info, res, cmd_str) {\n var cmds = cmd_str.split(' ');\n var cmd = cmds[0];\n switch(cmd) {\n case 'addcheevo':\n addCheevo(fb_info, res, cmds[1]);\n break;\n case 'addaction':\n //og_action_create(res,params.action,params.object,fb_info.access_token);\n og_action_create(res,cmds[1],cmds[2],fb_info.access_token);\n }\n}\n\nfunction req_handler(command, req, res)\n{\n var fb_info = { access_token : 0 };\n \n if('cheevo_grant' == command) {\n // TODO: check list of available cheevos\n sys.debug('cheevo_update');\n\n var params = params_from_url(req.url);\n var cheevo = params.cheevo;\n var cheevo_url = escape('pirateninjachess.com/chess/cheevo/' + cheevo + '.shtml');\n var path = '/me/games.achieves?';\n var body = 'achievement='+cheevo_url+'&access_token='+escape(fb_info.access_token)+'&client_secret='+Server.fb_app_info.app_secret;\n var graph_req = graph_post(\n path,\n body,\n function(d) {\n sys.debug('og achieves response:'+d);\n res.end('og achieves response: '+cheevo+' response: '+d);\n }\n );\n return;\n }\n else if('cheevo_get' == command) {\n graph_get(\n '/me/games.achieves?access_token='+escape(fb_info.access_token),\n function (data) {\n res.end(data);\n }\n );\n return;\n }\n else if('action_grant' == command) {\n // TODO: check list of available actions\n sys.debug('action_grant');\n var params = params_from_url(req.url);\n og_action_create(res,params.action,params.object,fb_info.access_token);\n return;\n }\n else if('action_get' == command) {\n // TODO: check list of available actions\n sys.debug('action_get');\n var params = params_from_url(req.url);\n og_action_get(res,params.action,fb_info.access_token);\n return;\n }\n else if('score_set' == command) {\n // https://graph.facebook.com/me/games.scores?\n sys.debug('score_set');\n var params = params_from_url(req.url);\n og_score_set(res,params.score,params.access_token,app_secret);\n return;\n }\n sys.debug('unkown command pathname is '+pathname+' root is ' + command); \n}\n\n\n\nexports.handler = handler;\nexports.addCheevo = addCheevo;\n", "dangerousExampleEn": "1. process.on(\"uncaughtException\", function(err) {\n2. // log necessary error details to log files\n3. //process.exit();\n4. });\nLine 1: uncaughtException was used but the current status of the program is unknown because the process has not been terminated explicitly.", "safeExampleEn": "1. process.on(\"uncaughtException\", function(err) {\n2. // log necessary error details to log files\n3. process.exit();\n4. });\nLine 3: This is secure because the process is terminated after the errors are logged.", "contexts": [{"lineNo": 1, "eventType": "sink", "messageKey": "jschk.UNCAUGHT_EXCEPTION.JS.defect", "params": {}}]}} {"id": "e5434bf99cf175580f71299f6cd073a421116bb660b8027a3518bb93ced99714", "license": {"spdx": ["MIT"], "repo": "sumanjs/suman", "path": "test/src/exp/promises-patch/two.test.js", "repo_head_hexsha": "c7ad5c3e12b7283d284471f5cd0c396e9add7ca9", "stack_hexsha": "e41a5cd638a6daf671132e7c9888512a4e49da6d", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of uncaughtException", "issueDescriptionEn": "Using uncaughtException enables a developer to handle errors that could not be addressed by a developer beforehand. However, the official node document specifies that it should only be used as a last resort. This is because uncaughtException cannot guarantee a program will close after an error occurs.\nuncaughtException should be used for logging purposes. After logging the errors, the process needs to be terminated using process.exit();.", "issueLineNumber": 12, "entireCode": "const then = Promise.prototype.then;\nPromise.prototype.then = function (fn1, fn2) {\n\n if (process.domain) {\n fn1 = fn1 && process.domain.bind(fn1);\n fn2 = fn2 && process.domain.bind(fn2);\n }\n\n return then.call(this, fn1, fn2);\n};\n\nprocess.on('uncaughtException', function(err){\n console.log(' This is uncaught => ', err);\n});\n\n\nconst domain = require('domain');\n\nconst d = domain.create();\n\nd.on('error', function(err){\n console.error(' => Domain caught => ',err);\n});\n\n\nd.run(function(){\n\n new Promise(function(resolve,reject){\n process.nextTick(function(){\n throw new Error('rooo');\n })\n });\n\n});", "dangerousExampleEn": "1. process.on(\"uncaughtException\", function(err) {\n2. // log necessary error details to log files\n3. //process.exit();\n4. });\nLine 1: uncaughtException was used but the current status of the program is unknown because the process has not been terminated explicitly.", "safeExampleEn": "1. process.on(\"uncaughtException\", function(err) {\n2. // log necessary error details to log files\n3. process.exit();\n4. });\nLine 3: This is secure because the process is terminated after the errors are logged.", "contexts": [{"lineNo": 12, "eventType": "sink", "messageKey": "jschk.UNCAUGHT_EXCEPTION.JS.defect", "params": {}}]}} {"id": "05349d2524e571c01ae7be7b780d7463cf74967d5e80720481e66bae0eb093bb", "license": {"spdx": ["MIT"], "repo": "Tyaisurm/DECSV", "path": "DECSV_project/app.js", "repo_head_hexsha": "76eb7cfed44230d1ce1895b6322659a9ac51d659", "stack_hexsha": "86cc6967fd36a60d4a99281b8e8257a915118596", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of uncaughtException", "issueDescriptionEn": "Using uncaughtException enables a developer to handle errors that could not be addressed by a developer beforehand. However, the official node document specifies that it should only be used as a last resort. This is because uncaughtException cannot guarantee a program will close after an error occurs.\nuncaughtException should be used for logging purposes. After logging the errors, the process needs to be terminated using process.exit();.", "issueLineNumber": 3, "entireCode": "'use strict';\n//////////////////////////////////// CUSTOM ERROR MESSAGE\nprocess.on('uncaughtException', function (err) {\n //process.exit(1);\n const electron = require('electron');\n const uncaugetdia = electron.dialog ? electron.dialog : electron.remote.dialog;\n const app = electron.app ? electron.app : electron.remote.app;\n const shell = electron.shell;\n logger.error(\"Uncaught Exception!\");\n logger.error(err);\n var uncaughtoptions = {};\n uncaughtoptions = {\n type: 'error',\n title: \"Uncaught Exception\",\n message: \"Unknown error occurred!\",\n detail: \"Something unexpected happened! Please check wiki-page if this is a known problem:\\r\\n#### ERROR #####\\r\\n\" + err,\n buttons: [\"Close application\", \"Open Wiki\"]\n }\n if (mainWindow === null) {\n uncaugetdia.showMessageBox(uncaughtoptions, function (index) {\n // no need to deal with anything.... just notifying user\n if (index === 1) {\n //open wiki\n shell.openExternal(\"https://github.com/Tyaisurm/DECSV/wiki\");\n logger.error(\"Closing application because of error....\");\n app.exit();\n } else {\n // close, do nothing\n logger.error(\"Closing application because of error....\");\n app.exit();\n }\n });\n } else {\n uncaugetdia.showMessageBox(mainWindow, uncaughtoptions, function (index) {\n // no need to deal with anything.... just notifying user\n if (index === 1) {\n //open wiki\n shell.openExternal(\"https://github.com/Tyaisurm/DECSV/wiki\");\n logger.error(\"Closing application because of error....\");\n app.exit();\n } else {\n // close, do nothing\n logger.error(\"Closing application because of error....\");\n app.exit();\n }\n });\n }\n});\n////////////////////////////////////\n\nlet openWindow = null;\nlet mainWindow = null;\nlet aboutWindow = null;\nlet i18n_app = null;\n\nconst electron = require('electron');\nconst ipcMain = electron.ipcMain;\nconst app = electron.app;\nconst logger = require('electron-log');\nconst BrowserWindow = electron.BrowserWindow; \nconst path = require('path');\nconst url = require('url');\nconst fs = require('fs');\nconst autoUpdater = require(\"electron-updater\").autoUpdater;\nconst dialog = electron.dialog;\nconst windowStateKeeper = require('electron-window-state');\n//const Store = require('electron-config');\nconst Store = require(\"electron-store\");\nconst XLSX = require('xlsx');\nconst charDetector = require('chardet');\nconst charDetector123 = require('charset-detector');\nconst Iconv = require('iconv').Iconv;\n\nvar current_project = null;\nvar pre_project = null;\nvar showExitPrompt = true;\n\nconst parseUtils = require(\"./assets/js/parseUtils.js\");\n\n///////////////////////////////////////////////////////////\n\n///////////////////////////////////////////////////////////\n\nif (require('electron-squirrel-startup')) { app.quit(); }\n\n/////////////////////////////// SETTING LOGGER LEVELS\nlogger.transports.file.level = \"verbose\";\nlogger.transports.console.level = \"silly\";\n//logger.transports.file.appName = 'SLIPPS Teacher Tool';\n///////////////////////////////\n\nautoUpdater.logger = logger;\n\n//autoUpdater.allowPrerelease = true; // flag for beta....\n//autoUpdater.autoDownload = false; // flag for handling updating manually, instead of automatically testing...\n\nconst gotTheLock = app.requestSingleInstanceLock();\n\nif (!gotTheLock) {\n logger.info(\"Was unable to get a single instance lock! Quitting application...\");\n app.quit();\n} else {\n app.on('second-instance', (event, commandLine, workingDirectory) => {\n logger.info(\"Tried to create second instance!\");\n // Someone tried to run a second instance, we should focus our window.\n if (mainWindow !== null) {\n logger.info(\"Main maindow was not null! Restoring and focusing...\");\n if (mainWindow.isMinimized()) {\n mainWindow.restore();\n }\n mainWindow.focus();\n\n // here take [1] command line arg (calling location / opened file) and try to open\n // HOWEVER, if there is a file open atm, show notification that current needs to be closed...\n // if nothing is wrong, let's try 1) switch to \"open project\"-view, 2) try to open arg[1] file, 3) notify if worked or not\n // THIS ABOVE NEEDS TO BE IN >win32< \n //\n // otherwise, you need to listen event in MacOS 'open-file' with event.preventDefault()\n // in windows parse process.argv\n logger.info(\"Testing if we need to open a new project...\");\n if (process.platform == 'win32' && commandLine.length >= 2) {\n var openFilePath = commandLine[1];\n if (current_project !== null) {\n // there is a project open\n logger.warn(\"Tried to open new project, while old one still exits!\");\n logger.info(\"# Old: \" + current_project);\n logger.info(\"# New: \" + openFilePath);\n // create dialog and notify to exit current project before opening new projects...\n var options = {\n type: 'info',\n title: \"Project open\",\n message: \"Unable to open new project while there is one open!\",\n detail: \"Please close the current project, and try opening again.\",\n buttons: [i18n_app.__('conf-ok', true)]\n };\n dialog.showMessageBox(mainWindow, options, function (index) {\n // no need to deal with anything.... just notifying user\n if (index === 1) {\n //\n } else {\n // close, do nothing\n }\n });\n } else {\n //no project exist... need to force opening\n logger.info(\"No project exists! Need to force open new project at mainWindow...\");\n mainWindow.webContents.send(\"force-open-project\", openFilePath);\n }\n\n } else {\n // do nothing\n logger.warn(\"Platform is not win32, or argv.length is not >=2!\");\n }\n } else {\n // no mainwindow! if we are opening project, we are settings this variable just in case\n logger.info(\"No main window exists! Setting variable just in case...\");\n if (process.platform == 'win32' && commandLine.length >= 2) {\n pre_project = commandLine[1];\n logger.info(\"[SECOND INSTANCE] Settings main process pre_project variable(win32): \" + pre_project);\n } else {\n logger.warn(\"[SECOND INSTANCE] Platform is not win32, or argv.length is not >=2!\");\n }\n /*\n if (process.platform == 'darwin') {\n logger.info(\"Platform was 'darwin'! Opening new mainWindow...\");\n createMainWindow();\n }\n */\n\n }\n });\n\n // saving command line parameter (file to be opened...)\n if (process.platform == 'win32' && process.argv.length >= 2) {\n if (process.argv[1] !== \"--updated\") { pre_project = process.argv[1]; }// since this is put here after updating\n logger.info(\"[FIRST INSTANCE] Settings main process pre_project variable(win32): \" + pre_project);\n } else {\n logger.warn(\"[FIRST INSTANCE] Platform is not win32, or argv.length is not >=2!\");\n }\n\n /* Called when application has finished loading */\n app.on('ready', () => {\n //setTimeout(function () {\n if (process.platform === 'win32') {\n //\n }\n else if (process.platform === 'linux') {\n //\n }\n else if (process.platform === 'darwin') {\n //\n }\n else {\n //well then, you are done for :x\n }\n logger.info('app ready');\n\n logger.debug(\"setupTranslations(app.js)\");\n i18n_app = new (require('./assets/translations/i18n'))(true);\n showExitPrompt = true;\n\n logger.debug(\"checking first usage...\");\n var options = {\n name: \"app-configuration\",\n cwd: app.getPath('userData')\n }\n const store = new Store(options);\n var firstuse = store.get('first-use');\n //logger.debug(firstuse);\n //logger.debug(typeof(firstuse));\n\n // Checking if the app json data file shows that the program has been opened before\n if (firstuse) {\n logger.info(\"######################################################\");\n logger.info(\"WELCOME! This app is now started for the first time :)\");\n logger.info(\"######################################################\");\n store.set('first-use', false);\n }\n else {\n logger.info(\"App has been started before!\");\n }\n createWin();\n //}, 0)\n });\n}\n\n/* Handle opening files in program (while not open before; that is above in the makeSingleInstance callback) */\napp.on('will-finish-launching', function () {\n app.on('open-file', function (ev, path) { // this works when called on MacOS\n event.preventDefault();\n if (process.platform == 'darwin') {\n pre_project = path;\n logger.info(\"Settings main process pre_project variable(darwin): \" + pre_project);\n\n } else {\n // nothing\n logger.info(\"Open-file event fired, but platform was not 'darwin'!\");\n logger.info(\"FILE: \" + path);\n }\n });\n app.on('open-url', function (event, url) {// yea.... we don't need this that much.. need to have for MacOS though\n event.preventDefault();\n logger.info(\"Open-url event fired! Ignoring...\");\n //log(\"open-url event: \" + url)\n\n // handle if argument is proper file or not\n var sourcelink = url;\n logger.info(\"LINK: \" + url);\n\n //dialog.showErrorBox('open-url', `You arrived from: ${url}`)\n });\n});\n\n/* These settings are here, so we can control what settings components get and to validate saved settings */\n/* Allows windows fetch settings from one place*/\n/* Returns array, where there is 2 stringify-ed JSONs */\nglobal.getSettings = function () {\n logger.debug(\"getSettings\");\n var apppath = app.getPath('userData');\n var returnable = {\n \"app\": {}\n };\n var config1 = {\n name: \"app-configuration\",\n cwd: apppath\n }\n var store1 = new Store(config1);\n var json1 = store1.store;\n try {\n json1 = JSON.stringify(json1);\n json1 = JSON.parse(json1);\n } catch (err) {\n json1 = {};\n }\n \n if (parseUtils.validateSettings(json1,1)) {\n // settings valid; giving them out\n //returnable.push(json1);\n } else {\n // settings invalid; need to give out defaults\n logger.warn(\"GetSettings() app settings invalid!\");\n json1 = {\n \"app-lang\": \"en\",\n \"first-use\": false,\n \"app-version\": app.getVersion(),\n \"latest-update-check\": null,\n \"latest-update-install\": null,\n \"zoom\": 100,\n \"edits\": [\n false,\n null\n ],\n \"enabled-keywordlists\": [\"en\"]\n };\n //returnable.push(json1);\n }\n\n returnable.app = json1;\n \n return returnable;\n\n};\n/* Allows windows to set settings from single place */\n/* 0 is settings for application, 1 is settings for keywords */\nglobal.setSettings = function (settings = {}) {\n logger.debug(\"setSettings\");\n //logger.debug(settings);\n var json1 = {};\n //var json2 = {};\n if (!(settings.constructor === {}.constructor)) {\n //settings is not an json object\n return [false,1];\n }\n else if (Object.keys(settings).length !== 1) {\n //settings keys not size of {1}<< 2\n return [false,2];\n }\n if (!settings.hasOwnProperty(\"app\")) {// || !settings.hasOwnProperty(\"kw\")) {\n // no app or kw object in settings object\n return [false, 3];\n }\n json1 = settings.app;\n //json2 = settings.kw;\n \n //\n if (parseUtils.validateSettings(json1,1)) {\n // settings valid - now we can save them\n } else {\n // settings invalid; saving default settings\n logger.warn(\"SetSettings() app settings invalid!\");\n json1 = {\n \"app-lang\": \"en\",\n \"first-use\": false,\n \"app-version\": app.getVersion(),\n \"latest-update-check\": null,\n \"latest-update-install\": null,\n \"zoom\": 100,\n \"edits\": [\n false,\n null\n ],\n \"enabled-keywordlists\": []\n };\n }\n\n var apppath = app.getPath('userData');\n var config1 = {\n name: \"app-configuration\",\n cwd: apppath\n }\n var store1 = new Store(config1);\n store1.store = json1;\n //\n\n /* CALL FORCE UPDATE TO ALL WINDOWS HERE!!!!!!!! */\n\n forceInterfaceUpdate(json1);//, json2)\n\n};\n\n/* sends info to all webContents with proper */\nfunction forceInterfaceUpdate(intset1 = {}) {//, intset2 = {}) {\n logger.debug(\"forceInterfaceUpdate (app.js)\");\n\n if (!parseUtils.validateSettings(intset1, 1)) {\n //\n //logger.debug(\"FAIL 1\");\n return false;\n }\n\n var webconts = electron.webContents.getAllWebContents();\n\n var tobesent = {\n \"app\": intset1\n }\n //logger.debug(webconts);\n //logger.debug(webconts.length);\n for (var id = 0; id < webconts.length; id++) {\n // send current settings to each renderer process (they need listener for this!!!)\n webconts[id].send('force-interface-update', tobesent);\n }\n return true;\n}\n\n/*\nLogger logs are on %AppData%\\Roaming\\*package: productName*\\log.log (or \"old\" version of the same) by default on windows systems.\nThe app itself will be installed into %AppData%\\Local\\*package: name*.\n\nelectron-store will save data as JSON into app.getPath(userData), which should be %AppData%\\Roaming\\*package: productName*\n*/\n\n///////////////////// Create directories to user's Documents-folder, and set up some files and directories in applications AppData/Roaming folder\ncreateDocStructure();\ncreateAppStructure();\n/////////////////////\n\n//////////////////////////////////////////////////////////// IPC MAIN LISTENERS\n\nipcMain.on('import-wiz-return', function (event, arg) {\n logger.debug(\"import-wiz-return\");\n var mode = arg[1];\n arg = arg[0];\n if (mode === 0) {\n // received importable file!\n if (!(arg instanceof Array)) {// not array\n logger.error(\"Main process file import array not instanceof Array!\");\n arg = [null, null, null, null]\n }\n if (arg.length !== 4) {// array not length of 3\n logger.error(\"Main process file import array not length of 3\");\n arg = [null, null, null, null]\n }\n //logger.debug(arg[0] + \" - \"+typeof(arg[0]));\n //logger.debug(arg[1] + \" - \" + typeof (arg[1]));\n\n // [tool, delimiter, encoding, filepath]\n var processeddata = readSourceFile(arg[0], arg[1], arg[2], arg[3]); // will be [false/true, status_code, result_array]\n\n if (mainWindow !== null) {\n //\n logger.info(\"Sending file import raw array to import wizard...\");\n event.sender.send(\"import-wiz-reply\", processeddata);\n } else {\n logger.error(\"MainWindow not open, but we tried to import file!\");\n event.sender.send(\"import-wiz-reply\", [null, null, null]);\n //do nothing\n }\n } else if (mode === 1) {\n //received selected lines to be imported.... parsing to proper form...\n //mainWindow.webContents.send(\"output-to-chrome-console\", arg[1]);\n var completearr = parseUtils.parseArray(arg[0], arg[1], arg[3]);// [tool, arr, survey_version] // returns [boolean, statuscode, arr] CURRENTLY USING PLACEHOLDERS!\n if (completearr[0]) {\n //mainWindow.webContents.send(\"output-to-chrome-console\", completearr[2]);\n\n // logger.error(\"DENIED! UNABLE TO USE BECAUSE NOT IMPLEMENTED!\");\n //event.sender.send(\"import-wiz-result\", [false, completearr[1], \"{}\"]);\n //return;\n\n try {\n var htmljson = parseUtils.readAndParseSource(completearr[2],arg[2]);\n var htmlstring = JSON.stringify(htmljson);\n event.sender.send(\"import-wiz-result\", [true, 0, htmlstring]);\n } catch (err) {\n logger.error(err);\n logger.error(\"Failed to parse import event JSON into string at import-wiz-return!\");\n event.sender.send(\"import-wiz-result\", [false, -1, \"{}\"]);\n }\n } else {\n logger.error(\"Unable to parse import! Reason: \" + completearr[1]);\n event.sender.send(\"import-wiz-result\", [false, completearr[1], \"{}\"]);\n }\n } else {\n logger.error(\"Invalid mode '\"+mode+\"' in ipcMain import-wiz-return\");\n }\n});\n\n/* This is called to get the file that was tried to use with the application NEEDSTOBECHANGED */\nipcMain.on('get-ext-file-data', function (event, arg) {// This is used to \"ask\" what the current file / process argument[1] was. \"null\" is returned default\n event.returnValue = pre_project;\n});\n/* This is used to \"update\" variable here to keep track if project is open or not */\nipcMain.on('set-project-status', function (event, arg) {\n current_project = arg;\n});\n\n// create project\nipcMain.on('async-create-project', (event, project_name, project_country, project_lang) => {\n logger.debug(\"async-create-project (at app.js)\");\n var results = createNewProject(project_name, project_country, project_lang);\n event.sender.send('async-create-project-reply', results);\n});\n\n/* create main window (called from openWindow) */\nipcMain.on('async-creat-mainwindow', (event, arg) => {\n setTimeout(function () { createMainWindow(); }, 2000);\n});\n\n////////////////////////////////////////////////////////////\n\n/* Creates application's folders into user's Documents-folder */\nfunction createDocStructure() {\n logger.debug(\"createDocStructure\");\n var docpath = app.getPath('documents');\n try {\n if (!fs.existsSync(path.join(docpath, 'SLIPPS Teacher Tool'))) {\n logger.info(\"No app documents folder found! Creating one...\");\n fs.mkdirSync(path.join(docpath, 'SLIPPS Teacher Tool'));\n }\n if (!fs.existsSync(path.join(docpath, 'SLIPPS Teacher Tool\\\\Projects'))) {\n logger.info(\"No app PROJECTS folder found! Creating one...\");\n fs.mkdirSync(path.join(docpath, 'SLIPPS Teacher Tool\\\\Projects'));\n }\n if (!fs.existsSync(path.join(docpath, 'SLIPPS Teacher Tool\\\\Output'))) {\n logger.info(\"No app OUTPUT folder found! Creating one...\");\n fs.mkdirSync(path.join(docpath, 'SLIPPS Teacher Tool\\\\Output'));\n }\n } catch (err) {\n logger.error(\"Unable to create file structure into user's documents! Reason: \" + err.message);\n }\n}\n\n/* Creates application's folders and settings-files into user's AppData-folder */\nfunction createAppStructure(mode = 0) {\n logger.debug(\"createAppStructure\");\n \n //var demostatus = false;\n var apppath = app.getPath('userData');\n var appconfigcheck = false;\n if (fs.existsSync(path.join(apppath, 'app-configuration.json'))) {\n try {\n appconfigcheck = !fs.statSync(path.join(apppath, 'app-configuration.json')).isDirectory()\n } catch (err) {\n logger.error(\"Error while using statSync! Reason: \" + err.message);\n }\n }\n\n if (!appconfigcheck) {\n logger.info(\"No app configuration file found! Creating one with defaults...\");\n let CA1_options = {\n defaults: {\n \"app-lang\": \"en\",\n \"first-use\": true,\n \"latest-update-check\": null,\n \"latest-update-install\": null,\n \"zoom\":100,\n \"app-version\": app.getVersion(),\n \"edits\": [false, null],\n \"enabled-keywordlists\": [\"en\"]\n },\n name: \"app-configuration\",\n cwd: apppath\n }\n const CA1_store = new Store(CA1_options);\n }\n else {\n logger.info(\"App configuration file found! Checking version...\");\n let CA1_options = {\n name: \"app-configuration\",\n cwd: apppath\n }\n const CA1_store = new Store(CA1_options);\n var appver = CA1_store.get(\"app-version\", \"0.0.0\");\n var applang = CA1_store.get(\"app-lang\", \"en\");\n\n var appupcheck = CA1_store.get(\"latest-update-check\", null);\n var appupinst = CA1_store.get(\"latest-update-install\", null);\n var appzoom = CA1_store.get(\"zoom\", 100);\n\n var appfirst = CA1_store.get(\"first-use\", true);\n var appedits = CA1_store.get(\"edits\", [false, null]);\n var enabledkwlists = CA1_store.get(\"enabled-keywordlists\", [\"en\"]);\n\n //logger.info(\"Current ver.: \" + app.getVersion() + \" Ver. in file: \" + appver);\n var appvercheck = parseUtils.validateVersion(appver);\n if (!appvercheck) {\n logger.info(\"Config major version not same as application major version! updating...\");\n CA1_store.clear();\n CA1_store.set(\"app-lang\", applang);\n\n CA1_store.set(\"latest-update-check\", appupcheck);\n CA1_store.set(\"latest-update-install\", appupinst);\n CA1_store.set(\"zoom\", appzoom);\n\n CA1_store.set(\"first-use\", appfirst);\n CA1_store.set(\"app-version\", app.getVersion());\n CA1_store.set(\"edits\", appedits)\n CA1_store.set(\"enabled-keywordlists\", enabledkwlists);\n } else {\n logger.info(\"Application config major version same or newer as application version! Not updating...\");\n }\n // check if consistent with this version, if not, remove and rebuild\n }\n \n}\n\n/* Creates new project with a given name into Documents-folder */\nfunction createNewProject(proj_name, proj_country, proj_lang) {//\n var reason = [];\n logger.debug(\"createNewProject\");\n logger.debug(proj_name);\n logger.debug(proj_name.length);\n var regex_filepath_val = /^[^\\\\/:\\*\\?\"<>\\|]+$/;\n var docpath = app.getPath('documents');\n\n if (proj_name === undefined) {\n // Projectname not defined\n reason.push(false, 1);\n return reason;\n }\n else if (proj_name.length === 0 || proj_name.length > 100) {\n // Projectname length 0 or over 100 characters\n reason.push(false, 2);\n return reason;\n }\n else if (!regex_filepath_val.test(proj_name)) {\n // Projectname not allowed\n reason.push(false, 3);\n return reason;\n }\n else if (proj_country === undefined) {\n // Project country not defined\n reason.push(false, 4);\n return reason;\n }\n else if (proj_lang === undefined) {\n // Project language not defined\n reason.push(false, 5);\n return reason;\n }\n else if (fs.existsSync(path.join(docpath, 'SLIPPS Teacher Tool'))) {\n if (fs.existsSync(path.join(docpath, 'SLIPPS Teacher Tool\\\\Projects'))) {\n // testing if directory just in case....\n var project_dircheck = fs.statSync(path.join(docpath, 'SLIPPS Teacher Tool\\\\Projects')); \n if (project_dircheck.isDirectory()) {\n logger.info(\"Projects directory in user's documents located!\");\n }\n else {\n // Projects-folder not present!\n createDocStructure();\n reason.push(false, 6);\n return reason;\n }\n\n try {\n fs.accessSync(path.join(docpath, 'SLIPPS Teacher Tool\\\\Projects\\\\' + proj_name + '.decsv'));\n // if we get past this, project exits...\n var projFileCheck = fs.statSync(path.join(docpath, 'SLIPPS Teacher Tool\\\\Projects\\\\' + proj_name + '.decsv'));\n if (projFileCheck.isDirectory()) {\n throw \"Tested project was directory, not file!\";\n }\n\n reason.push(false, 7);\n return reason;\n } catch (err) {\n // project does not exist!\n logger.info(\"Project with name'\"+proj_name+\"' does not exits! Creating....\");\n }\n\n //logger.debug(\"Creating new properties file.....\");\n var project_data_template = JSON.stringify({\n \"____INFO____\": \"THIS IS PROJECT FILE FOR DECSV/SLIPPS Teacher Tool APPLICATION, USED AS PART OF THE SLIPPS EU PROJECT\",\n \"created\": new Date().toISOString(),\n \"project-files\": {},\n \"notes\": [],\n \"lang-preset\": proj_lang,\n \"country-preset\": proj_country,\n \"version\": app.getVersion()\n });\n //const CA3_store = new Store(CA3_options);\n try {\n fs.writeFileSync(path.join(docpath, 'SLIPPS Teacher Tool\\\\Projects\\\\' + proj_name + '.decsv'), project_data_template, 'utf-8');\n } catch (err) {\n logger.error(\"Failed to write new project file '\" + proj_name + \".decsv'! Reason: \" + err.message);\n reason.push(false, 8);\n return reason;\n }\n \n logger.info(\"Created project '\" + proj_name + \"'!\");\n reason.push(true, 11, path.join(docpath, 'SLIPPS Teacher Tool\\\\Projects\\\\' + proj_name + '.decsv'));\n return reason;\n }\n else {\n // Projects-folder not present!\n createDocStructure();\n reason.push(false, 9);\n return reason;\n }\n }\n else {\n // Application-folder (at Documents) not present!\n createDocStructure();\n reason.push(false, 10);\n return reason;\n }\n}\n\n/* Handles needed stuff when application is going to be closed */\nfunction handleclosing(callback = function (i) { return i;}) {\n logger.debug(\"handleClosing\");\n logger.info(\"Handling things before closing...\");\n // do things needed before shutting down\n var CA3_options = {\n name: \"app-configuration\",\n cwd: app.getPath('userData')\n }\n const CA3_store = new Store(CA3_options);\n\n var edit_check = CA3_store.get(\"edits\", [false, null]);\n\n var dial_options_2 = {//app.quit()\n type: 'info',\n title: \"Saved\",\n message: \"Changes were saved!\",\n detail: \"Press ok to continue\",\n buttons: [i18n_app.__('conf-ok', true)]\n }\n\n if (edit_check[0] && (edit_check[1] !== null)) {\n logger.info(\"Unsaved changes possible! Asking user what to do...\");\n logger.debug(edit_check[0] + \" - \" + edit_check[1]);\n // ask if want to save changes, or not\n var file_ext = edit_check[1].split('.').pop();\n var proj_name = edit_check[1].split('\\\\').pop();\n proj_name = proj_name.split(\".\");\n proj_name.pop();\n proj_name.join(\".\");\n var dial_options = {\n type: 'info',\n title: i18n_app.__('conf-title', true),\n message: i18n_app.__('conf-unsaved-title', true),\n detail: i18n_app.__('conf-unsaved-desc', true),\n buttons: [i18n_app.__('conf-yes', true), i18n_app.__('conf-no', true)]\n };\n\n dialog.showMessageBox(mainWindow, dial_options, function (index) {\n if (index === 0) {\n logger.info(\"User decided to save backup! Saving to file '\" + edit_check[1] + \"'\");\n var backup_options = {\n name: proj_name,\n cwd: path.join(app.getPath('userData'), \"backup_files\")\n }\n const backup_store = new Store(backup_options);\n var backup_content = backup_store.store;\n\n CA3_store.set(\"edits\", [false, null]);\n\n try {\n fs.writeFileSync(edit_check[1], JSON.stringify(backup_content), \"utf8\");\n fs.unlinkSync(path.join(app.getPath(\"userData\"), \"backup_files\\\\\" + proj_name + \".json\"));\n } catch (err) {\n logger.error(\"Error while writing '\" + edit_check[1] + \"' or removing backup for it! Reason: \" + err.message);\n }\n //logger.info(\"callback_1\")\n callback(0);\n } else {\n //\n CA3_store.set(\"edits\", [false, null]);\n\n logger.info(\"User decided not to save backup! Removing...\");\n try {\n fs.unlinkSync(path.join(app.getPath(\"userData\"), \"backup_files\\\\\" + proj_name + \".json\"));\n } catch (err) {\n logger.error(\"Unable to unlink backup file for '\" + edit_check[1] + \"'!\");\n }\n //logger.info(\"callback_2\")\n callback(0);\n }\n });\n \n }\n else if (edit_check[1] !== null) {\n logger.info(\"Unsaved backup possible, even though it was not mentioned! Trying to remove...\");\n try {\n fs.unlinkSync(path.join(app.getPath(\"userData\"), \"backup_files\\\\\" + proj_name + \".json\"));\n } catch (err) {\n logger.error(\"Unable to unlink backup file for '\" + edit_check[1] + \"'!\");\n }\n //logger.info(\"callback_3\")\n callback(0);\n } else { callback(1);}\n}\n\n/* Creates opening window (with logo) and main window */\nfunction createWin() {\n setTimeout(function () {\n logger.debug(\"createWin\");\n openWindow = new BrowserWindow({\n width: 320,\n height: 320,\n resizable: false,\n devTools: true,\n frame: false,\n backgroundColor: '#dadada',\n show: false\n });\n\n let win1_url = url.format({\n protocol: 'file',\n slashes: true,\n pathname: path.join(__dirname, './assets/html/opening.html')\n });\n openWindow.loadURL(win1_url);\n\n openWindow.on('ready-to-show', function () {\n //\n openWindow.show();\n openWindow.webContents.send(\"open-update-setup\");\n });\n\n openWindow.on('closed', function () {\n if (mainWindow !== null) {\n mainWindow.show();\n }\n openWindow = null;\n });\n }, 0)\n}\n\nfunction createMainWindow() {\n logger.debug(\"createMainWindow\");\n logger.info(\"Creating main window...\");\n let mainWindowState = windowStateKeeper({\n defaultWidth: 1200,\n defaultHeight: 840\n });\n\n mainWindow = new BrowserWindow({\n x: mainWindowState.x,\n y: mainWindowState.y,\n width: mainWindowState.width,\n height: mainWindowState.height,\n devTools: true,\n frame: false,\n backgroundColor: '#dadada',\n show: false\n });\n //mainWindow.toggleDevTools();//ENABLED NEEDSTOBECHANGED\n\n let win2_url = url.format({\n protocol: 'file',\n slashes: true,\n pathname: path.join(__dirname, './assets/html/index.html')\n });\n mainWindow.loadURL(win2_url);\n\n //toggle dev tools when window opens\n //mainWindow.webContents.openDevTools();\n mainWindow.on('ready-to-show', function () {\n //logger.debug(\"%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\");\n mainWindowState.manage(mainWindow);\n // because testing\n //mainWindow.show();\n logger.debug(\"Hiding and closing start window\");\n openWindow.hide();\n openWindow.close();\n });\n\n mainWindow.on('close', (e) => {\n logger.debug(\"called close\");\n\n if (showExitPrompt) {\n e.preventDefault();\n logger.info(\"Mainwindow closed... prevented app exit!\");\n\n var options = {\n type: 'info',\n title: i18n_app.__('conf-title', true),\n message: i18n_app.__('quit-conf-message', true),\n detail: i18n_app.__('quit-conf-detail', true),\n buttons: [i18n_app.__('conf-yes', true), i18n_app.__('conf-no', true)]\n };\n\n dialog.showMessageBox(mainWindow, options, function (index) {\n if (index === 0) {\n handleclosing(function (i) {\n showExitPrompt = false;//\n logger.debug(\"from handleclosing: '\" + i + \"'\");\n logger.info(\"Inside handleclosing callback! Returnvalue: \"+i);\n if (aboutWindow !== null) {\n logger.info(\"Re-closing main window....\");\n aboutWindow.close();// closing about-window, if it is open\n } else {\n logger.warn(\"Tried to re-close main window, but it was NULL!\");\n }\n\n app.quit();// should we? need to think about darwin/macos options....\n\n });\n logger.debug(\"after handleclosing\");\n }\n });\n }\n });\n\n mainWindow.on('closed', function () {\n mainWindow = null;\n current_project = null;\n });\n mainWindow.on('unresponsive', function () {\n logger.error(\"MainWindow unresponsive!\");\n // create dialog and show that app jammed! clicking ok reloads the page\n var options = {\n type: 'error',\n title: \"Status\",\n message: \"Application unresponsive!\",\n detail: \"Application stopped responding! Would you like to reload app, or wait for it to become responsive again?\",\n buttons: [\"Reload\", \"Wait\"],\n BrowserWindow: mainWindow\n }\n dialog.showMessageBox(options, function (index) {\n //\n if (index === 0) {\n //open wiki\n logger.warn(\"Reloading app...\");\n mainWindow.reload();\n } else {\n // close, do nothing\n logger.warn(\"User wanted to >wait< for app to become responsive again!\");\n }\n });\n });\n mainWindow.on('responsive', function () {\n // nothing...\n logger.info(\"MainWindow responsive!\");\n });\n}\n\n/* Called when all windows are closed */\napp.on('window-all-closed', function () {\n logger.info(\"all windows closed\");\n // On OS X it is common for applications and their menu bar\n // to stay active until the user quits explicitly with Cmd + Q\n if (process.platform !== 'darwin') { // this needs more control!\n app.quit();\n }\n});\n\n/* Called when activating application window */\napp.on('activate', function () {\n // On OS X it's common to re-create a window in the app when the\n // dock icon is clicked and there are no other windows open.\n logger.info(\"app activated\");\n if (mainWindow === null) {\n createWin();\n }\n});\n\n/* AUTOUPDATER */\n// WARN DO NOT USE THESE! var updatePath = \"http://testing-tyaisurm.c9users.io/update/win32/\" + app.getVersion().toString();\n//autoUpdater.setFeedURL(updatePath);\n\n/* These are quit-handlers for the application */\napp.on('will-quit', function () {\n logger.info(\"application will quit...\");\n});\napp.on('quit', function () {\n logger.info(\"quitting application...\");\n});\n\n///////////////////////////////////////////////////////////////////////////////// UPDATER HANDLERS\n // 0 = checking\n // 1 = update found\n // 2 = no update available\n // 3 = error\n // 4 = downloading %\n // 5 = downloaded\n/* Called from init.js (or somewhere else) when wanted to check updates */\nipcMain.on(\"check-updates\", (event, arg) => { // CREATING LISTENERS IN FUNCTION ONLY SO THAT THE \"event\"-object CAN BE SAVED\n logger.debug(\"check-updates here!\");\nautoUpdater.on('checking-for-update', function () {\n logger.info(\"Current version: \" + app.getVersion().toString());\n var chekcupdatesettings = getSettings();\n chekcupdatesettings.app[\"latest-update-check\"] = new Date().toISOString();\n setSettings(chekcupdatesettings);\n //console.log(event);\n var arr = [];\n arr.push(0);\n event.sender.send(\"check-updates-reply\", arr);\n});\n autoUpdater.on('update-available', function (info) {//NEEDSTOBECHANGED\n logger.info(\"Update available!\");\n logger.info(info);\n var ver = info.version;\n var relDat = info.releaseDate;\n var relNote = info.releaseNotes;\n var arr = [];\n arr.push(1, ver, relDat, relNote);\n event.sender.send(\"check-updates-reply\", 1);\n});\n autoUpdater.on('error', function (err) {\n logger.error(\"Failed to get updates!\");\n //logger.error(err.message);\n var arr = [];\n arr.push(3);\n event.sender.send(\"check-updates-reply\", arr);\n clearUpdaterListeners();\n});\nautoUpdater.on('update-not-available', function (info) {\n logger.info(\"Update not available!\");\n logger.info(info);\n var arr = [];\n arr.push(2);\n event.sender.send(\"check-updates-reply\", arr);\n clearUpdaterListeners();\n});\n\n autoUpdater.on('update-downloaded', function (info) {//ev, relNot, relNam, relDat, updUrl) {NEEDSTOBECHANGED\n logger.info(\"Update has been downloaded!\");\n\n var updatedownloadedsettings = getSettings();\n updatedownloadedsettings.app[\"latest-update-install\"] = new Date().toISOString();\n setSettings(updatedownloadedsettings);\n\n var ver = info.version;\n var relDat = info.releaseDate;\n var relNote = info.releaseNotes;\n var arr = [];\n arr.push(5, ver, relDat, relNote);\n event.sender.send(\"check-updates-reply\", arr);\n clearUpdaterListeners();\n if (mainWindow !== null) {\n var options = {\n type: 'info',\n title: \"Update downloaded\",\n message: \"New version \" + ver + \" is ready to be installed\",\n detail: \"Would you like to close the application and update now? By default, update will be done when the application gets closed.\\r\\n\\r\\nVersion: \" + ver,\n buttons: [i18n_app.__('conf-yes', true), i18n_app.__('conf-no', true)]\n }; // DATE NEED TO BE REFORMATTED, AND RELNOTE SHOULD BE PARSED (CONTAINS HTML)\n // + \"\\r\\nRelease date: \" + new Date(relDat) +\"\\r\\n\"+relNote,\n\n dialog.showMessageBox(mainWindow, options, function (index) {\n if (index === 0) {\n showExitPrompt = false;\n autoUpdater.quitAndInstall();\n }\n else {\n //nothing\n }\n });\n } else {\n setTimeout(function () { showExitPrompt = false; autoUpdater.quitAndInstall(); }, 2000);\n }\n });\n\nautoUpdater.on('download-progress', function (progressObj) {\n var arr = [];\n arr.push(4, progressObj);\n event.sender.send(\"check-updates-reply\", arr);\n });\n //logger.debug(\"CALLING CHECKFORUPDATES!!!\");\n autoUpdater.checkForUpdates().then(\n function (val) {\n logger.info('Promise fulfilled!');\n }).catch(\n function (reason) {\n logger.warn('Rejected promise handler...');\n });\n});\n\n/* Clears away all listeners after updates have been checked - prevents listener-dublicates */\nfunction clearUpdaterListeners() { // THIS IS ONLY HERE SO THAT listeners wont get stacked up because of being called multiple times\n logger.debug(\"clearUpdaterListeners\");\n autoUpdater.removeAllListeners('checking-for-update');\n autoUpdater.removeAllListeners('update-available');\n autoUpdater.removeAllListeners('error');\n autoUpdater.removeAllListeners('update-not-available');\n autoUpdater.removeAllListeners('update-downloaded');\n autoUpdater.removeAllListeners('download-progress');\n}\n\n/* Global function that opens up the ABOUT-window */\nglobal.createAboutWin = function () {\n if (aboutWindow === null) {\n logger.debug(\"createAboutWindow\");\n logger.info(\"Opening about-window...\");\n aboutWindow = new BrowserWindow({\n width: 500,\n height: 500,\n resizable: false,\n minWidth: 500,\n minHeight: 500,\n devTools: false,\n frame: false,\n backgroundColor: '#dadada',\n show: false\n });\n\n let about_url = url.format({\n protocol: 'file',\n slashes: true,\n pathname: path.join(__dirname, './assets/html/about.html')\n });\n aboutWindow.loadURL(about_url);\n\n aboutWindow.on('ready-to-show', function () {\n aboutWindow.show();\n });\n\n aboutWindow.on('closed', function () {\n logger.info(\"About-window closed\");\n aboutWindow = null;\n });\n }\n else {\n logger.info(\"Refocus about-window...\");\n aboutWindow.focus();\n }\n}\n/* Global function that creates dummy \"not implemented\" dialog with \"OK\" button */\nglobal.createDummyDialog = function (callingWindow) {\n var options = {\n type: 'info',\n title: i18n_app.__('dummy-dia-1', true),\n message: i18n_app.__('dummy-dia-2', true),\n detail: i18n_app.__('dummy-dia-3', true),\n buttons: [i18n_app.__('conf-ok', true)]\n };\n\n dialog.showMessageBox(callingWindow, options, function (index) {\n // no need to deal with anything.... just notifying user\n });\n}\n\n// NEEDS const XLSX = require('xlsx');\n/* Reads source file, CSV or XLS or XLSX format into array */\nfunction readSourceFile(lert_tool = null, lert_delimiter = null, lert_encoding = null, file = null) {//[tool, delimiter, encoding, filepath] NEEDSTOBECHANGED\n logger.debug(\"readFile\");\n\n /* check file-extension and name */\n var result = [];\n var output_data = [];\n var file_ext = file.split('.').pop();\n var file_name = file.split('\\\\').pop();\n\n //console.log(\"################################################\");\n //console.log(file_ext);\n //console.log(file);\n\n\n\n /* file has .xlsx or .xls extension */\n if (file_ext === 'xlsx' || file_ext === 'xls') {\n logger.info(\"Parsing XLSX or XLS file... NOT ENABLED\");\n /*\n // xlsx-js \n try {\n var workbook = XLSX.readFile(file);\n }\n catch (err) {\n logger.error(\"Error opening .xlsx or .xls file: \" + err.message);\n result.push(false);\n result.push(1); //xlsx opening failed!\n result.push([]);\n return result;\n }\n var first_sheet_name = workbook.SheetNames[0];\n var worksheet = workbook.Sheets[first_sheet_name];\n\n var csv_sheet = XLSX.utils.sheet_to_csv(worksheet);\n\n var parseResult = parseUtils.validateAndParseCSV(csv_sheet, lert_tool, lert_delimiter);\n logger.info(\"Parse & validate result: [\"+parseResult[0]+\", \"+parseResult[1]+\", *PARSED DATA*]\");\n if (parseResult[0]) {\n result.push(true);\n result.push(0); //xlsx parsin ok\n result.push(parseResult[2]);\n return result;\n } else {\n result.push(false);\n result.push(2); // parsing failed\n result.push([]);\n return result;\n }\n */\n } else if (file_ext === 'csv') {\n logger.info(\"Parsing CSV file...\");\n /*Node.js fs*/\n var data = \"\";\n try {\n //mainWindow.webContents.send(\"output-to-chrome-console\", \"PARSING DATAAAAAAAAAAAAAAAAAAAAAAAA ORIGINAL aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\");\n data = fs.readFileSync(file, null);\n }\n catch (err) {\n logger.error(\"Error opening file '\"+file_name+\"': \" + err.message);\n result.push(false);\n result.push(1);// couldn't open csv file!\n result.push([]);\n return result;\n }\n //////////////\n\n //var chardet1 = charDetector.detectAll(data);\n //var chardet2 = charDetector123(data);\n\n //////////////////////////////////////////\n var detectRes = charDetector.detectAll(data);\n\n var encodings = {};\n var tempencodings = [];\n try {\n tempencodings = JSON.parse(fs.readFileSync(path.join(__dirname, \"./assets/select2/encodings.json\"), \"utf8\"));\n if (!(tempencodings instanceof Array)) {\n logger.warn(\"Encodings from file not array!\");\n encodings = {}\n } else {\n for (var sew = 0; sew < tempencodings.length; sew++) {\n encodings[sew] = tempencodings[sew].name;\n }\n }\n }\n catch (err) {\n logger.error(\"Error opening encodings file: \" + err.message);\n encodings = {}\n }\n if (encodings.hasOwnProperty(lert_encoding) && lert_encoding !== 0) {\n lert_encoding = encodings[lert_encoding];\n } else {\n logger.error(\"Chosen encoding does not exist in file, or encoding was default! Value: \" + lert_encoding);\n lert_encoding = null;\n }\n\n\n\n /////////////////////////////////////////////////////////////////////\n var data_rdy = \"\";\n if (detectRes.length > 0) {\n var encresstr = \"\";\n try {\n encresstr = JSON.stringify(detectRes[0]);\n //logger.debug(encresstr);\n } catch (err) {\n logger.error(\"Error while encoding check stringify!\");\n logger.error(err.message);\n encresstr = detectRes[0];\n }\n\n logger.info(\"Encoding found: \" + encresstr);\n logger.info(\"Trying to convert to UTF-8...\");\n\n //logger.debug(JSON.parse(detectRes));\n var iconv_csv = null;\n //mainWindow.webContents.send(\"output-to-chrome-console\", data);\n try {\n logger.debug(\"Source encoding: \" + detectRes[0].name);\n if (lert_encoding === null) {\n logger.info(\"Lert_encoding was null! Using default...\");\n iconv_csv = new Iconv(detectRes[0].name, 'UTF-8//TRANSLIT');\n } else {\n logger.info(\"Lert_encoding defined! Using it...\");\n iconv_csv = new Iconv(lert_encoding, 'UTF-8//TRANSLIT');\n }\n data_rdy = iconv_csv.convert(data).toString(); \n } catch (err) {\n logger.error(err)\n logger.error(\"Encoding failed! Failed to set source encoding: \" + detectRes[0].name);\n logger.info(\"Trying second encoding option...\");\n try {\n logger.debug(\"Source encoding: \" + detectRes[2].name);\n if (lert_encoding === null) {\n logger.info(\"Lert_encoding was null! Using default...\");\n iconv_csv = new Iconv(detectRes[1].name, 'UTF-8//TRANSLIT');\n } else {\n logger.info(\"Lert_encoding defined! Using it...\");\n iconv_csv = new Iconv(detectRes[0].name, 'UTF-8//TRANSLIT');\n }\n data_rdy = iconv_csv.convert(data).toString();\n } catch (err) {\n logger.error(err)\n logger.error(\"Encoding failed! Failed to set source encoding: \" + detectRes[0].name);\n logger.info(\"Trying final encoding option...\");\n try {\n if (lert_encoding === null) {\n logger.info(\"Lert_encoding was null! Not retrying...\");\n throw \"Last file import data encoding attempt failed!\";\n } else {\n logger.info(\"Lert_encoding defined! Using it...\");\n iconv_csv = new Iconv(detectRes[1].name, 'UTF-8//TRANSLIT');\n }\n data_rdy = iconv_csv.convert(data).toString();\n } catch (err) {\n logger.error(err)\n logger.error(\"Encoding failed! Failed to set source encoding: \" + detectRes[0].name);\n logger.warn(\"Defaulting toString() UTF-8...\");\n data_rdy = data.toString('utf8');\n }\n }\n }\n }\n else {\n logger.warn(\"No hits for encoding found!\");\n logger.warn(\"Defaulting toString() UTF-8...\");\n data_rdy = data.toString('utf8'); \n }\n ////////////////////////////////////////////\n var parseResult = parseUtils.validateAndParseCSV(data_rdy, lert_tool, lert_delimiter);\n \n\n if (!parseResult[0]) {\n result.push(false);\n result.push(2); // parsing failed!\n result.push([]);\n return result;\n }\n result.push(true);\n result.push(0); // parsing successful\n result.push(parseResult[2]);\n logger.info(\"File '\" + file_name + \"' content successfully loaded and parsed!\");\n return result;\n }\n else {\n //what lies beyond this land... prob not right file for some reason :D\n logger.warn(\"Tried to open invalid file! Wrong extension: \" + file_ext);\n result.push(false);\n result.push(3);// File invalid\n result.push([]);\n return result;\n }\n}", "dangerousExampleEn": "1. process.on(\"uncaughtException\", function(err) {\n2. // log necessary error details to log files\n3. //process.exit();\n4. });\nLine 1: uncaughtException was used but the current status of the program is unknown because the process has not been terminated explicitly.", "safeExampleEn": "1. process.on(\"uncaughtException\", function(err) {\n2. // log necessary error details to log files\n3. process.exit();\n4. });\nLine 3: This is secure because the process is terminated after the errors are logged.", "contexts": [{"lineNo": 3, "eventType": "sink", "messageKey": "jschk.UNCAUGHT_EXCEPTION.JS.defect", "params": {}}]}} {"id": "f3365d43aebdc62c7f9720025494622666e060219440d7f7d03ff20f9eb0b285", "license": {"spdx": ["MIT"], "repo": "codestates/re-collect-server", "path": "controller/mailCtrl.js", "repo_head_hexsha": "9799642fa2f076282194e67cee0737bdac38c4d8", "stack_hexsha": "dd2ab3519f15fc92c067d056be8dfee3c9dbc12b", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of uncaughtException", "issueDescriptionEn": "Using uncaughtException enables a developer to handle errors that could not be addressed by a developer beforehand. However, the official node document specifies that it should only be used as a last resort. This is because uncaughtException cannot guarantee a program will close after an error occurs.\nuncaughtException should be used for logging purposes. After logging the errors, the process needs to be terminated using process.exit();.", "issueLineNumber": 82, "entireCode": "const cron = require('node-cron');\nconst nodemailer = require('nodemailer');\nconst { User, sequelize } = require('../models');\nconst handlebars = require('handlebars');\nconst fs = require('fs');\nconst express = require('express');\nconst path = require('path');\nconst app = express();\n\n\nconst transporter = nodemailer.createTransport({\n service: 'gmail',\n host: 'smtp.google.com',\n port: 587,\n secure: true,\n auth: {\n type: 'OAuth2',\n user: process.env.GMAIL_USER,\n clientId: process.env.GMAIL_CLIENT_ID,\n clientSecret: process.env.GMAIL_CLIENT_SECRET,\n accessToken: process.env.GMAIL_ACCESS_TOKEN,\n refreshToken: process.env.GMAIL_REFRESH_TOKEN\n },\n});\n\ncron.schedule('00 09 * * 5', async() => {\n const templateStr = fs.readFileSync(path.resolve('./view', 'notification-template.html')).toString('utf8');\n const users = await User.findAll({\n attributes:['id', 'username', 'email']\n }).then((result) => result.map((user) => user.dataValues));\n console.log(users);\n const sql = `SELECT COUNT(id) AS count, userId FROM Bookmarks WHERE visitCounts = 0 AND NOW() - createdAt >= 7 GROUP BY userId;`;\n const results = await sequelize.query(sql);\n console.log(results);\n let lists = results[0].map((el) => {\n for(let idx in users) {\n if(users[idx].id === el.userId) {\n el.email = users[idx].email;\n el.username = users[idx].username;\n }\n }\n return el;\n });\n try {\n for(let i = 0; i < lists.length; i++) {\n let template = handlebars.compile(templateStr, { noEscape: true });\n let data = { username:'', count:'', email: '' };\n data.username = lists[i].username;\n data.count = lists[i].count;\n let htmlToSend = template(data);\n console.log('-----------확인------------------');\n let message = {\n from: process.env.GMAIL_USER,\n to: lists[i].email,\n subject:'Recollect에 아직 읽지 않은 북마크가 있습니다',\n html: htmlToSend,\n }\n transporter.sendMail(message, (err, info) => {\n if(err) {\n console.error(err);\n throw Error;\n } else {\n console.log('-------------------알림 메일을 전송하였습니다------------------', info);\n }\n });\n } \n} catch(err) {\n next(new Error('failed'));\n }\n});\n\napp.listen(4000, () => {\n console.log('cron 작업을 위한 포트 4000번 실행 중 입니다.');\n});\n\n//* SIGTERM && SIGINT 처리\nprocess.on('SIGINT', (err,req,res,next) => {\n process.exit(err ? 1 : 0);\n});\n\n//* 예상치 못한 예외 처리\nprocess.on('uncaughtException', function (err) {\n\tconsole.log('uncaughtException 발생 : ' + err);\n});\n\nmodule.exports = app;", "dangerousExampleEn": "1. process.on(\"uncaughtException\", function(err) {\n2. // log necessary error details to log files\n3. //process.exit();\n4. });\nLine 1: uncaughtException was used but the current status of the program is unknown because the process has not been terminated explicitly.", "safeExampleEn": "1. process.on(\"uncaughtException\", function(err) {\n2. // log necessary error details to log files\n3. process.exit();\n4. });\nLine 3: This is secure because the process is terminated after the errors are logged.", "contexts": [{"lineNo": 82, "eventType": "sink", "messageKey": "jschk.UNCAUGHT_EXCEPTION.JS.defect", "params": {}}]}} {"id": "38d4f15d29b5b7010910b009272866fbf1e854037b52babf934022703787c731", "license": {"spdx": ["MIT"], "repo": "GuyHarwood/bare-bones", "path": "test/functional.js", "repo_head_hexsha": "52afdce3a168f02bfedfb83f676a623d89a90b36", "stack_hexsha": "cdb0dac96adcae19eba327445c464faf551eb50f", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of uncaughtException", "issueDescriptionEn": "Using uncaughtException enables a developer to handle errors that could not be addressed by a developer beforehand. However, the official node document specifies that it should only be used as a last resort. This is because uncaughtException cannot guarantee a program will close after an error occurs.\nuncaughtException should be used for logging purposes. After logging the errors, the process needs to be terminated using process.exit();.", "issueLineNumber": 23, "entireCode": "var test = require('tape')\nvar app = require('./../app') // auth, token verification & render helpers\nvar mock = require('./mock') // basic mock of http module req & res\n\ntest('home', function (t) {\n app.home(mock.res)\n t.equal(200, 200, 'Status 200')\n t.end()\n})\n\ntest('notFound', function (t) {\n var res = app.notFound(mock.res)\n // console.log(res.status)\n t.equal(res.status, 404, 'Not found')\n t.end()\n})\n\nsetTimeout(function () {\n app.done(mock.res)\n app.exit(mock.res)\n}, 1500)\n\nprocess.on('uncaughtException', function (err) {\n console.log('FAIL ... ' + err)\n})", "dangerousExampleEn": "1. process.on(\"uncaughtException\", function(err) {\n2. // log necessary error details to log files\n3. //process.exit();\n4. });\nLine 1: uncaughtException was used but the current status of the program is unknown because the process has not been terminated explicitly.", "safeExampleEn": "1. process.on(\"uncaughtException\", function(err) {\n2. // log necessary error details to log files\n3. process.exit();\n4. });\nLine 3: This is secure because the process is terminated after the errors are logged.", "contexts": [{"lineNo": 23, "eventType": "sink", "messageKey": "jschk.UNCAUGHT_EXCEPTION.JS.defect", "params": {}}]}} {"id": "415c396089c707e1428780ff36a66dbc58b83dc9f0b3bdb0170df9d092c02723", "license": {"spdx": ["MIT"], "repo": "e7217/electron-app", "path": "websocket_two.js", "repo_head_hexsha": "da391b1d6fb80bd5a2eb9401e79ebca9dc3f0a10", "stack_hexsha": "1e95fd94473eedf6faef7d43648213b81148df83", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of uncaughtException", "issueDescriptionEn": "Using uncaughtException enables a developer to handle errors that could not be addressed by a developer beforehand. However, the official node document specifies that it should only be used as a last resort. This is because uncaughtException cannot guarantee a program will close after an error occurs.\nuncaughtException should be used for logging purposes. After logging the errors, the process needs to be terminated using process.exit();.", "issueLineNumber": 1, "entireCode": "process.on('uncaughtException', function (err) {\n console.log(\"error occur : \", err)\n});\n\nconst io = require('socket.io')();\nio.on('connection', client => { console.log(\"hello world\") });\ntry {\n io.listen(3000)\n} catch(err) {\n console.log(err)\n}", "dangerousExampleEn": "1. process.on(\"uncaughtException\", function(err) {\n2. // log necessary error details to log files\n3. //process.exit();\n4. });\nLine 1: uncaughtException was used but the current status of the program is unknown because the process has not been terminated explicitly.", "safeExampleEn": "1. process.on(\"uncaughtException\", function(err) {\n2. // log necessary error details to log files\n3. process.exit();\n4. });\nLine 3: This is secure because the process is terminated after the errors are logged.", "contexts": [{"lineNo": 1, "eventType": "sink", "messageKey": "jschk.UNCAUGHT_EXCEPTION.JS.defect", "params": {}}]}} {"id": "ee55e9abdb0bf18d6896d42cce5fc6ea1ba320a1aea46a87daa6ed674a489e46", "license": {"spdx": ["MIT"], "repo": "arxpoetica/stallion", "path": "src/server.js", "repo_head_hexsha": "44fdfad775b0cfbd019ae1c6feb8720de2b5957c", "stack_hexsha": "b27f179cb5273bd0f82e48cf4868dcee35e44f70", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of uncaughtException", "issueDescriptionEn": "Using uncaughtException enables a developer to handle errors that could not be addressed by a developer beforehand. However, the official node document specifies that it should only be used as a last resort. This is because uncaughtException cannot guarantee a program will close after an error occurs.\nuncaughtException should be used for logging purposes. After logging the errors, the process needs to be terminated using process.exit();.", "issueLineNumber": 24, "entireCode": "// FIXME: config should work\n// import config from './_server/build/config'\nimport { white, green } from 'ansi-colors'\nimport express from 'express'\nimport morgan from 'morgan'\nimport helmet from 'helmet'\nimport compression from 'compression'\nimport sirv from 'sirv'\nimport bodyParser from 'body-parser'\nimport cookieParser from 'cookie-parser'\nimport { appSetup } from './_server/services/app-setup.js'\nimport { authSetup } from './_server/services/auth-setup.js'\nimport { graphqlSetup } from './_server/services/graphql-setup.js'\nimport { validate } from './routes/_services/auth-check.js'\nimport * as sapper from '@sapper/server'\n\nconst { PORT, NODE_ENV } = process.env\nconst development = NODE_ENV === 'development'\n\n// https://www.joyent.com/node-js/production/design/errors\n// TODO: https://shapeshed.com/uncaught-exceptions-in-node/\n// handle all uncaught exceptions\n// see - https://nodejs.org/api/process.html#process_event_uncaughtexception\nprocess.on('uncaughtException', error => console.error('Uncaught Exception:'.red, error))\n// handle all unhandled promise rejections\n// see - http://bluebirdjs.com/docs/api/error-management-configuration.html#global-rejection-events\n// or for latest node - https://nodejs.org/api/process.html#process_event_unhandledrejection\nprocess.on('unhandledRejection', error => console.error('Unhandled Rejection:'.red, error))\n\n// ---> FOOTGUN!?\nasync function start() {\n\n\t// NOTE: order matters!!! https://github.com/jaredhanson/passport/issues/14#issuecomment-4863459\n\tconst app = express()\n\n\tapp.use(morgan(development ? 'dev' : 'combined', {\n\t\tskip: (req, res) => development ? false : res.statusCode < 400,\n\t}))\n\n\t// SEE: https://expressjs.com/en/advanced/best-practice-security.html\n\tapp.use(helmet())\n\tapp.set('trust proxy', 1) // trust first proxy\n\n\tapp.use(compression({ threshold: 0 }))\n\tapp.use(sirv('static', { development }))\n\n\t// app.use(bodyParser.text())\n\tapp.use(bodyParser.json())\n\tapp.use(bodyParser.urlencoded({ extended: true }))\n\tapp.use(cookieParser())\n\n\tawait appSetup(app)\n\tawait authSetup(app)\n\tawait graphqlSetup(app)\n\n\tapp.use(sapper.middleware({\n\t\tsession: req => {\n\t\t\tconst user = validate(req)\n\t\t\treturn {\n\t\t\t\tenv: NODE_ENV,\n\t\t\t\tuser: user.unauthorized ? null : user,\n\t\t\t\t// req: req,\n\t\t\t}\n\t\t},\n\t}))\n\n\tapp.listen(PORT, setTimeout(() => {\n\t\tconsole.log()\n\t\tconsole.log(' ,~~_')\n\t\tconsole.log(' |/\\\\ =_ _ ~')\n\t\tconsole.log(' _( )_( )\\\\~~')\n\t\tconsole.log(' \\\\,\\\\ _|\\\\ \\\\~~~')\n\t\tconsole.log(' \\\\` \\\\')\n\t\tconsole.log(' ` `')\n\t\tconsole.log()\n\t\tconsole.log(' ~~~ Stallion ~~~ Headless CMS built atop Svelte and Sapper.')\n\t\tconsole.log()\n\t\tconsole.log(green(` listening at ${white(process.env.STALLION_HOST)} in ${white(NODE_ENV)} mode on process ${white(process.pid)}`))\n\t\t// console.log(JSON.stringify(process.env, null, 2))\n\t\tif (development) {\n\t\t\tconsole.log(green(` Running ${white(`${process.env.STALLION_HOST}/graphiql`)} in development mode only...`))\n\t\t}\n\t\tconsole.log()\n\t}, 100))\n\n}\n\nstart()", "dangerousExampleEn": "1. process.on(\"uncaughtException\", function(err) {\n2. // log necessary error details to log files\n3. //process.exit();\n4. });\nLine 1: uncaughtException was used but the current status of the program is unknown because the process has not been terminated explicitly.", "safeExampleEn": "1. process.on(\"uncaughtException\", function(err) {\n2. // log necessary error details to log files\n3. process.exit();\n4. });\nLine 3: This is secure because the process is terminated after the errors are logged.", "contexts": [{"lineNo": 24, "eventType": "sink", "messageKey": "jschk.UNCAUGHT_EXCEPTION.JS.defect", "params": {}}]}} {"id": "ad7ae3fa04dfdead5b26d9e0ef84251f72fa90e4c16c143cbb1dc59e3bd37f07", "license": {"spdx": ["MIT"], "repo": "Kerinlin/wallet", "path": "static/rpc-server.js", "repo_head_hexsha": "28b8d4db1faf4fd26ce71f67a231bc0f384c1365", "stack_hexsha": "af320b921fba75386da392c0e563c36654e8e09a", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of uncaughtException", "issueDescriptionEn": "Using uncaughtException enables a developer to handle errors that could not be addressed by a developer beforehand. However, the official node document specifies that it should only be used as a last resort. This is because uncaughtException cannot guarantee a program will close after an error occurs.\nuncaughtException should be used for logging purposes. After logging the errors, the process needs to be terminated using process.exit();.", "issueLineNumber": 24, "entireCode": "const dnode = require('dnode');\nconst objectAssign = require('object-assign');\n\nconst path =require('path')\nconst account=require(path.join(__dirname, \"../src/rpcserver/accountkey.js\"));\n\n\n\n var obj={\n abc:function(s, cb){\n console.log('abc!!!!!'+Date.now())\n cb('abc!!!!!'+Date.now())\n }\n }\n\nlet api =objectAssign({}, obj,account);\n\ndnode(api).listen(process.env.RPC_PORT, () => {\n process.send({\n state: 'init'\n });\n});\n\nprocess.on('uncaughtException', (err) => {\n Object.assign({}, err);\n process.send({\n error: err.stack\n }); // 'A Fatal Exception has occured in the genaroshare-daemon RPC server'\n});", "dangerousExampleEn": "1. process.on(\"uncaughtException\", function(err) {\n2. // log necessary error details to log files\n3. //process.exit();\n4. });\nLine 1: uncaughtException was used but the current status of the program is unknown because the process has not been terminated explicitly.", "safeExampleEn": "1. process.on(\"uncaughtException\", function(err) {\n2. // log necessary error details to log files\n3. process.exit();\n4. });\nLine 3: This is secure because the process is terminated after the errors are logged.", "contexts": [{"lineNo": 24, "eventType": "sink", "messageKey": "jschk.UNCAUGHT_EXCEPTION.JS.defect", "params": {}}]}} {"id": "9139cbf5efb07965f4e3f3d7dbc3f5770b16808b56067e8af4e876ab84297847", "license": {"spdx": ["MIT"], "repo": "jellythewobbly/node-express-mongoDB", "path": "vidly_api/startup/logger.js", "repo_head_hexsha": "7e578e9f210a74c2ca805600d00379f063f2d749", "stack_hexsha": "45757912d30c71e4f102f53b2594d71555403d75", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of uncaughtException", "issueDescriptionEn": "Using uncaughtException enables a developer to handle errors that could not be addressed by a developer beforehand. However, the official node document specifies that it should only be used as a last resort. This is because uncaughtException cannot guarantee a program will close after an error occurs.\nuncaughtException should be used for logging purposes. After logging the errors, the process needs to be terminated using process.exit();.", "issueLineNumber": 11, "entireCode": "require('express-async-errors');\nconst winston = require('winston');\nrequire('winston-mongodb');\n\nmodule.exports = function() {\n winston.add(new winston.transports.File({ filename: 'logfile.log' }));\n winston.add(\n new winston.transports.MongoDB({ db: 'mongodb://localhost/node_vidly' })\n );\n\n process.on('uncaughtException', err => {\n console.error('Error: There was an uncaught exception');\n const { name, message, level, stack } = err;\n winston.error({\n message,\n name,\n level,\n stack,\n });\n });\n\n process.on('unhandledRejection', err => {\n console.error('Error: There was an unhandled rejection');\n const { name, message, level, stack } = err;\n winston.error({\n message,\n name,\n level,\n stack,\n });\n });\n};", "dangerousExampleEn": "1. process.on(\"uncaughtException\", function(err) {\n2. // log necessary error details to log files\n3. //process.exit();\n4. });\nLine 1: uncaughtException was used but the current status of the program is unknown because the process has not been terminated explicitly.", "safeExampleEn": "1. process.on(\"uncaughtException\", function(err) {\n2. // log necessary error details to log files\n3. process.exit();\n4. });\nLine 3: This is secure because the process is terminated after the errors are logged.", "contexts": [{"lineNo": 11, "eventType": "sink", "messageKey": "jschk.UNCAUGHT_EXCEPTION.JS.defect", "params": {}}]}} {"id": "bd7672c825ca6b3639862ca5536649b96ec29b0f60544e05e523b6b11efba14d", "license": {"spdx": ["Apache-2.0"], "repo": "madanagopaltcomcast/pxCore", "path": "examples/pxScene2d/external/libnode-v6.9.0/test/parallel/test-exception-handler2.js", "repo_head_hexsha": "c4a3a40a190521c8b6383d126c87612eca5b3c42", "stack_hexsha": "1dabedf4c68730dd4b5fa9f5b001908dd07db8bf", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of uncaughtException", "issueDescriptionEn": "Using uncaughtException enables a developer to handle errors that could not be addressed by a developer beforehand. However, the official node document specifies that it should only be used as a last resort. This is because uncaughtException cannot guarantee a program will close after an error occurs.\nuncaughtException should be used for logging purposes. After logging the errors, the process needs to be terminated using process.exit();.", "issueLineNumber": 4, "entireCode": "'use strict';\nconst common = require('../common');\n\nprocess.on('uncaughtException', function(err) {\n console.log('Caught exception: ' + err);\n});\n\nsetTimeout(common.mustCall(function() {\n console.log('This will still run.');\n}), 50);\n\n// Intentionally cause an exception, but don't catch it.\nnonexistentFunc(); // eslint-disable-line no-undef\ncommon.fail('This will not run.');", "dangerousExampleEn": "1. process.on(\"uncaughtException\", function(err) {\n2. // log necessary error details to log files\n3. //process.exit();\n4. });\nLine 1: uncaughtException was used but the current status of the program is unknown because the process has not been terminated explicitly.", "safeExampleEn": "1. process.on(\"uncaughtException\", function(err) {\n2. // log necessary error details to log files\n3. process.exit();\n4. });\nLine 3: This is secure because the process is terminated after the errors are logged.", "contexts": [{"lineNo": 4, "eventType": "sink", "messageKey": "jschk.UNCAUGHT_EXCEPTION.JS.defect", "params": {}}]}} {"id": "ffcdd62ff295df4c3590629ad2da86bfb5268835d5031ae892055e7e398d2cac", "license": {"spdx": ["MIT"], "repo": "konstantinzolotarev/lo3_demo_scripts", "path": "deploy.js", "repo_head_hexsha": "b0c372b2d7a0b9bb135234c261b3be3a3f6f0f1d", "stack_hexsha": "9304deb7c336f073d89a75ab39821aec9ad0c471", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of uncaughtException", "issueDescriptionEn": "Using uncaughtException enables a developer to handle errors that could not be addressed by a developer beforehand. However, the official node document specifies that it should only be used as a last resort. This is because uncaughtException cannot guarantee a program will close after an error occurs.\nuncaughtException should be used for logging purposes. After logging the errors, the process needs to be terminated using process.exit();.", "issueLineNumber": 32, "entireCode": "'use strict'\n\nconst erisDb = require('eris-db-promise')\nconst config = require('config')\nconst contract = require('./contract')\n\n\nconst deployer = config.accounts.lo3_demo_chain_root_000\nconst tx = {\n data: contract.bytecode.toUpperCase(),\n input: {\n address: deployer.address\n }\n}\n\nconst eris = erisDb.createInstance(config.rpc.node1)\n\neris\n .unsafe\n .transactAndHold(deployer.privKey, contract.bytecode, '', 0, 10000)\n .then((info) => {\n console.log('==========================')\n console.log(info.call_data.callee)\n console.log('==========================')\n })\n .catch((err) => {\n console.log('==========================')\n console.log('error: ', err)\n console.log('==========================')\n })\n\nprocess.on('uncaughtException', (err) => {\n console.log('==========================')\n console.log('error: ', err)\n console.log('==========================')\n})", "dangerousExampleEn": "1. process.on(\"uncaughtException\", function(err) {\n2. // log necessary error details to log files\n3. //process.exit();\n4. });\nLine 1: uncaughtException was used but the current status of the program is unknown because the process has not been terminated explicitly.", "safeExampleEn": "1. process.on(\"uncaughtException\", function(err) {\n2. // log necessary error details to log files\n3. process.exit();\n4. });\nLine 3: This is secure because the process is terminated after the errors are logged.", "contexts": [{"lineNo": 32, "eventType": "sink", "messageKey": "jschk.UNCAUGHT_EXCEPTION.JS.defect", "params": {}}]}} {"id": "3af3925d4fe4c1f9970142061529bb8bd3be90e0fb5d92013767444b7f5c43e3", "license": {"spdx": ["MIT"], "repo": "Tout/nodetime", "path": "test/app-http.js", "repo_head_hexsha": "62dc0216b5155e0ad0d1c5379afbab731d7a0643", "stack_hexsha": "e725d261e3e6684fb99211bfd1861d44cc45c5e2", "match": "repo_path"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of uncaughtException", "issueDescriptionEn": "Using uncaughtException enables a developer to handle errors that could not be addressed by a developer beforehand. However, the official node document specifies that it should only be used as a last resort. This is because uncaughtException cannot guarantee a program will close after an error occurs.\nuncaughtException should be used for logging purposes. After logging the errors, the process needs to be terminated using process.exit();.", "issueLineNumber": 35, "entireCode": "/*\n * Copyright (c) 2012 \n *\n * Permission is hereby granted, free of charge, to any person obtaining a \n * copy of this software and associated documentation files (the \n * \"Software\"), to deal in the Software without restriction, including \n * without limitation the rights to use, copy, modify, merge, publish, \n * distribute, sublicense, and/or sell copies of the Software, and to permit \n * persons to whom the Software is furnished to do so, subject to the \n * following conditions:\n * \n * The above copyright notice and this permission notice shall be included \n * in all copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS \n * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF \n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN \n * NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, \n * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR \n * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR \n * THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n\n\nvar nodetime = require('nodetime');\nnodetime.on('session', function(token) { \n //console.log('session', token);\n});\nnodetime.on('sample', function(sample) { \n //console.log('sample');\n});\n\nnodetime.profile({debug: true, headless: false});\n\nprocess.on('uncaughtException', function (err) {\n console.error(err, err.stack)\n});\n\nvar probes = require('./probes');\n\nvar http = require('http');\nhttp.createServer(function(req, res) {\n probes(process.argv.slice(2), function() {\n res.writeHead(200, {'Content-Type': 'text/plain'});\n res.end('Hello World\\n');\n }); \n\n}).listen(3000);\n\nconsole.log('http app started');", "dangerousExampleEn": "1. process.on(\"uncaughtException\", function(err) {\n2. // log necessary error details to log files\n3. //process.exit();\n4. });\nLine 1: uncaughtException was used but the current status of the program is unknown because the process has not been terminated explicitly.", "safeExampleEn": "1. process.on(\"uncaughtException\", function(err) {\n2. // log necessary error details to log files\n3. process.exit();\n4. });\nLine 3: This is secure because the process is terminated after the errors are logged.", "contexts": [{"lineNo": 35, "eventType": "sink", "messageKey": "jschk.UNCAUGHT_EXCEPTION.JS.defect", "params": {}}]}} {"id": "a9ec980c0e6a364dfa7ebc554ab890e4c16c12f85d8905fc8e50e46f338142a0", "license": {"spdx": ["MIT"], "repo": "csanz/expressjs-example", "path": "lib/exceptions.js", "repo_head_hexsha": "c39963ab842d78fbcf0c87811bdc2bb9e6730fa1", "stack_hexsha": "5b14104bc5a4127de6767eeb334b80afd6ced2d9", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of uncaughtException", "issueDescriptionEn": "Using uncaughtException enables a developer to handle errors that could not be addressed by a developer beforehand. However, the official node document specifies that it should only be used as a last resort. This is because uncaughtException cannot guarantee a program will close after an error occurs.\nuncaughtException should be used for logging purposes. After logging the errors, the process needs to be terminated using process.exit();.", "issueLineNumber": 3, "entireCode": "var colors = require('colors');\n\nprocess.on('uncaughtException', function(err) {\n console.log(\"\\nERROR:\".red.bold);\n if (err.message) {\n console.log('\\nMessage: ' + err.message)\n }\n if (err.stack) {\n console.log('\\nStacktrace:')\n console.log('====================')\n console.log(err.stack);\n }\n});\nprocess.addListener('uncaughtException', function (err) {\n console.log('uncaughtException: ' + err, err);\n});", "dangerousExampleEn": "1. process.on(\"uncaughtException\", function(err) {\n2. // log necessary error details to log files\n3. //process.exit();\n4. });\nLine 1: uncaughtException was used but the current status of the program is unknown because the process has not been terminated explicitly.", "safeExampleEn": "1. process.on(\"uncaughtException\", function(err) {\n2. // log necessary error details to log files\n3. process.exit();\n4. });\nLine 3: This is secure because the process is terminated after the errors are logged.", "contexts": [{"lineNo": 3, "eventType": "sink", "messageKey": "jschk.UNCAUGHT_EXCEPTION.JS.defect", "params": {}}]}} {"id": "0c1d7c8065051fdf4ac48306c6b03aa6cb96193ab99e3ed6b0e4ffb306664d67", "license": {"spdx": ["MIT"], "repo": "vishnucprasad/MovieMaster", "path": "routes/theatre.js", "repo_head_hexsha": "cad4009ee0fbc71f788ee1b49e353a811568ca6c", "stack_hexsha": "cdc8015208f38b1bf0b72d99ae1247af3d2b647d", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Redirection to untrusted site", "issueDescriptionEn": "The Redirection to untrusted site checker finds instances of redirecting to a URL generated with an unvalidated external input.\nAlthough connecting to a client-provided URL is often believed to be safe, an attacker can modify the request and redirect the user to a malicious site.\nMaintain a whitelist of external site URLs and domains allowed for redirection, which needs to be checked when a user input is passed as a redirect URL.", "issueLineNumber": 331, "entireCode": "const express = require('express');\nconst router = express.Router();\nconst fs = require('fs');\nconst theatreHelpers = require('../helpers/theatreHelpers');\nconst passport = require('passport');\nconst date = require('date-and-time');\nconst isTheatre = require('../middleware/auth').isTheatre;\n\nrouter.get('/login', (req, res) => {\n if (req.isAuthenticated() && req.user.theatre) {\n res.redirect('/theatre');\n } else {\n if (req.session.messages) {\n res.render('theatre/login', { title: 'Theatre | Login', messages: req.session.messages, theatreStyle: true });\n req.session.messages = false;\n } else {\n res.render('theatre/login', { title: 'Theatre | Login', theatreStyle: true });\n }\n }\n});\n\nrouter.post('/login', passport.authenticate('theatre-login', { successRedirect: '/theatre', failureRedirect: '/theatre/login', failureFlash: true }));\n\nrouter.get('/auth/google', passport.authenticate('theatre-google-auth', { scope: ['profile', 'email'] }));\n\nrouter.get('/auth/google/callback', passport.authenticate('theatre-google-auth', { failureRedirect: '/theatre/popup', failureFlash: true }), (req, res) => {\n res.redirect('/theatre/popup');\n});\n\nrouter.get('/popup', (req, res) => {\n if (!req.isAuthenticated()) {\n req.session.messages = { error: 'Invalid Account' };\n }\n res.render('auth-popup-callback');\n});\n\nrouter.get('/logout', (req, res) => {\n req.logout();\n res.json({ status: true });\n});\n\nrouter.get('/', isTheatre, async function (req, res, next) {\n const totalShows = await theatreHelpers.getNumberOfShows(req.user._id);\n const totalScreens = await theatreHelpers.getNumberOfScreens(req.user._id);\n const totalBookings = await theatreHelpers.getNumberOfBookings(req.user._id);\n const paidBookings = await theatreHelpers.getNumberOfPayedBookings(req.user._id);\n const unpaidBookings = await theatreHelpers.getNumberOfUnpayedBookings(req.user._id);\n const currentMonthBookings = await theatreHelpers.getTheatreBookings(req.user._id, date.format(new Date(), 'YYYY'), date.format(new Date(), 'MM'), date.format(new Date(), 'DD'));\n const pastMonthBookings = await theatreHelpers.getTheatreBookings(req.user._id, date.format(new Date(), 'YYYY'), date.format(new Date(new Date().getFullYear(), new Date().getMonth(), 0), 'MM'), date.format(new Date(new Date().getFullYear(), new Date().getMonth(), 0), 'DD'));\n res.render('theatre/dashboard', { title: 'Theatre | Dashboard', theatre: req.user, totalShows, totalScreens, totalBookings, paidBookings, unpaidBookings, currentMonthBookings, pastMonthBookings });\n});\n\nrouter.post('/update-owner-picture/:id', isTheatre, (req, res) => {\n if (req.files.ownerPicture) {\n theatreHelpers.updateOwnerPicture(req.params.id, true).then((response) => {\n\n let image = req.files.ownerPicture;\n\n image.mv(`./public/images/theatre/${response.theatre._id}.jpg`, (err, done) => {\n if (err) {\n console.log(err);\n } else {\n console.log(done);\n }\n });\n req.flash('info', response.alertMessage);\n res.redirect('/theatre');\n }).catch((error) => {\n req.flash('error', error.errMessage);\n res.redirect('/theatre');\n });\n }\n});\n\nrouter.get('/remove-owner-picture/:id', isTheatre, (req, res) => {\n theatreHelpers.updateOwnerPicture(req.params.id, false).then((response) => {\n req.flash('info', response.alertMessage);\n fs.unlinkSync(`./public/images/theatre/${response.theatre._id}.jpg`);\n res.redirect('/theatre');\n }).catch((error) => {\n req.flash('error', error.errMessage);\n res.redirect('/theatre');\n });;\n});\n\nrouter.post('/update-theatre-details', isTheatre, (req, res) => {\n theatreHelpers.updateTheatreDetails(req.body, req.user._id).then((response) => {\n res.json(response);\n }).catch((error) => {\n res.redirect(error);\n });\n});\n\nrouter.post('/update-location', (req, res) => {\n theatreHelpers.updateLocation(req.body, req.user._id).then((response) => {\n res.json(response);\n }).catch((error) => {\n res.json(error);\n });\n});\n\nrouter.post('/change-password', isTheatre, (req, res) => {\n theatreHelpers.changePassword(req.body, req.user._id).then((response) => {\n res.json(response);\n }).catch((error) => {\n res.json(error);\n });\n});\n\nrouter.get('/screens', isTheatre, (req, res) => {\n theatreHelpers.getAllScreens(req.user._id).then((screens) => {\n res.render('theatre/screens', { title: 'Theatre | Screens', theatre: req.user, screens });\n });\n});\n\nrouter.get('/add-screens', isTheatre, (req, res) => {\n res.render('theatre/add-screens', { title: 'Admin | Add Screens', theatre: req.user });\n});\n\nrouter.post('/add-screens', isTheatre, (req, res) => {\n theatreHelpers.addScreens(req.body, req.user._id).then((response) => {\n req.flash('info', response.alertMessage);\n res.redirect('/theatre/screens');\n }).catch((error) => {\n req.flash('error', error.errMessage);\n res.redirect('/theatre/screens');\n });\n});\n\nrouter.get('/edit-screen/:id', isTheatre, (req, res) => {\n theatreHelpers.getScreen(req.params.id).then((screen) => {\n res.render('theatre/edit-screen', { title: 'Admin | Edit Screen', theatre: req.user, screen });\n }).catch((error) => {\n req.flash('error', error.errMessage);\n res.redirect('/theatre/screens');\n });\n});\n\nrouter.post('/edit-screen', isTheatre, (req, res) => {\n theatreHelpers.editScreen(req.body).then((response) => {\n req.flash('info', response.alertMessage);\n res.redirect('/theatre/screens');\n }).catch((error) => {\n req.flash('error', error.errMessage);\n res.redirect('/theatre/screens');\n });\n});\n\nrouter.post('/delete-screen', isTheatre, (req, res) => {\n theatreHelpers.deleteScreen(req.body.id).then((response) => {\n res.json(response);\n }).catch((error) => {\n res.json(error);\n });\n});\n\nrouter.get('/movie-management', isTheatre, (req, res) => {\n theatreHelpers.getAllMovies().then((movies) => {\n res.render('theatre/movie-management', { title: 'Theatre | Movie Management', theatre: req.user, movies, errMessage: req.session.errMessage, alertMessage: req.session.alertMessage });\n req.session.errMessage = false;\n req.session.alertMessage = false;\n });\n});\n\nrouter.get('/add-movies', isTheatre, (req, res) => {\n res.render('theatre/add-movies', { title: 'Theatre | Add Movies', theatre: req.user });\n});\n\nrouter.post('/add-movies', isTheatre, (req, res) => {\n theatreHelpers.addMovies(req.body, req.user._id).then((response) => {\n let image = req.files.moviePoster;\n\n image.mv(`./public/images/movies/posters/${response.data._id}.jpg`, (err, done) => {\n if (err) {\n console.log(err);\n } else {\n console.log(done);\n }\n });\n\n req.flash('info', response.alertMessage);\n res.redirect('/theatre/movie-management');\n }).catch((error) => {\n req.flash('error', error.errMessage);\n res.redirect('/theatre/movie-management');\n });\n});\n\nrouter.get('/edit-movie/:id', isTheatre, (req, res) => {\n theatreHelpers.getMovie(req.params.id).then((movie) => {\n res.render('theatre/edit-movie', { title: 'Theatre | Edit Movie', theatre: req.user, movie });\n }).catch((error) => {\n req.flash('error', error.errMessage);\n res.redirect('/theatre/movie-management');\n });\n});\n\nrouter.post('/edit-movie', isTheatre, (req, res) => {\n theatreHelpers.editMovie(req.body).then((response) => {\n req.flash('info', response.alertMessage);\n res.redirect('/theatre/movie-management');\n\n if (req.files.moviePoster) {\n let image = req.files.moviePoster;\n\n image.mv(`./public/images/movies/posters/${response.movieId}.jpg`, (err, done) => {\n if (err) {\n console.log(err);\n } else {\n console.log(done);\n }\n });\n }\n }).catch((error) => {\n req.flash('error', error.errMessage);\n res.redirect('/theatre/movie-management');\n });\n});\n\nrouter.post('/delete-movie', isTheatre, (req, res) => {\n theatreHelpers.deleteMovie(req.body.id, req.user._id).then((response) => {\n fs.unlinkSync(`./public/images/movies/posters/${req.body.id}.jpg`);\n res.json(response);\n }).catch((error) => {\n res.json(error);\n });\n});\n\nrouter.get('/upcoming-movies', isTheatre, (req, res) => {\n theatreHelpers.getAllUpcomingMovies(req.user._id).then((movies) => {\n res.render('theatre/upcoming-movies', { title: 'Theatre | Upcoming Movies', theatre: req.user, movies });\n });\n});\n\nrouter.get('/add-upcoming-movies', isTheatre, (req, res) => {\n res.render('theatre/add-upcoming-movies', { title: 'Theatre | Add Movies', theatre: req.user });\n});\n\nrouter.post('/add-upcoming-movies', isTheatre, (req, res) => {\n theatreHelpers.addUpcomingMovies(req.body, req.user._id).then((response) => {\n let image = req.files.moviePoster;\n\n image.mv(`./public/images/movies/upcoming-movies/posters/${response.data._id}.jpg`, (err, done) => {\n if (err) {\n console.log(err);\n } else {\n console.log(done);\n }\n });\n\n req.flash('info', response.alertMessage);\n res.redirect('/theatre/upcoming-movies');\n }).catch((error) => {\n req.flash('error', error.errMessage);\n res.redirect('/theatre/upcoming-movies');\n });\n});\n\nrouter.get('/edit-upcoming-movie/:id', isTheatre, (req, res) => {\n theatreHelpers.getUpcomingMovie(req.params.id).then((movie) => {\n res.render('theatre/edit-upcoming-movie', { title: 'Theatre | Edit Upcoming Movie', theatre: req.user, movie });\n }).catch((error) => {\n req.flash('error', error.errMessage);\n res.redirect('/theatre/upcoming-movies');\n });\n});\n\nrouter.post('/edit-upcoming-movie', isTheatre, (req, res) => {\n theatreHelpers.editUpcomingMovie(req.body).then((response) => {\n req.flash('info', response.alertMessage);\n res.redirect('/theatre/upcoming-movies');\n\n if (req.files.moviePoster) {\n let image = req.files.moviePoster;\n\n image.mv(`./public/images/movies/upcoming-movies/posters/${response.movieId}.jpg`, (err, done) => {\n if (err) {\n console.log(err);\n } else {\n console.log(done);\n }\n });\n }\n }).catch((error) => {\n req.flash('error', error.errMessage);\n res.redirect('/theatre/upcoming-movies');\n });\n});\n\nrouter.post('/delete-upcoming-movie', isTheatre, (req, res) => {\n theatreHelpers.deleteUpcomingMovie(req.body.id).then((response) => {\n fs.unlinkSync(`./public/images/movies/upcoming-movies/posters/${req.body.id}.jpg`);\n res.json(response);\n }).catch((error) => {\n res.json(error);\n });\n});\n\nrouter.get('/view-schedule/:id', isTheatre, (req, res) => {\n theatreHelpers.getScreen(req.params.id).then(async (screen) => {\n const shows = await theatreHelpers.getAllShows(req.params.id);\n res.render('theatre/view-schedule', { title: 'Theatre | View Schedule', theatre: req.user, screen, shows });\n }).catch((error) => {\n req.flash('error', error.errMessage);\n res.redirect('/theatre/screens');\n });\n});\n\nrouter.get('/add-shows/:id', isTheatre, (req, res) => {\n theatreHelpers.getAllMovies().then((movies) => {\n res.render('theatre/add-shows', { title: 'Theatre | Add Shows', theatre: req.user, screenId: req.params.id, movies });\n });\n});\n\nrouter.post('/add-shows', isTheatre, (req, res) => {\n theatreHelpers.addShows(req.body).then((response) => {\n req.flash('info', response.alertMessage);\n res.redirect(`/theatre/view-schedule/${response.screenId}`);\n }).catch((error) => {\n req.flash('error', error.errMessage);\n res.redirect(`/theatre/view-schedule/${error.screenId}`);\n });\n});\n\nrouter.get('/edit-show', isTheatre, (req, res) => {\n theatreHelpers.getAllMovies().then(async (movies) => {\n const show = await theatreHelpers.getShow(req.query);\n res.render('theatre/edit-show', { title: 'Theatre | Edit Show', theatre: req.user, show, movies });\n }).catch((error) => {\n req.flash('error', error.errMessage);\n res.redirect(`/theatre/view-schedule/${req.query.screenId}`);\n });\n});\n\nrouter.post('/edit-show', isTheatre, (req, res) => {\n theatreHelpers.editShow(req.body).then((response) => {\n req.flash('info', response.alertMessage);\n res.redirect(`/theatre/view-schedule/${req.body.screenId}`)\n }).catch((error) => {\n req.flash('error', error.errMessage);\n res.redirect(`/theatre/view-schedule/${req.body.screenId}`)\n });\n});\n\nrouter.post('/delete-show', isTheatre, (req, res) => {\n theatreHelpers.deleteShow(req.body).then((response) => {\n res.json(response);\n }).catch((error) => {\n res.json(error);\n });\n});\n\nrouter.post('/get-time-slots', (req, res) => {\n theatreHelpers.getTimeSlots(req.body).then((slots) => {\n res.json(slots);\n });\n});\n\nrouter.get('/users-activity', isTheatre, (req, res) => {\n theatreHelpers.getUsers(req.user._id).then((users) => {\n res.render('theatre/users-activity', { title: 'Theatre | Users Activity', theatre: req.user, users });\n });\n});\n\nrouter.get('/profile', isTheatre, (req, res) => {\n res.render('theatre/profile', { title: 'Theatre | Profile', theatre: req.user });\n});\n\nmodule.exports = router;", "dangerousExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/dan', function (req, res) {\n5. const url = req.body.profile_url;\n6. try{\n7. res.redirect(url);\n8. }catch (e) {\n9. return res.status(500).send(\"ERROR\");\n10. }\n11. });\n12. \n13. module.exports = router;\nLine 7: A string variable URL of an unvalidated external input is used to connect.", "safeExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/safe', function (req, res) {\n5. const url = req.body.profile_url;\n6. const white_list = [\"https://www.safeurl.com\", \"https://www.verified.com\"];\n7. if (white_list.indexOf(url) < 0) {\n8. return res.status(500).send(\"url not allowed\");\n9. } else {\n10. try {\n11. res.redirect(url);\n12. } catch (e) {\n13. return res.status(500).send(\"ERROR\");\n14. }\n15. }\n16. });\n17. \n18. module.exports = router;\nLine 7-9: Validate external inputs through a filter function.", "contexts": [{"lineNo": 331, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "req"}}, {"lineNo": 331, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "redirect"}}]}} {"id": "a5270f784aed38a049f6eb10eb3580082df969f8a57ac674001302778b9db897", "license": {"spdx": ["MIT"], "repo": "gNabeen/simple-discordjs-dashboard", "path": "dashboard/dashboard.js", "repo_head_hexsha": "376b4f177d04e570b9f9bcd305bb660f9170a61d", "stack_hexsha": "52f9f466478e2315de370393ecd94810eee308e6", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Redirection to untrusted site", "issueDescriptionEn": "The Redirection to untrusted site checker finds instances of redirecting to a URL generated with an unvalidated external input.\nAlthough connecting to a client-provided URL is often believed to be safe, an attacker can modify the request and redirect the user to a malicious site.\nMaintain a whitelist of external site URLs and domains allowed for redirection, which needs to be checked when a user input is passed as a redirect URL.", "issueLineNumber": 190, "entireCode": "/* eslint-disable no-self-assign */\n/* eslint-disable no-inline-comments */\n\n// We import modules.\nconst url = require(\"url\");\nconst ejs = require(\"ejs\");\nconst path = require(\"path\");\nconst chalk = require(\"chalk\");\nconst express = require(\"express\");\nconst config = require(\"../config\");\nconst passport = require(\"passport\");\nconst bodyParser = require(\"body-parser\");\nconst session = require(\"express-session\");\nconst { Permissions } = require(\"discord.js\");\nconst GuildSettings = require(\"../models/settings\");\nconst Strategy = require(\"passport-discord\").Strategy;\nconst { boxConsole } = require(\"../functions/boxConsole\");\n\n// We instantiate express app and the session store.\nconst app = express();\nconst MemoryStore = require(\"memorystore\")(session);\n\n// We export the dashboard as a function which we call in ready event.\nmodule.exports = async (client) => {\n // We declare absolute paths.\n const dataDir = path.resolve(`${process.cwd()}${path.sep}dashboard`); // The absolute path of current this directory.\n const templateDir = path.resolve(`${dataDir}${path.sep}templates`); // Absolute path of ./templates directory.\n\n // Deserializing and serializing users without any additional logic.\n passport.serializeUser((user, done) => done(null, user));\n passport.deserializeUser((obj, done) => done(null, obj));\n\n // Validating the url by creating a new instance of an Url then assign an object with the host and protocol properties.\n // If a custom domain is used, we take the protocol, then the hostname and then we add the callback route.\n // Ex: Config key: https://localhost/ will have - hostname: localhost, protocol: http\n\n let domain;\n let callbackUrl;\n\n try {\n const domainUrl = new URL(config.domain);\n domain = {\n host: domainUrl.hostname,\n protocol: domainUrl.protocol,\n };\n } catch (e) {\n console.log(e);\n throw new TypeError(\"Invalid domain specific in the config file.\");\n }\n\n if (config.usingCustomDomain) {\n callbackUrl = `${domain.protocol}//${domain.host}/callback`;\n } else {\n callbackUrl = `${domain.protocol}//${domain.host}${\n config.port == 80 ? \"\" : `:${config.port}`\n }/callback`;\n }\n\n // This line is to inform users where the system will begin redirecting the users.\n // And can be removed.\n const msg = `${chalk.red.bold(\"Info:\")} ${chalk.green.italic(\n \"Make sure you have added the Callback URL to the Discord's OAuth Redirects section in the developer portal.\",\n )}`;\n boxConsole([\n `${chalk.red.bold(\"Callback URL:\")} ${chalk.white.bold.italic.underline(\n callbackUrl,\n )}`,\n `${chalk.red.bold(\n \"Discord Developer Portal:\",\n )} ${chalk.white.bold.italic.underline(\n `https://discord.com/developers/applications/${config.id}/oauth2`,\n )}`,\n msg,\n ]);\n\n // We set the passport to use a new discord strategy, we pass in client id, secret, callback url and the scopes.\n /** Scopes:\n\t * - Identify: Avatar's url, username and discriminator.\n\t * - Guilds: A list of partial guilds.\n\t */\n passport.use(\n new Strategy(\n {\n clientID: config.id,\n clientSecret: config.clientSecret,\n callbackURL: callbackUrl,\n scope: [\"identify\", \"guilds\", \"email\",\n \"guilds.join\"],\n },\n (accessToken, refreshToken, profile, done) => {\n // On login we pass in profile with no logic.\n process.nextTick(() => done(null, profile));\n },\n ),\n );\n\n // We initialize the memorystore middleware with our express app.\n app.use(\n session({\n store: new MemoryStore({ checkPeriod: 86400000 }),\n secret:\n\t\t\t\t\"%^%^%^%^^#@%#&^$^$%@$^$&%#$%@#$%$^%&$%^#$%@#$%#E%#%@$FEErfgr3g#%GT%536c53cc6%5%tv%4y4hrgrggrgrgf4n\",\n resave: false,\n saveUninitialized: false,\n }),\n );\n\n // We initialize passport middleware.\n app.use(passport.initialize());\n app.use(passport.session());\n\n // We bind the domain.\n app.locals.domain = config.domain.split(\"//\")[1];\n\n // We set out templating engine.\n app.engine(\"ejs\", ejs.renderFile);\n app.set(\"view engine\", \"ejs\");\n\n // We initialize body-parser middleware to be able to read forms.\n app.use(bodyParser.json());\n app.use(\n bodyParser.urlencoded({\n extended: true,\n }),\n );\n\n // We host all of the files in the assets using their name in the root address.\n // A style.css file will be located at http:///style.css\n // You can link it in any template using src=\"/assets/filename.extension\"\n app.use(\"/\", express.static(path.resolve(`${dataDir}${path.sep}assets`)));\n\n // We declare a renderTemplate function to make rendering of a template in a route as easy as possible.\n const renderTemplate = (res, req, template, data = {}) => {\n // Default base data which passed to the ejs template by default.\n const baseData = {\n bot: client,\n path: req.path,\n user: req.isAuthenticated() ? req.user : null,\n };\n // We render template using the absolute path of the template and the merged default data with the additional data provided.\n res.render(\n path.resolve(`${templateDir}${path.sep}${template}`),\n Object.assign(baseData, data),\n );\n };\n\n // We declare a checkAuth function middleware to check if an user is logged in or not, and if not redirect him.\n const checkAuth = (req, res, next) => {\n // If authenticated we forward the request further in the route.\n if (req.isAuthenticated()) return next();\n // If not authenticated, we set the url the user is redirected to into the memory.\n req.session.backURL = req.url;\n // We redirect user to login endpoint/route.\n res.redirect(\"/login\");\n };\n\n // Login endpoint.\n app.get(\n \"/login\",\n (req, res, next) => {\n // We determine the returning url.\n if (req.session.backURL) {\n req.session.backURL = req.session.backURL;\n } else if (req.headers.referer) {\n const parsed = url.parse(req.headers.referer);\n if (parsed.hostname === app.locals.domain) {\n req.session.backURL = parsed.path;\n }\n } else {\n req.session.backURL = \"/\";\n }\n // Forward the request to the passport middleware.\n next();\n },\n passport.authenticate(\"discord\"),\n );\n\n // Callback endpoint.\n app.get(\n \"/callback\",\n passport.authenticate(\"discord\", { failureRedirect: \"/\" }),\n /* We authenticate the user, if user canceled we redirect him to index. */ (\n req,\n res,\n ) => {\n // If user had set a returning url, we redirect him there, otherwise we redirect him to index.\n if (req.session.backURL) {\n const backURL = req.session.backURL;\n req.session.backURL = null;\n res.redirect(backURL);\n } else {\n res.redirect(\"/\");\n }\n },\n );\n\n // Logout endpoint.\n app.get(\"/logout\", function(req, res) {\n // We destroy the session.\n req.session.destroy(() => {\n // We logout the user.\n req.logout();\n // We redirect user to index.\n res.redirect(\"/\");\n });\n });\n\n // Index endpoint.\n app.get(\"/\", (req, res) => {\n renderTemplate(res, req, \"index.ejs\", {\n discordInvite: config.discordInvite,\n });\n });\n\n // Dashboard endpoint.\n app.get(\"/dashboard\", checkAuth, (req, res) => {\n renderTemplate(res, req, \"dashboard.ejs\", { perms: Permissions });\n });\n app.get(\"/profile\", checkAuth, (req, res) => {\n renderTemplate(res, req, \"profile.ejs\", { perms: Permissions });\n });\n\n // Settings endpoint.\n app.get(\"/dashboard/:guildID\", checkAuth, async (req, res) => {\n // We validate the request, check if guild exists, member is in guild and if member has minimum permissions, if not, we redirect it back.\n const guild = client.guilds.cache.get(req.params.guildID);\n if (!guild) return res.redirect(\"/dashboard\");\n let member = guild.members.cache.get(req.user.id);\n if (!member) {\n try {\n await guild.members.fetch();\n member = guild.members.cache.get(req.user.id);\n } catch (err) {\n console.error(`Couldn't fetch the members of ${guild.id}: ${err}`);\n }\n }\n if (!member) return res.redirect(\"/dashboard\");\n if (!member.permissions.has(Permissions.FLAGS.MANAGE_GUILD)) {\n return res.redirect(\"/dashboard\");\n }\n\n // We retrive the settings stored for this guild.\n let storedSettings = await GuildSettings.findOne({ guildID: guild.id });\n if (!storedSettings) {\n // If there are no settings stored for this guild, we create them and try to retrive them again.\n const newSettings = new GuildSettings({\n guildID: guild.id,\n });\n await newSettings.save().catch((e) => {\n console.log(e);\n });\n storedSettings = await GuildSettings.findOne({ guildID: guild.id });\n }\n\n renderTemplate(res, req, \"settings.ejs\", {\n guild,\n settings: storedSettings,\n alert: null,\n });\n });\n\n // Settings endpoint.\n app.post(\"/dashboard/:guildID\", checkAuth, async (req, res) => {\n // We validate the request, check if guild exists, member is in guild and if member has minimum permissions, if not, we redirect it back.\n const guild = client.guilds.cache.get(req.params.guildID);\n if (!guild) return res.redirect(\"/dashboard\");\n const member = guild.members.cache.get(req.user.id);\n if (!member) return res.redirect(\"/dashboard\");\n if (!member.permissions.has(\"MANAGE_GUILD\")) {\n return res.redirect(\"/dashboard\");\n }\n // We retrive the settings stored for this guild.\n let storedSettings = await GuildSettings.findOne({ guildID: guild.id });\n if (!storedSettings) {\n // If there are no settings stored for this guild, we create them and try to retrive them again.\n const newSettings = new GuildSettings({\n guildID: guild.id,\n });\n await newSettings.save().catch((e) => {\n console.log(e);\n });\n storedSettings = await GuildSettings.findOne({ guildID: guild.id });\n }\n\n // We set the prefix of the server settings to the one that was sent in request from the form.\n storedSettings.prefix = req.body.prefix;\n // We save the settings.\n await storedSettings.save().catch((e) => {\n console.log(e);\n });\n\n // We render the template with an alert text which confirms that settings have been saved.\n renderTemplate(res, req, \"settings.ejs\", {\n guild,\n settings: storedSettings,\n alert: \"Your settings have been saved.\",\n });\n });\n\n app.listen(config.port, null, null, () =>\n console.log(`Dashboard is up and running on port ${config.port}.`),\n );\n};", "dangerousExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/dan', function (req, res) {\n5. const url = req.body.profile_url;\n6. try{\n7. res.redirect(url);\n8. }catch (e) {\n9. return res.status(500).send(\"ERROR\");\n10. }\n11. });\n12. \n13. module.exports = router;\nLine 7: A string variable URL of an unvalidated external input is used to connect.", "safeExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/safe', function (req, res) {\n5. const url = req.body.profile_url;\n6. const white_list = [\"https://www.safeurl.com\", \"https://www.verified.com\"];\n7. if (white_list.indexOf(url) < 0) {\n8. return res.status(500).send(\"url not allowed\");\n9. } else {\n10. try {\n11. res.redirect(url);\n12. } catch (e) {\n13. return res.status(500).send(\"ERROR\");\n14. }\n15. }\n16. });\n17. \n18. module.exports = router;\nLine 7-9: Validate external inputs through a filter function.", "contexts": [{"lineNo": 187, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "187"}}, {"lineNo": 188, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 189, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "req"}}, {"lineNo": 190, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "redirect"}}]}} {"id": "bdf0b40fd82e1b7610191c190efb4a1a541c7645a8020b9d10cc2faf6ccce1e0", "license": {"spdx": ["MIT"], "repo": "Aaron-Lin-74/learn-animal-mern-project", "path": "client/src/Pages/Animals/AllAnimals/AnimalTypeSection/AnimalTypeSection.js", "repo_head_hexsha": "c5f55ed9c607ccf8e4b378f9e2d9ae933a66d147", "stack_hexsha": "7cefdeaf89ea22478e1d906e9969b74cc7a506d1", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Redirection to untrusted site", "issueDescriptionEn": "The Redirection to untrusted site checker finds instances of redirecting to a URL generated with an unvalidated external input.\nAlthough connecting to a client-provided URL is often believed to be safe, an attacker can modify the request and redirect the user to a malicious site.\nMaintain a whitelist of external site URLs and domains allowed for redirection, which needs to be checked when a user input is passed as a redirect URL.", "issueLineNumber": 46, "entireCode": "import React from 'react'\nimport { useSelector } from 'react-redux'\nimport './AnimalTypeSection.css'\nimport { VscFoldDown } from 'react-icons/vsc'\nimport { BsStarFill } from 'react-icons/bs'\nimport { Fade } from 'react-awesome-reveal'\nimport {\n selectAllTypesPlural,\n selectPremiumTypes,\n} from '../../../../features/animal/animalSlice'\nimport useUtils from '../../../../hooks/useUtils'\nimport Button from '../../../../components/Button/Button'\n\nfunction AnimalTypeSection({ type, description }) {\n const premiumTypes = useSelector(selectPremiumTypes)\n const allTypesPlural = useSelector(selectAllTypesPlural)\n const { redirect } = useUtils()\n\n // Check is current section the last section\n const isLastSection =\n allTypesPlural.indexOf(type) === allTypesPlural.length - 1\n\n // If not, get the next type of animals\n const nextType = isLastSection\n ? ''\n : allTypesPlural[allTypesPlural.indexOf(type) + 1]\n\n return (\n \n \n
    \n

    {type}

    \n

    {description}

    \n
    \n
    \n \n
    \n \n redirect(`https://en.wikipedia.org/wiki/${type}`)}\n >\n Learn More\n \n\n \n \n \n
    \n
    \n \n )\n}\n\nexport default AnimalTypeSection", "dangerousExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/dan', function (req, res) {\n5. const url = req.body.profile_url;\n6. try{\n7. res.redirect(url);\n8. }catch (e) {\n9. return res.status(500).send(\"ERROR\");\n10. }\n11. });\n12. \n13. module.exports = router;\nLine 7: A string variable URL of an unvalidated external input is used to connect.", "safeExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/safe', function (req, res) {\n5. const url = req.body.profile_url;\n6. const white_list = [\"https://www.safeurl.com\", \"https://www.verified.com\"];\n7. if (white_list.indexOf(url) < 0) {\n8. return res.status(500).send(\"url not allowed\");\n9. } else {\n10. try {\n11. res.redirect(url);\n12. } catch (e) {\n13. return res.status(500).send(\"ERROR\");\n14. }\n15. }\n16. });\n17. \n18. module.exports = router;\nLine 7-9: Validate external inputs through a filter function.", "contexts": [{"lineNo": 46, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "type"}}, {"lineNo": 46, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "redirect"}}]}} {"id": "3bcf0097f1164b324049d7042eee93b4ce40a8e62642f753f72d72f9d5125fa5", "license": {"spdx": ["MIT"], "repo": "DFE-Digital/login.dfe.services", "path": "src/app/users/selectOrganisation.js", "repo_head_hexsha": "3a9a0bf9518b87257f95ebc456fe465e9eab4b1b", "stack_hexsha": "7084259efaa3ab6a7a86048e13e089a11c85acff", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Redirection to untrusted site", "issueDescriptionEn": "The Redirection to untrusted site checker finds instances of redirecting to a URL generated with an unvalidated external input.\nAlthough connecting to a client-provided URL is often believed to be safe, an attacker can modify the request and redirect the user to a malicious site.\nMaintain a whitelist of external site URLs and domains allowed for redirection, which needs to be checked when a user input is passed as a redirect URL.", "issueLineNumber": 142, "entireCode": "'use strict';\nconst {\n getApproverOrgsFromReq,\n getUserOrgsFromReq,\n isUserManagement,\n isUserApprover,\n isUserEndUser,\n getOrgNaturalIdentifiers,\n isOrganisationInvite,\n isViewOrganisationRequests,\n isRequestService,\n isAddService,\n isEditService,\n} = require('./utils');\nconst { recordRequestServiceBannerAck } = require('../../infrastructure/helpers/common');\n\nconst buildAdditionalOrgDetails = (userOrgs) => {\n userOrgs.forEach((userOrg) => {\n const org = userOrg.organisation;\n userOrg.naturalIdentifiers = getOrgNaturalIdentifiers(org);\n });\n};\n\nconst renderSelectOrganisationPage = (req, res, model) => {\n const isManage = isUserManagement(req);\n res.render(`users/views/${isManage ? 'selectOrganisation' : 'selectOrganisationRedesigned'}`, {\n ...model,\n currentPage: isManage ? 'users' : 'services',\n });\n};\n\nconst handleRedirectAfterOrgSelected = (req, res, model, isApprover, isManage) => {\n const selectedOrg = model.organisations.filter((o) => o.organisation.id === model.selectedOrganisation);\n const isApproverForSelectedOrg = selectedOrg.filter((r) => r.role.id === 10000).length > 0;\n\n if (isAddService(req) || isRequestService(req)) {\n if (isApproverForSelectedOrg) {\n return res.redirect(`/approvals/${model.selectedOrganisation}/users/${req.user.sub}/associate-services`);\n }\n\n if (isApprover && !isManage) {\n //show banner to an approver who is also an end-user\n res.flash('title', `Important`);\n res.flash('heading', `You are not an approver at: ${selectedOrg[0].organisation.name}`);\n res.flash(\n 'message',\n `Because you are not an approver at this organisation, you will need to request access to a service in order to use it. This request will be sent to approvers at ${selectedOrg[0].organisation.name}.`,\n );\n }\n return res.redirect(`/request-service/${model.selectedOrganisation}/users/${req.user.sub}`);\n } else if (isOrganisationInvite(req)) {\n return res.redirect(`/approvals/${model.selectedOrganisation}/users/new-user`);\n } else if (isViewOrganisationRequests(req)) {\n return res.redirect(`/access-requests/${model.selectedOrganisation}/requests`);\n } else {\n return res.redirect(`/approvals/users`);\n }\n};\n\nconst setUserOrgs = (req) => {\n const isManage = isUserManagement(req);\n const isApprover = isUserApprover(req);\n const isEndUser = isUserEndUser(req);\n const hasDualPermission = isEndUser && isApprover;\n req.userOrganisations =\n (hasDualPermission && !isManage) || !isApprover ? getUserOrgsFromReq(req) : getApproverOrgsFromReq(req);\n return { isApprover, hasDualPermission, isEndUser, isManage };\n};\n\nconst buildBackLink = (req) => {\n let backRedirect;\n const isManage = isUserManagement(req);\n if (isManage) {\n backRedirect = '/approvals/users';\n } else {\n backRedirect = '/my-services';\n }\n return backRedirect;\n};\n\nconst get = async (req, res) => {\n const { isApprover, isEndUser, hasDualPermission, isManage } = setUserOrgs(req);\n\n if (isEndUser && !isApprover && isManage) {\n //Recording request-a-service banner acknowledgement by end-user\n await recordRequestServiceBannerAck(req.session.user.uid);\n }\n\n buildAdditionalOrgDetails(req.userOrganisations);\n\n const model = {\n csrfToken: req.csrfToken(),\n title: 'Select Organisation',\n organisations: req.userOrganisations,\n currentPage: 'users',\n selectedOrganisation: req.session.user ? req.session.user.organisation : null,\n validationMessages: {},\n backLink: buildBackLink(req),\n isApprover,\n hasDualPermission,\n };\n\n renderSelectOrganisationPage(req, res, model);\n};\n\nconst validate = (req) => {\n const selectedOrg = req.body.selectedOrganisation;\n const model = {\n organisations: req.userOrganisations,\n currentPage: 'users',\n selectedOrganisation: selectedOrg,\n validationMessages: {},\n backLink: buildBackLink(req),\n };\n\n if (model.selectedOrganisation === undefined || model.selectedOrganisation === null) {\n model.validationMessages.selectedOrganisation = 'Select an organisation to continue.';\n }\n return model;\n};\n\nconst post = async (req, res) => {\n const { isApprover, hasDualPermission, isManage } = setUserOrgs(req);\n\n buildAdditionalOrgDetails(req.userOrganisations);\n\n const model = validate(req);\n model.isApprover = isApprover;\n model.hasDualPermission = hasDualPermission;\n\n // persist selected org in session\n if (!req.session.user) {\n req.session.user = {};\n }\n req.session.user.organisation = model.selectedOrganisation;\n\n if (Object.keys(model.validationMessages).length > 0) {\n model.csrfToken = req.csrfToken();\n return renderSelectOrganisationPage(req, res, model);\n }\n\n handleRedirectAfterOrgSelected(req, res, model, isApprover, isManage);\n};\n\nmodule.exports = {\n get,\n post,\n};", "dangerousExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/dan', function (req, res) {\n5. const url = req.body.profile_url;\n6. try{\n7. res.redirect(url);\n8. }catch (e) {\n9. return res.status(500).send(\"ERROR\");\n10. }\n11. });\n12. \n13. module.exports = router;\nLine 7: A string variable URL of an unvalidated external input is used to connect.", "safeExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/safe', function (req, res) {\n5. const url = req.body.profile_url;\n6. const white_list = [\"https://www.safeurl.com\", \"https://www.verified.com\"];\n7. if (white_list.indexOf(url) < 0) {\n8. return res.status(500).send(\"url not allowed\");\n9. } else {\n10. try {\n11. res.redirect(url);\n12. } catch (e) {\n13. return res.status(500).send(\"ERROR\");\n14. }\n15. }\n16. });\n17. \n18. module.exports = router;\nLine 7-9: Validate external inputs through a filter function.", "contexts": [{"lineNo": 135, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 142, "eventType": "source", "messageKey": "jschk.COMMON.value.passed.to.anonymous", "params": {"arg0": "$handleRedirectAfterOrgSelected$vr(req,res,mo~33)1"}}, {"lineNo": 142, "eventType": "source", "messageKey": "jschk.COMMON.called.anonymous", "params": {"arg0": "$handleRedirectAfterOrgSelected$vr(req,res,mo~33)1"}}, {"lineNo": 142, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "redirect"}}]}} {"id": "6bc028a9440b1f466e6cd97f9cd927f570257c238678973965641e76cafe982c", "license": {"spdx": ["CC0-1.0"], "repo": "satejsarker/elctro-D", "path": "server/routes/index.js", "repo_head_hexsha": "5bf887b43dde0a7885f30f53d997c45056b46f8b", "stack_hexsha": "70c82dae7ae59ddd905f883d27b3e72163b2d004", "match": "repo_path"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Redirection to untrusted site", "issueDescriptionEn": "The Redirection to untrusted site checker finds instances of redirecting to a URL generated with an unvalidated external input.\nAlthough connecting to a client-provided URL is often believed to be safe, an attacker can modify the request and redirect the user to a malicious site.\nMaintain a whitelist of external site URLs and domains allowed for redirection, which needs to be checked when a user input is passed as a redirect URL.", "issueLineNumber": 130, "entireCode": "var express = require('express');\nvar router = express.Router();\nvar mysql = require('mysql');\nvar sqlq = require('.././sql/sql');\nvar date = require('date-and-time');\n\nvar now = new Date();\n\n\nvar connection = mysql.createConnection({\n host: \"172.16.31.10\",\n user: \"dbcdb\",\n password: \"\",\n database: \"content_manager\",\n multipleStatements: true\n});\nconnection.connect(function(err) {\n if (err) throw err;\n console.log(\"Connected!\");\n});\n\n\n\n\n\n\n\nrouter.route('/test').get(function(req, res, next) {\n var newsid;\n\n sqlq.sqlid().then(function(id) {\n console.log(id);\n newsid = id;\n\n connection.query(\"select * from news where id=? \", [id], function(err, doc) {\n console.log(doc);\n res.render('hello', {\n value: doc\n })\n })\n })\n}).post(function(req, res, next) {\n req.flash('info', 'Flash is back!')\n var user = { name: req.body.userName, password: }\n connection.query(\"insert into user set?\", user, function(err, doc) {\n if (err) throw err;\n })\n res.redirect('/');\n})\n\n\n\n\nrouter.get('/',isLoggedIn, function(req, res, next) {\n connection.query('SELECT news.*, users.username FROM news INNER JOIN details ON news.id = details.news_id INNER JOIN users ON news.user_id = users.id', function(error, docs) {\n console.log(JSON.stringify (req.user));\n res.render('pages/dashboard.hbs', {\n title: 'News List',\n news: docs,\n info: req.flash('info'),\n user:req.user\n })\n })\n});\n\n\n\nrouter.route('/news-update/:news').get(isLoggedIn,function(req, res, next) {\n var id = req.params.news;\n\n connection.query('SELECT * FROM news INNER JOIN details ON news.id = details.news_id WHERE news.id = ?', [id], function(error, docs) {\n\n connection.query('SELECT * FROM categories', function(error, categorylists) {\n\n connection.query('SELECT * FROM category_news INNER JOIN categories ON category_news.category_id = categories.id WHERE category_news.news_id = ?', [id], function(error, category_docs) {\n\n\n res.render('pages/update-news', {\n title: 'News Update',\n id: docs[0].news_id,\n headline: docs[0].headline,\n photo: docs[0].photo,\n top_news: docs[0].top_news,\n breaking_news: docs[0].breaking_news,\n video: docs[0].video,\n description: docs[0].description,\n category_list: categorylists,\n sel_category: category_docs,\n message: req.flash('catagory')\n })\n })\n })\n\n })\n}).post(function(req, res) {\n var id = req.params.news;\n var headline = req.body.headline;\n\n var topNews = Boolean(req.body.newsT);\n connection.query(\"update news set headline=?,top_news=? where id=?\", [headline, topNews, id], function(error, doc) {\n if (error) throw error;\n\n });\n if (req.body.description) {\n connection.query(\"update details set description=?, updated_at=? where news_id=?\", [req.body.description, date.format(now, 'YYYY/MM/DD HH:mm:ss'), id], function(err, doc) {\n if (err) throw err;\n\n })\n }\n if (req.body.optionsCheckboxes) {\n var values = [];\n var select = req.param('optionsCheckboxes');\n\n for (var i = 0; i < select.length; i++) {\n values.push([id, select[i]]);\n\n }\n connection.query('delete from category_news where news_id=?', id);\n\n\n connection.query('INSERT INTO category_news (news_id, category_id) VALUES ? on duplicate key update news_id=? ', [values, id], function(err, result) {\n if (err) {\n throw err;\n }\n });\n res.redirect('/');\n\n } else {\n req.flash('catagory',isLoggedIn, 'Catagory have to select');\n res.redirect('/news-update/' + id);\n\n }\n})\nrouter.get('/delete/:id',isLoggedIn, (req, res) => {\n var id = req.params.id;\n console.log(id);\n connection.query('delete from details where news_id=?', id, function(err, doc) {\n if (err) throw err;\n else {\n console.log(doc);\n res.redirect('/');\n }\n })\n})\nrouter.get('/activate/:id',isLoggedIn,(req,res)=>{\n var id=req.params.id;\n connection.query('update news set active=1 where id=?',id,function (err,doc) {\n if(err) throw err;\n else{\n res.redirect('/');\n } \n })\n})\n\n\nrouter.get('/notdraft/:id',isLoggedIn,(req,res)=>{\n var id=req.params.id;\n connection.query('update news set draft=0 where id=?',id,function (err,doc) {\n if(err) throw err;\n else{\n res.redirect('/');\n } \n })\n})\n\nrouter.get('/disactivate/:id',isLoggedIn,(req,res)=>{\n var id=req.params.id;\n connection.query('update news set active=0 where id=?',id,function (err,doc) {\n if(err) throw err;\n else{\n res.redirect('/');\n } \n })\n})\n\n\n\n\nrouter.get('/image-list',isLoggedIn, function(req, res, next) {\n res.render('pages/image-list', { title: 'Image List' });\n});\n\nrouter.get('/image-upload',isLoggedIn, function(req, res, next) {\n res.render('pages/image-upload', { title: 'Image Upload' });\n});\n\nrouter.get('/statistics',isLoggedIn, function(req, res, next) {\n res.render('pages/statistics', { title: 'Statistics' });\n});\n\nrouter.get('/profile',isLoggedIn, function(req, res, next) {\n res.render('pages/profile', { title: 'User Profile' });\n});\n\n\n\nrouter.get('/logout',isLoggedIn, function(req, res) {\n req.logout();\n res.redirect('/users/');\n});\n\n\n// route middleware to make sure\nfunction isLoggedIn(req, res, next) {\n\n // if user is authenticated in the session, carry on\n if (req.isAuthenticated())\n return next();\n\n // if they aren't redirect them to the home page\n res.redirect('/');\n}\n\nmodule.exports = router;", "dangerousExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/dan', function (req, res) {\n5. const url = req.body.profile_url;\n6. try{\n7. res.redirect(url);\n8. }catch (e) {\n9. return res.status(500).send(\"ERROR\");\n10. }\n11. });\n12. \n13. module.exports = router;\nLine 7: A string variable URL of an unvalidated external input is used to connect.", "safeExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/safe', function (req, res) {\n5. const url = req.body.profile_url;\n6. const white_list = [\"https://www.safeurl.com\", \"https://www.verified.com\"];\n7. if (white_list.indexOf(url) < 0) {\n8. return res.status(500).send(\"url not allowed\");\n9. } else {\n10. try {\n11. res.redirect(url);\n12. } catch (e) {\n13. return res.status(500).send(\"ERROR\");\n14. }\n15. }\n16. });\n17. \n18. module.exports = router;\nLine 7-9: Validate external inputs through a filter function.", "contexts": [{"lineNo": 96, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "req"}}, {"lineNo": 110, "eventType": "source", "messageKey": "synz.COMMON.branch.false.assumed", "params": {"arg0": "128"}}, {"lineNo": 130, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "redirect"}}]}} {"id": "83414b036c4887364a9ddcecb3acef24916bb3f7644150eef98c6486af9109d6", "license": {"spdx": ["MIT"], "repo": "mayconbeserra/TheBoard", "path": "controllers/homeController.js", "repo_head_hexsha": "929df215727c6a71c13dfee3e005073a068f2310", "stack_hexsha": "a4510abca7eb4f3c3ba1801e10613093f0b3b470", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Redirection to untrusted site", "issueDescriptionEn": "The Redirection to untrusted site checker finds instances of redirecting to a URL generated with an unvalidated external input.\nAlthough connecting to a client-provided URL is often believed to be safe, an attacker can modify the request and redirect the user to a malicious site.\nMaintain a whitelist of external site URLs and domains allowed for redirection, which needs to be checked when a user input is passed as a redirect URL.", "issueLineNumber": 36, "entireCode": "(function (homeController) {\n\n var data = require(\"../dataService\");\n var auth = require(\"../auth\");\n\n homeController.init = function (app) {\n\n app.get(\"/\", function (req, res) {\n data.getNoteCategories(function(err, results) {\n res.render(\"vash/index\", {\n title: \"Express + Vash in controller\",\n error: err,\n categories: results,\n newCatError: req.flash(\"newCatNameValidation\"),\n user: req.user\n });\n });\n });\n\n app.get(\"/notes/:categoryName\",\n auth.ensureAuthenticated,\n function (req, res) {\n var categoryName = req.params.categoryName;\n res.render('vash/notes', { title: categoryName, user: req.user });\n });\n\n app.post(\"/newCategory\", function (req, res){\n var categoryName = req.body.categoryName;\n data.createNewCategory(categoryName, function(err) {\n if (err) {\n //handle error\n console.log(err);\n req.flash(\"newCatNameValidation\", err);\n res.redirect(\"/\");\n } else {\n res.redirect(\"/notes/\" + categoryName);\n }\n });\n });\n };\n\n})(module.exports);", "dangerousExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/dan', function (req, res) {\n5. const url = req.body.profile_url;\n6. try{\n7. res.redirect(url);\n8. }catch (e) {\n9. return res.status(500).send(\"ERROR\");\n10. }\n11. });\n12. \n13. module.exports = router;\nLine 7: A string variable URL of an unvalidated external input is used to connect.", "safeExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/safe', function (req, res) {\n5. const url = req.body.profile_url;\n6. const white_list = [\"https://www.safeurl.com\", \"https://www.verified.com\"];\n7. if (white_list.indexOf(url) < 0) {\n8. return res.status(500).send(\"url not allowed\");\n9. } else {\n10. try {\n11. res.redirect(url);\n12. } catch (e) {\n13. return res.status(500).send(\"ERROR\");\n14. }\n15. }\n16. });\n17. \n18. module.exports = router;\nLine 7-9: Validate external inputs through a filter function.", "contexts": [{"lineNo": 28, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "req"}}, {"lineNo": 30, "eventType": "source", "messageKey": "synz.COMMON.branch.false.assumed", "params": {"arg0": "35"}}, {"lineNo": 36, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "redirect"}}]}} {"id": "feedb48d08de13b7146cb7a60487f5eef4c162fff25f27e69bbc91b3d1db928b", "license": {"spdx": ["MIT"], "repo": "jahammo2/veery", "path": "src/api/app/controllers/users.js", "repo_head_hexsha": "d55e790db3acadb060eaa9c34253a8f822bb942e", "stack_hexsha": "d961768616c140682d16fa6e6cc245c6b7b90711", "match": "repo_path"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Redirection to untrusted site", "issueDescriptionEn": "The Redirection to untrusted site checker finds instances of redirecting to a URL generated with an unvalidated external input.\nAlthough connecting to a client-provided URL is often believed to be safe, an attacker can modify the request and redirect the user to a malicious site.\nMaintain a whitelist of external site URLs and domains allowed for redirection, which needs to be checked when a user input is passed as a redirect URL.", "issueLineNumber": 196, "entireCode": "'use strict';\n\nconst crypto = require('crypto');\n\nconst config = require('../../config');\nconst mailgun = require('../../config/mailgun');\n\nconst Invitation = require('../models/invitation');\nconst User = require('../models/user');\n\nfunction sendEmail(email, resetToken) {\n // For local testing, you'll need to add ':8080' after {config.domain}.\n const link = `http://${config.domain}/api/reset-password/${resetToken}`;\n const body = `Please visit the following link to reset your Veery password: \\n ${link}`;\n\n return mailgun.sendEmail(\n email,\n 'Veery Account Password Reset',\n body\n );\n}\n\nfunction setupPasswordReset(user, res, next) {\n return crypto.randomBytes(48, (_, buffer) => {\n const resetToken = buffer.toString('hex');\n user.resetPasswordToken = Token;\n user.resetPasswordExpires = Date.now() + 3600000; // 1 hour\n\n return user.save()\n .then((_user) => {\n return sendEmail(_user.email, resetToken);\n })\n .then(() => {\n return res.status(202).json({ message: `Forgot password email sent to ${user.email}.` });\n })\n .catch((err) => {\n console.log('Error:', err && err.message); // eslint-disable-line no-console\n next(err);\n });\n });\n}\n\nfunction forgotPassword(req, res, next) {\n const email = req.body.email;\n\n if (!email) {\n return res.status(422).send({ error: 'No email was attached.' });\n }\n\n return User.findOne({ email })\n .then((user) => {\n if (!user) {\n return res.status(404).json({ error: `Could not find user with email ${email}.` });\n }\n\n return setupPasswordReset(user, res, next);\n })\n .catch((err) => {\n console.log('Error:', err && err.message); // eslint-disable-line no-console\n next(err);\n });\n}\n\nfunction isSignedIn(req, res) {\n return res.status(200).json({ user: req.user });\n}\n\nfunction validatePassword(password, passwordConfirmation) {\n if (!password) {\n return 'You must enter a password.';\n }\n\n if (password !== passwordConfirmation) {\n return 'The passwords must match.';\n }\n\n if (password.length < 6) {\n return 'The password must be 6 characters or more.';\n }\n}\n\nfunction registerUser(invitation, password) {\n const params = {\n email: invitation.email,\n password,\n role: 'venueAdmin',\n venues: invitation.venues\n };\n\n return new User(params).save();\n}\n\nfunction handleInvitation(req, res, { invitation, user }) {\n // Just so I can be notified if someone signs up\n mailgun.sendEmail(\n '',\n 'Someone Signed Up!',\n `${user}`\n );\n\n return req.login(user, (err) => {\n if (err) { throw new Error(err); }\n\n res.status(201).json({ user });\n return invitation.remove();\n });\n}\n\nfunction handleError(err, res) {\n console.log('Error:', err && err.message); // eslint-disable-line no-console\n let errorMessage = err.message;\n const statusCode = err.statusCode || 404;\n\n if (statusCode === 404) {\n errorMessage = 'This invitation no longer exists.';\n }\n\n return res.status(statusCode).json({ error: errorMessage });\n}\n\nfunction register(req, res) {\n let invitation;\n const password = req.body.password;\n const passwordBasedError = validatePassword(password, req.body.passwordConfirmation);\n\n if (passwordBasedError) {\n return res.status(422).send({ error: passwordBasedError });\n }\n\n return Invitation\n .findById(req.body.invitationId)\n .then((foundInvitation) => {\n invitation = foundInvitation;\n return registerUser(foundInvitation, password);\n })\n .then((user) => handleInvitation(req, res, { invitation, user }))\n .catch((err) => handleError(err, res));\n}\n\nfunction findUserForPasswordReset(token) {\n const options = {\n resetPasswordToken: ,\n resetPasswordExpires: { $gt: Date.now() }\n };\n\n return User.findOne(options);\n}\n\nfunction updateAndSignInUser(user, password, req, res) {\n user.password = password;\n user.resetPasswordExpires = ;\n user.resetPasswordToken = ;\n\n return user.save()\n .then((_user) => {\n return req.login(user, (err) => {\n if (err) { throw new Error(err); }\n return res.status(202).json({ user: _user });\n });\n });\n}\n\nfunction resetPassword(req, res, next) {\n const password = ;\n const passwordBasedError = validatePassword(password, req.body.passwordConfirmation);\n\n if (passwordBasedError) {\n return res.status(422).send({ error: passwordBasedError });\n }\n\n return findUserForPasswordReset(req.params.token)\n .then((user) => {\n if (!user) {\n return res.status(401).send({ error: 'The reset password link has expired.' });\n }\n\n return updateAndSignInUser(user, password, req, res);\n })\n .catch((err) => {\n console.log('Error:', err && err.message); // eslint-disable-line no-console\n next(err);\n });\n}\n\nfunction resetPasswordRedirect(req, res) {\n const token = req.params.token;\n const failureRedirect = `http://${config.domain}/#/admin/forgot-password?token=expired`;\n\n return findUserForPasswordReset(token)\n .then((user) => {\n if (!user) {\n return res.redirect(failureRedirect);\n }\n\n // For local testing, you'll need to add ':8080' after {config.domain}.\n return res.redirect(`http://${config.domain}/#/admin/reset-password?token=${token}`);\n })\n .catch((err) => {\n console.log('Error:', err && err.message); // eslint-disable-line no-console\n return res.redirect(failureRedirect);\n });\n}\n\nfunction showAll(req, res) {\n return User\n .find({})\n .sort('email')\n .then((users) => res.json({ users }));\n}\n\nfunction signIn(req, res) {\n const userInfo = {\n email: req.user.email\n };\n\n res.status(200).json(userInfo);\n}\n\nfunction signOut(req, res) {\n req.logout();\n res.status(200).send();\n}\n\nmodule.exports = {\n forgotPassword,\n isSignedIn,\n register,\n resetPassword,\n resetPasswordRedirect,\n showAll,\n signIn,\n signOut\n};", "dangerousExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/dan', function (req, res) {\n5. const url = req.body.profile_url;\n6. try{\n7. res.redirect(url);\n8. }catch (e) {\n9. return res.status(500).send(\"ERROR\");\n10. }\n11. });\n12. \n13. module.exports = router;\nLine 7: A string variable URL of an unvalidated external input is used to connect.", "safeExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/safe', function (req, res) {\n5. const url = req.body.profile_url;\n6. const white_list = [\"https://www.safeurl.com\", \"https://www.verified.com\"];\n7. if (white_list.indexOf(url) < 0) {\n8. return res.status(500).send(\"url not allowed\");\n9. } else {\n10. try {\n11. res.redirect(url);\n12. } catch (e) {\n13. return res.status(500).send(\"ERROR\");\n14. }\n15. }\n16. });\n17. \n18. module.exports = router;\nLine 7-9: Validate external inputs through a filter function.", "contexts": [{"lineNo": 186, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "req"}}, {"lineNo": 196, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "redirect"}}]}} {"id": "6135922aed3a4069a834fa6fbf1c2a0b166098272e919ac5f41f7ce26a38b30c", "license": {"spdx": ["MIT"], "repo": "mmesba/Markdown-Blog", "path": "controllers/articles.js", "repo_head_hexsha": "93c65029501850e321b46bbc78fee6a0ff1b31e0", "stack_hexsha": "f2a3891253a8c524b0e3842e0241e6264e096438", "match": "repo_path"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Redirection to untrusted site", "issueDescriptionEn": "The Redirection to untrusted site checker finds instances of redirecting to a URL generated with an unvalidated external input.\nAlthough connecting to a client-provided URL is often believed to be safe, an attacker can modify the request and redirect the user to a malicious site.\nMaintain a whitelist of external site URLs and domains allowed for redirection, which needs to be checked when a user input is passed as a redirect URL.", "issueLineNumber": 59, "entireCode": "/*\n * Title: articles module for app.\n * Description: articles module for app.\n * Author: (github profile: https://github.com/Mohammad-Mesbaul-Haque )\n * Date: 18/05/2021\n */\n// Dependencies.\nconst express = require('express');\nconst Article = require('../models/Article');\n\n// Module scaffolding.\nconst router = express.Router();\n\n\n// Main functions.\nrouter.get('/new', (req, res)=>{\n res.render('articles/new', {article: new Article()});\n})\n\nrouter.get('/edit/:id', async(req, res)=>{\n let article = await Article.findById(req.params.id);\n res.render('articles/edit', {article: article})\n\n})\n\nrouter.get('/:slug', async (req, res)=>{\n const article = await Article.findOne({slug: req.params.slug})\n if(article === null) res.redirect('/')\n res.render('articles/show', {article: article})\n})\n\nrouter.post('/',async (req, res, next)=>{\n req.article = new Article();\n next();\n}, saveArticleAndRedirect('new'))\n\nrouter.put('/:id',async (req, res, next)=>{\n req.article = await Article.findById(req.params.id)\n next();\n }, saveArticleAndRedirect('edit'))\n\nrouter.delete('/:id', async(req, res)=>{\n await Article.findByIdAndDelete(req.params.id);\n res.redirect('/');\n})\n\n//common function for post and put route\n// because they are almost identical\nfunction saveArticleAndRedirect(path) {\n return async(req, res)=>{\n let article = req.article\n article.title= req.body.title;\n article.description= req.body.description;\n article.markdown= req.body.markdown;\n \n try {\n article = await article.save();\n //if successfully save article , redirect\n res.redirect(`/articles/${article.slug}`)\n // it will redirect to the show page where the newly saved data will be arrived\n \n } catch (err) {\n // console.error(err.message);\n res.render(`articles/${path}`, {article: article})\n }\n }}\n\n\n// export the module.\nmodule.exports = router;", "dangerousExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/dan', function (req, res) {\n5. const url = req.body.profile_url;\n6. try{\n7. res.redirect(url);\n8. }catch (e) {\n9. return res.status(500).send(\"ERROR\");\n10. }\n11. });\n12. \n13. module.exports = router;\nLine 7: A string variable URL of an unvalidated external input is used to connect.", "safeExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/safe', function (req, res) {\n5. const url = req.body.profile_url;\n6. const white_list = [\"https://www.safeurl.com\", \"https://www.verified.com\"];\n7. if (white_list.indexOf(url) < 0) {\n8. return res.status(500).send(\"url not allowed\");\n9. } else {\n10. try {\n11. res.redirect(url);\n12. } catch (e) {\n13. return res.status(500).send(\"ERROR\");\n14. }\n15. }\n16. });\n17. \n18. module.exports = router;\nLine 7-9: Validate external inputs through a filter function.", "contexts": [{"lineNo": 59, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "article"}}, {"lineNo": 59, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "redirect"}}]}} {"id": "8b8ed0ba5a40a2339861f9cafe2fb965844f543ef0ed1a3b5d5121276ac10597", "license": {"spdx": ["MIT"], "repo": "1self/github-datasource", "path": "routes/githubOAuth.js", "repo_head_hexsha": "e30aae17bac4f90ae99d356aa3d60a34fa0f09aa", "stack_hexsha": "cd346098b1dd30d57b088e4f007d956c572c9569", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Redirection to untrusted site", "issueDescriptionEn": "The Redirection to untrusted site checker finds instances of redirecting to a URL generated with an unvalidated external input.\nAlthough connecting to a client-provided URL is often believed to be safe, an attacker can modify the request and redirect the user to a malicious site.\nMaintain a whitelist of external site URLs and domains allowed for redirection, which needs to be checked when a user input is passed as a redirect URL.", "issueLineNumber": 105, "entireCode": "var request = require(\"request\");\nvar passport = require('passport');\nvar githubStrategy = require('passport-github').Strategy;\nvar _ = require('underscore');\nvar q = require('q');\nvar logger = require('winston');\n\nvar GITHUB_DATASOURCE_CLIENT_ID = process.env.GITHUB_DATASOURCE_CLIENT_ID;\nvar GITHUB_DATASOURCE_CLIENT_SECRET = process.env.GITHUB_DATASOURCE_CLIENT_SECRET;\nvar GITHUB_INT_CONTEXT_URI = process.env.GITHUB_INT_CONTEXT_URI;\n\nvar logInfo = function(username, message, object){\n logger.info(username + ': ' + message, object);\n}\n\nvar logDebug = function(username, message, object){\n logger.debug(username + ': ' + message, object);\n}\n\nvar logError = function(username, message, object){\n logger.error(username + ': ' + message, object);\n}\n\nlogger.info('env');\nlogger.info(GITHUB_DATASOURCE_CLIENT_ID);\nlogger.info(GITHUB_DATASOURCE_CLIENT_SECRET);\nlogger.info(GITHUB_INT_CONTEXT_URI);\n\nmodule.exports = function (app, mongoRepository, oneselfService) {\n\n var handleNewAuthCallback = function(req, res){\n var githubUser = req.user.profile;\n var githubUsername = githubUser.username;\n\n req.session.accessToken = req.user.accessToken;\n req.session.githubUsername = githubUsername;\n var oneselfUsername = req.session.oneselfUsername;\n var registrationToken = req.session.registrationToken;\n logDebug('reading user and registration token out of the session');\n logDebug(githubUsername, \"github User is: \" + JSON.stringify(githubUser));\n var callbackUrl = GITHUB_INT_CONTEXT_URI + '/authSuccess?username=' + githubUsername\n + '&latestSyncField={{latestSyncField}}'\n + '&streamid={{streamid}}';\n\n // we use the display name to spot commits that weren't made by the committer. \n // this can happen when a rebase occurs.\n var userInfo = {\n githubUsername: githubUsername,\n accessToken: req.user.accessToken,\n displayName: req.user.profile.displayName,\n };\n\n var getEmailAddress = function (accessToken) {\n var deferred = q.defer();\n var options = {\n url: \"https://api.github.com/user/emails?access_token=\" + accessToken,\n headers: {\n \"User-Agent\": \"1self\"\n }\n };\n request(options, function (err, res, body) {\n if (!err) {\n userInfo.email = JSON.parse(body)[0].email; \n logDebug(userInfo.githubUsername, 'email retrieved from users github profile', userInfo.email);\n deferred.resolve();\n }\n else {\n logDebug(userInfo.githubUsername, 'error trying to get email: ', err); \n deferred.reject(err);\n }\n });\n return deferred.promise;\n };\n\n var syncGithubEvents = function (callbackUrl, writeToken) {\n\n request({\n method: 'GET',\n uri: callbackUrl,\n gzip: true,\n headers: {\n 'Authorization': writeToken\n }\n }, function (e, response, body) {\n console.log(\"Started event sync\");\n });\n };\n\n getEmailAddress(req.session.accessToken)\n .then(function(){\n return mongoRepository.findByGithubUsername(userInfo.githubUsername);\n })\n .then(function (user) {\n // we hit this if we are doing a re-auth and the user already exists\n oneselfService.registerStream(oneselfUsername, registrationToken, process.env.APIURI, callbackUrl)\n .then(function (stream) {\n mongoRepository.insert(userInfo)\n .then(function () {\n var callbackUrlForUser = callbackUrl\n .replace('{{streamid}}', stream.streamid)\n .replace('{{latestSyncField}}', new Date(1970, 1, 1).toISOString());\n syncGithubEvents(callbackUrlForUser, stream.writeToken);\n\n var redirectUri = req.session.redirectUri + '?success=true';\n res.redirect(redirectUri);\n });\n }, function (error) {\n var redirectUri = req.session.redirectUri + '?success=false&error=server_error';\n res.redirect(redirectUri); \n });\n })\n .catch(function (error) {\n logError(userInfo.githubUsername, \"Error in github callback: \", error);\n });\n };\n\n var handleReauthCallback = function(req, res){\n var githubUser = req.user.profile;\n var githubUsername = githubUser.username;\n\n logDebug(githubUsername, \"github User is: \", JSON.stringify(githubUser));\n var callbackUrl = GITHUB_INT_CONTEXT_URI + '/authSuccess?username=' + githubUsername\n + '&latestSyncField={{latestSyncField}}'\n + '&streamid={{streamid}}';\n\n var userInfo = {\n githubUsername: githubUsername,\n accessToken: req.user.accessToken,\n displayName: req.user.profile.displayName,\n };\n\n var getEmailAddress = function (accessToken) {\n var deferred = q.defer();\n var options = {\n url: \"https://api.github.com/user/emails?access_token=\" + accessToken,\n headers: {\n \"User-Agent\": \"1self\"\n }\n };\n request(options, function (err, res, body) {\n if (!err) {\n userInfo.email = JSON.parse(body)[0].email; \n logDebug(userInfo.githubUsername, 'email retrieved from users github profile', userInfo.email);\n deferred.resolve();\n }\n else {\n logDebug(userInfo.githubUsername, 'error trying to get email: ', err); \n deferred.reject(err);\n }\n });\n return deferred.promise;\n };\n\n getEmailAddress(userInfo.accessToken)\n .then(function(){\n return mongoRepository.findByGithubUsername(githubUsername);\n })\n .then(function (user) {\n var query = {\n _id: user._id\n };\n\n var operation = {\n $set: {\n accessToken: userInfo.accessToken,\n email: userInfo.email\n }\n };\n \n mongoRepository.update(query, operation)\n .then(function () {\n res.redirect(req.session.redirect);\n }); \n })\n .catch(function (error) {\n logError(userInfo.githubUsername, \"Error in github callback: \", error);\n });\n };\n var handleGithubCallback = function (req, res) {\n if(req.session.reauth){\n handleReauthCallback(req, res);\n }\n else{\n handleNewAuthCallback(req, res);\n }\n };\n\n passport.serializeUser(function (user, done) {\n done(null, user);\n });\n\n passport.deserializeUser(function (obj, done) {\n done(null, obj);\n });\n\n console.log(GITHUB_DATASOURCE_CLIENT_ID);\n console.log(GITHUB_DATASOURCE_CLIENT_SECRET);\n console.log(GITHUB_INT_CONTEXT_URI);\n passport.use(new githubStrategy({\n clientID: GITHUB_DATASOURCE_CLIENT_ID,\n clientSecret: GITHUB_DATASOURCE_CLIENT_SECRET,\n callbackURL: GITHUB_INT_CONTEXT_URI + \"/auth/github/callback\"\n },\n function (accessToken, refreshToken, profile, done) {\n var githubProfile = {\n profile: profile,\n accessToken: accessToken\n };\n return done(null, githubProfile);\n }\n ));\n app.use(passport.initialize());\n app.use(passport.session());\n\n app.get('/auth/github', passport.authenticate('github', {\n scope: 'repo,user:email'\n }));\n\n app.get('/auth/github/callback', passport.authenticate('github', {\n failureRedirect: GITHUB_INT_CONTEXT_URI,\n }), handleGithubCallback);\n}\n;", "dangerousExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/dan', function (req, res) {\n5. const url = req.body.profile_url;\n6. try{\n7. res.redirect(url);\n8. }catch (e) {\n9. return res.status(500).send(\"ERROR\");\n10. }\n11. });\n12. \n13. module.exports = router;\nLine 7: A string variable URL of an unvalidated external input is used to connect.", "safeExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/safe', function (req, res) {\n5. const url = req.body.profile_url;\n6. const white_list = [\"https://www.safeurl.com\", \"https://www.verified.com\"];\n7. if (white_list.indexOf(url) < 0) {\n8. return res.status(500).send(\"url not allowed\");\n9. } else {\n10. try {\n11. res.redirect(url);\n12. } catch (e) {\n13. return res.status(500).send(\"ERROR\");\n14. }\n15. }\n16. });\n17. \n18. module.exports = router;\nLine 7-9: Validate external inputs through a filter function.", "contexts": [{"lineNo": 104, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "req"}}, {"lineNo": 104, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 105, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "redirect"}}]}} {"id": "dc5555246baa0a31e631ef192362238ec28d0c659c7f593988ad1b9a30bff29a", "license": {"spdx": ["MIT"], "repo": "KabbalahOracle/hakhel-mvc", "path": "apps/web/modules/user/admin/routes.js", "repo_head_hexsha": "db2feebd0487dcfd29c5ebb48002b5b6ad014702", "stack_hexsha": "d121fde6fc6796ffdb356d67547690c3a9af9da5", "match": "repo_path"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Redirection to untrusted site", "issueDescriptionEn": "The Redirection to untrusted site checker finds instances of redirecting to a URL generated with an unvalidated external input.\nAlthough connecting to a client-provided URL is often believed to be safe, an attacker can modify the request and redirect the user to a malicious site.\nMaintain a whitelist of external site URLs and domains allowed for redirection, which needs to be checked when a user input is passed as a redirect URL.", "issueLineNumber": 75, "entireCode": "'use strict';\n\nconst router = require('express').Router();\nconst path = require('path');\nconst config = require('../../../../../config');\nconst isAdmin = require(path.join(config.app.path, 'shared/permissions.js')).isAdmin;\nconst models = require(path.join(config.app.path, 'models'));\nconst User = models.user;\n\nconst indexUser = function(req, res) {\n User.findAll()\n .then(function (users) {\n res.render('user/admin/view-index.hbs', {users, users});\n })\n .catch(function (error) {\n res.flash('error', error.message);\n res.redirect('/error');\n });\n}\n\nconst newUser = function(req, res) {\n res.render('user/admin/view-new.hbs');\n};\n\nconst createUser = function(req, res) {\n User.create({\n email: req.body.email,\n password: ,\n role: req.body.role\n })\n .then(function (user) {\n res.flash('success', 'User ' + user.email + ' created.');\n res.redirect('/admin/users');\n })\n .catch(function (error) {\n res.flash('error', error.message);\n res.redirect('/admin/users/new');\n });\n};\n\nconst editUser = function(req, res) {\n User.findById(req.params.id)\n .then(function (user) {\n if(user === null) {\n throw new Error('User ' + req.params.id + ' does not exist.');\n return;\n }\n res.render('user/admin/view-edit.hbs', {user: user});\n })\n .catch(function (error) {\n res.flash('error', error.message);\n res.redirect('/admin/users');\n })\n};\n\nconst updateUser = function(req, res) {\n User.findById(req.params.id)\n .then(function (user) {\n if(user === null) {\n throw new Error('User ' + req.params.id + ' does not exist.');\n return;\n }\n return user.update({\n email: req.body.email,\n password: ,\n role: req.body.role\n })\n })\n .then(function (user) {\n res.flash('success', 'User ' + user.id + ' updated.');\n res.redirect('/admin/users');\n })\n .catch(function (error) {\n res.flash('error', error.message);\n res.redirect('/admin/users/' + req.params.id + '/edit');\n });\n};\n\nconst destroyUser = function(req, res) {\n User.findById(req.params.id)\n .then(function (user) {\n if(user === null) throw new Error('Cannot delete user ' + req.params.id + '. User not found.');\n return user.destroy();\n })\n .then(function (user) {\n res.flash('success', 'User ' + req.params.id + ' deleted');\n res.redirect('/admin/users');\n })\n .catch(function (error) {\n res.flash('error', error.message);\n res.redirect('/admin/users');\n });\n};\n\nrouter.get('/admin/users', [isAdmin], indexUser);\nrouter.get('/admin/users/new', [isAdmin], newUser);\nrouter.post('/admin/users', [isAdmin], createUser);\nrouter.get('/admin/users/:id/edit', [isAdmin], editUser);\nrouter.post('/admin/users/:id', [isAdmin], updateUser);\nrouter.post('/admin/users/:id/destroy', [isAdmin], destroyUser);\n\nmodule.exports = router;", "dangerousExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/dan', function (req, res) {\n5. const url = req.body.profile_url;\n6. try{\n7. res.redirect(url);\n8. }catch (e) {\n9. return res.status(500).send(\"ERROR\");\n10. }\n11. });\n12. \n13. module.exports = router;\nLine 7: A string variable URL of an unvalidated external input is used to connect.", "safeExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/safe', function (req, res) {\n5. const url = req.body.profile_url;\n6. const white_list = [\"https://www.safeurl.com\", \"https://www.verified.com\"];\n7. if (white_list.indexOf(url) < 0) {\n8. return res.status(500).send(\"url not allowed\");\n9. } else {\n10. try {\n11. res.redirect(url);\n12. } catch (e) {\n13. return res.status(500).send(\"ERROR\");\n14. }\n15. }\n16. });\n17. \n18. module.exports = router;\nLine 7-9: Validate external inputs through a filter function.", "contexts": [{"lineNo": 75, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "req"}}, {"lineNo": 75, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "redirect"}}]}} {"id": "3883d4c83cbeb86a0943d4460055d7161e25c4211642b16b0605b9f5a664fb3b", "license": {"spdx": ["MIT"], "repo": "costagguilherme/askMe-node.js", "path": "plataforma/index.js", "repo_head_hexsha": "5ee752f51315772b2bf5a98a0d782e8be763718a", "stack_hexsha": "5b70c472b18437256317622a69145e8e9e7f1611", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Redirection to untrusted site", "issueDescriptionEn": "The Redirection to untrusted site checker finds instances of redirecting to a URL generated with an unvalidated external input.\nAlthough connecting to a client-provided URL is often believed to be safe, an attacker can modify the request and redirect the user to a malicious site.\nMaintain a whitelist of external site URLs and domains allowed for redirection, which needs to be checked when a user input is passed as a redirect URL.", "issueLineNumber": 96, "entireCode": "const express = require(\"express\");\nconst app = express();\nconst bodyParser = require(\"body-parser\")\nconst connection = require(\"./database/database\")\nconst Pergunta = require(\"./database/Pergunta\")\nconst Resposta = require(\"./database/Resposta\")\n\n//Database\n\nconnection.authenticate().then(() => {\n console.log(\"Conexão feita com sucesso\")\n}).catch((erro) => {\n console(\"Ocorreu o seguinte erro\" + erro)\n})\n\n\n// Definindo o EJS como view engine\n\napp.set('view engine', 'ejs')\napp.use(express.static('public'))\n\n//Body Parser\napp.use(bodyParser.urlencoded({extended: false}))\napp.use(bodyParser.json())\n\n\n//Rotas\n\n//PRINCIPAL\napp.get(\"/\", (req, res) => {\n\n Pergunta.findAll({raw: true, order:[\n ['id', 'DESC']\n ]}).then(perguntas => {\n res.render(\"index\", {\n perguntas: perguntas\n })\n })\n})\n\n// FAZER UMA PERGUNTA E SALVÁ-LA NO BD\napp.get(\"/perguntar\", (req, res) => {\n \n res.render(\"perguntar\")\n})\n\napp.post(\"/salvarpergunta\", (req, res) => {\n var titulo = req.body.titulo\n var descricao = req.body.descricao\n\n Pergunta.create({\n\n titulo: titulo,\n descricao: descricao\n\n }).then(() => {\n res.redirect(\"/\")\n })\n})\n\n// EXIBIR PERGUNTAS E SUAS RESPOSTAS\napp.get(\"/pergunta/:id\", (req, res) => {\n var id = req.params.id\n\n Pergunta.findOne({\n where: {id: id}\n }).then(pergunta => {\n\n if (pergunta != undefined) { //Pergunta encontrada\n\n Resposta.findAll({\n where: {pergunta_id: pergunta.id},\n order: [ ['id', 'DESC'] ]\n }).then(respostas => {\n res.render(\"pergunta\", {\n pergunta: pergunta,\n respostas: respostas\n })\n })\n\n } else {\n res.redirect(\"/\")\n\n }\n })\n})\n\n// RESPONDER UMA PERGUNTA E SALVÁ-LA NO BD\napp.post(\"/responder\", (req,res) => {\n var corpo = req.body.corpo\n var perguntaId = req.body.perguntaId\n Resposta.create({\n corpo: corpo,\n pergunta_id: perguntaId\n }).then(() => {\n res.redirect(\"/pergunta/\" + perguntaId)\n\n })\n})\n\n\napp.listen(8080, function (erro) {\n\n console.log(\"Servidor iniciado\")\n})", "dangerousExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/dan', function (req, res) {\n5. const url = req.body.profile_url;\n6. try{\n7. res.redirect(url);\n8. }catch (e) {\n9. return res.status(500).send(\"ERROR\");\n10. }\n11. });\n12. \n13. module.exports = router;\nLine 7: A string variable URL of an unvalidated external input is used to connect.", "safeExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/safe', function (req, res) {\n5. const url = req.body.profile_url;\n6. const white_list = [\"https://www.safeurl.com\", \"https://www.verified.com\"];\n7. if (white_list.indexOf(url) < 0) {\n8. return res.status(500).send(\"url not allowed\");\n9. } else {\n10. try {\n11. res.redirect(url);\n12. } catch (e) {\n13. return res.status(500).send(\"ERROR\");\n14. }\n15. }\n16. });\n17. \n18. module.exports = router;\nLine 7-9: Validate external inputs through a filter function.", "contexts": [{"lineNo": 91, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "req"}}, {"lineNo": 96, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "redirect"}}]}} {"id": "88f5e26a99cfaaf734372dddc97036c3f4f6742c5e2e409183cad04bfb8dc17d", "license": {"spdx": ["MIT"], "repo": "hussainwali74/PLANENDAR", "path": "backend/routes/auth.route.js", "repo_head_hexsha": "c86e4e4a6e3c72ad1acc1aa626072fbce28fb225", "stack_hexsha": "e559836db8ce4188638c6990762962e1a4a0589d", "match": "repo_path"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Redirection to untrusted site", "issueDescriptionEn": "The Redirection to untrusted site checker finds instances of redirecting to a URL generated with an unvalidated external input.\nAlthough connecting to a client-provided URL is often believed to be safe, an attacker can modify the request and redirect the user to a malicious site.\nMaintain a whitelist of external site URLs and domains allowed for redirection, which needs to be checked when a user input is passed as a redirect URL.", "issueLineNumber": 195, "entireCode": "const express = require(\"express\");\nconst passport = require(\"passport\");\nconst router = express.Router();\nconst jwt = require(\"jsonwebtoken\");\nconst _ = require(\"lodash\");\n\nvar expressjwt = require(\"express-jwt\");\nconst bcrypt = require(\"bcryptjs\");\n\n//MODELS\nconst User = require(\"../models/user.model\");\n\n// CONTROLLERS\nconst AuthController = require(\"../controllers/Auth.controller\");\n\nconst nodemailer = require(\"nodemailer\");\nrequire(\"dotenv\").config();\n\nconst path = require(\"path\");\n\nconst transport = nodemailer.createTransport({\n service: \"Gmail\",\n auth: {\n user: process.env.GMAIL_USER,\n pass: process.env.GMAIL_PASS,\n },\n});\n\nvar auth = expressjwt({\n secret: \"MY_SECRET\",\n userProperty: \"payload\",\n algorithms: [\"RS256\"],\n});\n\n//@desc Auth with Google\n//@route Get /auth/google\nrouter.get(\"/google\", passport.authenticate(\"google\", { scope: [\"profile\"] }));\n\n//@desc google auth callback\n// @route GET /auth/google/callback\nrouter.get(\n \"/google/callback\",\n passport.authenticate(\"google\", { failureRedirect: \"/\" }),\n (req, res) => {\n console.log(\"res got\");\n res.send(\"/dashboard\");\n }\n);\n\n// @desc Logout User\n// @route /auth/logout\nrouter.get(\"/logout\", (req, res) => {\n req.logout(); //since we are using passport it provides this logout method in request\n res.redirect(\"/\");\n});\n\n//Login Validation with Credentials and Issue token hhh\nrouter.post(\"/login\", (req, res, next) => {\n console.log(\"56: authroute login\");\n let fetchedUser;\n User.findOne({ email: req.body.email })\n .then((result) => {\n if (!result) {\n return res.status(401).json({\n msg: \"User not founds, please register !\",\n result: result,\n });\n }\n if (!result.confirmed) {\n return res.status(401).json({\n msg: \"Please confirm your email to login\",\n result: \"false\",\n });\n }\n fetchedUser = result;\n return bcrypt.compare(req.body.password, result.password);\n })\n .then((result) => {\n if (!result) {\n return res.status(401).json({\n msg: \"email, password don't match, please try again!\",\n result: \"false\",\n });\n } else {\n //Creation of Token Since Credentials are matched\n if (fetchedUser) {\n const payload = {\n email: fetchedUser.email,\n };\n //Secret key to issue JWT token\n const token = jwt.sign(payload, process.env.EMAIL_SECRET, {\n expiresIn: \"1h\",\n });\n //Sending Token\n return res.status(200).json({\n msg: \"Welcome Back..!!\",\n token: token,\n user: fetchedUser,\n result: \"true\",\n });\n }\n }\n })\n .catch((err) => {\n console.log(err);\n return res.status(401).json({\n msg: \"Authorization Failed..!!\",\n result: \"false\",\n });\n });\n});\nrouter.post(\"/signup\", AuthController.signUp);\n\n// @DESC: send forgot password link\n// ROUTE: /auth/forgot-password\n\nrouter.post(\n \"/forgot-password\",\n (req, res, next) => {\n var user;\n var tok;\n User.findOne({ email: req.body.email }).then((result) => {\n user = result;\n var emailSent = false;\n //sync email sending\n try {\n const emailToken = jwt.sign(\n { user: _.pick(user, \"id\") },\n process.env.EMAIL_SECRET,\n { expiresIn: \"1d\" }\n );\n tok = emailToken;\n const url = `${process.env.BACK_URL}:${process.env.PORT}/auth/updatepassword/${emailToken}`;\n // const url = `http://localhost:3000/auth/updatepassword/${emailToken}`;\n var nodemailer = require(\"nodemailer\");\n var transporter = nodemailer.createTransport({\n service: \"Gmail\",\n auth: {\n user: process.env.GMAIL_USER,\n pass: process.env.GMAIL_PASS,\n },\n });\n transporter.sendMail(\n {\n from: process.env.EMAIL_FROM,\n // to: ' ',\n to: req.body.email,\n subject: \"PLANENDAR | Reset Password\",\n // text: 'hello world!'\n html: `\n

    Please click the link below to reset your password

    \n
    \n ${url}\n `,\n },\n (error, info) => {\n if (error) {\n return console.log(error);\n }\n emailSent = true;\n console.log(\"Message sent: %s\", info.messageId);\n console.log(emailSent);\n res.status(201).json({\n result: true,\n details: \"email sent\",\n emailSent: emailSent,\n });\n }\n );\n } catch (error) {\n console.log(error);\n res.status(401).json({\n result: false,\n error: \"Could not send reset link please try again later\",\n emailSent: emailSent,\n });\n }\n });\n },\n (err) => {\n res.status(500).json({\n result: false,\n error: \"something went wrong\",\n });\n }\n);\n\n// @DESC: verify token for reset password\n// ROUTE: /auth/updatepassword\nrouter.get(\"/updatepassword/:token\", (req, res) => {\n try {\n const {\n user: { id },\n } = jwt.verify(req.params.token, process.env.EMAIL_SECRET);\n return res.redirect(\n process.env.HOST_URL + \"/reset-password/\" + req.params.token\n );\n // return res.redirect(\n // \"http://localhost:4200/reset-password/\" + req.params.token\n // );\n } catch (error) {\n console.log(\"udpate password error\");\n console.log(error);\n // return res.redirect(\n // \"http://ec2-18-132-13-64.eu-west-2.compute.amazonaws.com/reset-password/\" +\n // req.params.token\n // );\n return res.redirect(\n process.env.HOST_URL + \"/reset-password/\" + req.params.token\n );\n }\n});\n\n// @DESC: reset password\n// ROUTE: /auth/update-password\nrouter.post(\"/update-password/:token\", (req, res) => {\n bcrypt\n .hash(req.body.password, 10)\n .then((hash) => {\n console.log(\"updating password\");\n\n const {\n user: { id },\n } = jwt.verify(req.params.token, process.env.EMAIL_SECRET);\n User.findById(id, function (err, user) {\n if (err) return console.log(err);\n console.log(\"user\");\n console.log(user);\n user.password = ;\n user.save(function (err) {\n if (err) return console.log(err);\n //user has been updated\n return res.status(200).json({\n result: true,\n msg: \"Password updated\",\n details: \"password updated successfully\",\n });\n });\n });\n })\n .catch((err) => {\n console.log(err);\n return res.status(500).json({\n result: false,\n error: \"could not update password\",\n details: err,\n });\n });\n});\n\n//USER CLICKS ON CONFIRM EMAIL LINK email confirmed\nrouter.get(\"/confirmation/:token\", async (req, res) => {\n try {\n const {\n user: { id },\n } = jwt.verify(req.params.token, process.env.EMAIL_SECRET);\n\n User.findByIdAndUpdate({ _id: id }, { confirmed: true }, (err, docs) => {\n if (err) {\n console.log(\"33\");\n console.log(err);\n return res.send(err);\n }\n\n console.log(\"docs\");\n console.log(docs);\n\n console.log(\"updated\");\n\n // return res.redirect(\n // \"http://ec2-18-132-13-64.eu-west-2.compute.amazonaws.com/signin\"\n // );\n return res.redirect(process.env.HOST_URL + \"/signin\");\n });\n } catch (error) {\n console.log(\"/confirmation: token link expired\");\n return res.status(500).json({\n result: false,\n details: \"the link has expired\",\n });\n // res.send(error)\n }\n});\n\n//Login Validation with token for (Angular Route Guard) Note: Input Token as header\nrouter.get(\n \"/auth/validation\",\n (req, res, next) => {\n console.log(req.body);\n token = req.headers.authorization;\n const secret = \"kadndak#$%^&*dfreqofn2oa2141341\";\n try {\n let payload = jwt.verify(token, secret);\n return res.status(200).json({\n result: true,\n payload: jwt.verify(token, secret),\n });\n } catch {\n return res.status(401).json({\n result: false,\n });\n }\n },\n (err) => {\n console.log(err);\n return res.status(500).json({\n result: false,\n });\n }\n);\n\nrouter.post(\"/save-social-login\", AuthController.saveSocialLogin);\nrouter.put(\"/save-profile-pic\", AuthController.saveProfilePic);\n\nmodule.exports = router;", "dangerousExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/dan', function (req, res) {\n5. const url = req.body.profile_url;\n6. try{\n7. res.redirect(url);\n8. }catch (e) {\n9. return res.status(500).send(\"ERROR\");\n10. }\n11. });\n12. \n13. module.exports = router;\nLine 7: A string variable URL of an unvalidated external input is used to connect.", "safeExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/safe', function (req, res) {\n5. const url = req.body.profile_url;\n6. const white_list = [\"https://www.safeurl.com\", \"https://www.verified.com\"];\n7. if (white_list.indexOf(url) < 0) {\n8. return res.status(500).send(\"url not allowed\");\n9. } else {\n10. try {\n11. res.redirect(url);\n12. } catch (e) {\n13. return res.status(500).send(\"ERROR\");\n14. }\n15. }\n16. });\n17. \n18. module.exports = router;\nLine 7-9: Validate external inputs through a filter function.", "contexts": [{"lineNo": 195, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "redirect"}}, {"lineNo": 196, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "req"}}]}} {"id": "c9c67eda718377aafccbab4846846a0af8bc7e8122b2edba5d49b4d279f0b89e", "license": {"spdx": ["MIT"], "repo": "Chandra-Panta-Chhetri/technically-a-review", "path": "routes/users.js", "repo_head_hexsha": "493f452552544b7055bded294452cc53ccd21eb1", "stack_hexsha": "1c67bed126599330c8461267722cb2f55f1f496b", "match": "repo_path"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Redirection to untrusted site", "issueDescriptionEn": "The Redirection to untrusted site checker finds instances of redirecting to a URL generated with an unvalidated external input.\nAlthough connecting to a client-provided URL is often believed to be safe, an attacker can modify the request and redirect the user to a malicious site.\nMaintain a whitelist of external site URLs and domains allowed for redirection, which needs to be checked when a user input is passed as a redirect URL.", "issueLineNumber": 95, "entireCode": "const TechProduct = require(\"../models/techProduct\");\nconst User = require(\"../models/user\");\nconst Review = require(\"../models/review\");\nconst router = require(\"express\").Router();\nconst middleware = require(\"../middleware\");\nconst cloudinary = require(\"./configs/cloudinaryConfig\");\nconst upload = require(\"./configs/multerConfig\");\nconst mongoose = require(\"mongoose\");\n\nrouter.post(\n \"/\",\n middleware.isLoggedOut,\n upload.single(\"avatar\"),\n async (req, res) => {\n try {\n const password = ;\n req.body.newUser.isAdmin =\n req.body.newUser.code === process.env.ADMINCODE;\n delete req.body.newUser.code;\n delete req.body.newUser.password;\n const user = await User.register(req.body.newUser, password);\n const result = await cloudinary.uploader.upload(req.file.path, {\n public_id: user._id,\n eager: [{ width: 350, height: 250, crop: \"scale\", quality: \"100\" }]\n });\n user.avatarUrl = result.eager[0].secure_url;\n await user.save();\n req.login(user, () => {\n req.flash(\"success\", `Welcome ${user.name}!`);\n return res.redirect(\"/techProducts\");\n });\n } catch (e) {\n req.flash(\"error\", e.message);\n return res.redirect(\"/signup\");\n }\n },\n (err, req, res, next) => {\n req.flash(\"error\", err);\n res.redirect(\"/signup\");\n }\n);\n\nrouter.get(\"/:userId\", async (req, res) => {\n try {\n const user = await User.findById(req.params.userId);\n if (!user) {\n throw new Error();\n }\n const usersTechProducts = await TechProduct.find({ \"author.id\": user._id });\n const numReviews = await Review.find({\n \"author.id\": user._id\n }).countDocuments();\n return res.render(\"user/show\", { user, usersTechProducts, numReviews });\n } catch (e) {\n req.flash(\"error\", \"User does not exist.\");\n return res.redirect(\"/techProducts\");\n }\n});\n\nrouter.get(\n \"/:userId/edit\",\n middleware.isLoggedIn,\n middleware.canModifyProfile,\n async (req, res) => {\n const user = await User.findById(req.params.userId);\n return res.render(\"user/edit\", { user });\n }\n);\n\nrouter.put(\n \"/:userId\",\n middleware.isLoggedIn,\n middleware.canModifyProfile,\n upload.single(\"avatar\"),\n async (req, res) => {\n try {\n const user = await User.findById(req.params.userId);\n req.body.user.email = req.body.user.email.toLowerCase();\n if (req.file) {\n cloudinary.uploader.destroy(user._id);\n const result = await cloudinary.uploader.upload(req.file.path, {\n public_id: user._id,\n eager: [{ width: 350, height: 250, crop: \"scale\", quality: \"100\" }]\n });\n req.body.user.avatarUrl = result.eager[0].secure_url;\n }\n await user.updateOne({ $set: req.body.user });\n req.flash(\"success\", \"Profile successfully updated!\");\n } catch (e) {\n req.flash(\n \"error\",\n \"Profile update unsuccessful. Please try again later.\"\n );\n }\n return res.redirect(`/users/${req.params.userId}`);\n },\n (err, req, res, next) => {\n req.flash(\"error\", err);\n res.redirect(`/users/${req.params.userId}/edit`);\n }\n);\n\nrouter.delete(\n \"/:userId\",\n middleware.isLoggedIn,\n middleware.canModifyProfile,\n async (req, res) => {\n try {\n const user = await User.findById(req.params.userId);\n cloudinary.uploader.destroy(user._id);\n await user.remove();\n req.flash(\"success\", \"Account has been closed successfully!\");\n return res.redirect(\"/techProducts\");\n } catch (e) {\n req.flash(\n \"error\",\n \"Account deletion unsuccessful. Please try again later.\"\n );\n return res.redirect(`/users/${req.params.userId}`);\n }\n }\n);\n\nrouter.get(\n \"/:userId/changePassword\",\n middleware.isLoggedIn,\n middleware.hasGoogleAccount,\n middleware.canModifyProfile,\n (req, res) => res.render(\"user/changePassword\", { userId: req.params.userId })\n);\n\nrouter.post(\n \"/:userId/changePassword\",\n middleware.isLoggedIn,\n middleware.hasGoogleAccount,\n middleware.canModifyProfile,\n async (req, res) => {\n try {\n const user = await User.findById(req.params.userId);\n if (req.body.newPass === req.body.confirmNewPass) {\n return user.changePassword(\n req.body.currentPass,\n req.body.newPass,\n (err) => {\n if (err) {\n req.flash(\"error\", \"Current password is wrong.\");\n return res.redirect(`/users/${req.params.userId}/changePassword`);\n }\n req.flash(\"success\", \"Password has been successfully changed!\");\n return res.redirect(`/users/${req.params.userId}`);\n }\n );\n }\n req.flash(\"error\", \"Please make sure passwords match.\");\n return res.redirect(`/users/${req.params.userId}/changePassword`);\n } catch (e) {\n req.flash(\n \"error\",\n \"Password change unsuccessful. Please try again later.\"\n );\n return res.redirect(\"/techProducts\");\n }\n }\n);\n\nmodule.exports = router;", "dangerousExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/dan', function (req, res) {\n5. const url = req.body.profile_url;\n6. try{\n7. res.redirect(url);\n8. }catch (e) {\n9. return res.status(500).send(\"ERROR\");\n10. }\n11. });\n12. \n13. module.exports = router;\nLine 7: A string variable URL of an unvalidated external input is used to connect.", "safeExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/safe', function (req, res) {\n5. const url = req.body.profile_url;\n6. const white_list = [\"https://www.safeurl.com\", \"https://www.verified.com\"];\n7. if (white_list.indexOf(url) < 0) {\n8. return res.status(500).send(\"url not allowed\");\n9. } else {\n10. try {\n11. res.redirect(url);\n12. } catch (e) {\n13. return res.status(500).send(\"ERROR\");\n14. }\n15. }\n16. });\n17. \n18. module.exports = router;\nLine 7-9: Validate external inputs through a filter function.", "contexts": [{"lineNo": 95, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "req"}}, {"lineNo": 95, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "redirect"}}]}} {"id": "8086206a30b31f119d72e3622239b61bdc79c221ab833d6d737ccc682e2ca7b8", "license": {"spdx": ["MIT"], "repo": "katsuraku/polyfill-service", "path": "server/routes/home.js", "repo_head_hexsha": "494b9e87b9e2af4583e7f58445f5e2f73a52a159", "stack_hexsha": "110ac9a567bd7fe35af7a45532c1e1062fd8b909", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Redirection to untrusted site", "issueDescriptionEn": "The Redirection to untrusted site checker finds instances of redirecting to a URL generated with an unvalidated external input.\nAlthough connecting to a client-provided URL is often believed to be safe, an attacker can modify the request and redirect the user to a malicious site.\nMaintain a whitelist of external site URLs and domains allowed for redirection, which needs to be checked when a user input is passed as a redirect URL.", "issueLineNumber": 17, "entireCode": "\"use strict\";\n\nconst cacheControl = require(\"@financial-times/origami-service\").middleware.cacheControl;\n\nmodule.exports = app => {\n\tconst cacheForOneDay = cacheControl({\n\t\tmaxAge: \"1 day\",\n\t\tstaleWhileRevalidate: \"7 days\",\n\t\tstaleIfError: \"7 days\"\n\t});\n\n\t// Redirect to the docs page\n\tapp.get(\"/\", cacheForOneDay, (request, response) => {\n\t\tresponse.set({\n\t\t\t\"cache-control\": \"public, s-maxage=31536000, max-age=604800, stale-while-revalidate=604800, stale-if-error=604800\"\n\t\t});\n\t\tresponse.redirect(301, `${request.basePath}v3/`);\n\t});\n};", "dangerousExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/dan', function (req, res) {\n5. const url = req.body.profile_url;\n6. try{\n7. res.redirect(url);\n8. }catch (e) {\n9. return res.status(500).send(\"ERROR\");\n10. }\n11. });\n12. \n13. module.exports = router;\nLine 7: A string variable URL of an unvalidated external input is used to connect.", "safeExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/safe', function (req, res) {\n5. const url = req.body.profile_url;\n6. const white_list = [\"https://www.safeurl.com\", \"https://www.verified.com\"];\n7. if (white_list.indexOf(url) < 0) {\n8. return res.status(500).send(\"url not allowed\");\n9. } else {\n10. try {\n11. res.redirect(url);\n12. } catch (e) {\n13. return res.status(500).send(\"ERROR\");\n14. }\n15. }\n16. });\n17. \n18. module.exports = router;\nLine 7-9: Validate external inputs through a filter function.", "contexts": [{"lineNo": 17, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "request"}}, {"lineNo": 17, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "redirect"}}]}} {"id": "257e9e027bb7d53b69ef7afcf107d3fc56a4cd2a5388822fe166cde9c819df17", "license": {"spdx": ["MIT"], "repo": "galdiatorocks/marketool", "path": "routes/api.js", "repo_head_hexsha": "d143033d6372ecacb9920d6da9464a2d8fd0d7e1", "stack_hexsha": "d9b547ef5702d25d11a5e990df2d80666221f4c4", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Redirection to untrusted site", "issueDescriptionEn": "The Redirection to untrusted site checker finds instances of redirecting to a URL generated with an unvalidated external input.\nAlthough connecting to a client-provided URL is often believed to be safe, an attacker can modify the request and redirect the user to a malicious site.\nMaintain a whitelist of external site URLs and domains allowed for redirection, which needs to be checked when a user input is passed as a redirect URL.", "issueLineNumber": 24, "entireCode": "const UserDisplay = require(\"../controllers/userDisplay\");\n\nconst passport = require('passport');\n\nfunction router(app) {\n \n const userDisplay = new UserDisplay;\n\n app.route(\"/\").get((req, res) => res.sendFile(process.cwd() + \"/main.html\"));\n\n app.route(\"/:twitter_handle\").get(ensureAuthenticated, userDisplay.displayProfile);\n\n app.route(\"/:twitter_handle/searchresults\").post(ensureAuthenticated, userDisplay.newSearch);\n\n app\n .route(\"/login/twitter\")\n .get(passport.authenticate('twitter'), (req) => {\n console.log(\"Req here:\", req);\n });\n\n app\n .route(\"/login/twitter/callback\")\n .get(passport.authenticate('twitter', {failureRedirect : \"/\"}), (req,res) => {\n res.redirect(`/${req.user.twitterHandle}`);\n })\n\n app\n .route(\"/:user/logout\")\n .get((req,res) => {\n req.logout();\n res.redirect('/');\n })\n\n}\n\nmodule.exports = router;\n\nfunction ensureAuthenticated(req,res,next){\n if (req.isAuthenticated()){\n return next();\n }\n res.redirect(\"/\");\n}", "dangerousExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/dan', function (req, res) {\n5. const url = req.body.profile_url;\n6. try{\n7. res.redirect(url);\n8. }catch (e) {\n9. return res.status(500).send(\"ERROR\");\n10. }\n11. });\n12. \n13. module.exports = router;\nLine 7: A string variable URL of an unvalidated external input is used to connect.", "safeExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/safe', function (req, res) {\n5. const url = req.body.profile_url;\n6. const white_list = [\"https://www.safeurl.com\", \"https://www.verified.com\"];\n7. if (white_list.indexOf(url) < 0) {\n8. return res.status(500).send(\"url not allowed\");\n9. } else {\n10. try {\n11. res.redirect(url);\n12. } catch (e) {\n13. return res.status(500).send(\"ERROR\");\n14. }\n15. }\n16. });\n17. \n18. module.exports = router;\nLine 7-9: Validate external inputs through a filter function.", "contexts": [{"lineNo": 24, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "req"}}, {"lineNo": 24, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "redirect"}}]}} {"id": "211b9da0ec85b71c633d77ac34d4209950051d6798ffd29dc483f9443aa95602", "license": {"spdx": ["MIT"], "repo": "NaskoVasilev/ChsrityShop", "path": "CharityShop/controllers/eventController.js", "repo_head_hexsha": "60165a63b1c95cf7eead2178bbaf7d84164c156b", "stack_hexsha": "136c30de87e3ef38e1da2c9607e382143bb1560c", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Redirection to untrusted site", "issueDescriptionEn": "The Redirection to untrusted site checker finds instances of redirecting to a URL generated with an unvalidated external input.\nAlthough connecting to a client-provided URL is often believed to be safe, an attacker can modify the request and redirect the user to a malicious site.\nMaintain a whitelist of external site URLs and domains allowed for redirection, which needs to be checked when a user input is passed as a redirect URL.", "issueLineNumber": 58, "entireCode": "const Event = require('../models/Event')\nconst entityHelper = require('../utilities/entityHelper')\nlet noChosenFileError = 'Please choose a photo!';\nlet errorMessage = 'Error occurred! Please try again!';\n\nmodule.exports.addGet = (req, res) => {\n res.render('event/add')\n}\n\nmodule.exports.addPost = (req, res) => {\n let event = req.body;\n\n if (!req.file || !req.file.path) {\n event.error = noChosenFileError;\n res.render('event/add', event);\n return;\n }\n\n entityHelper.addBinaryFileToEntity(req, event);\n\n if (new Date(event.date) < Date.now()) {\n\n event.error = \"The event's date cannot be in the past!\";\n res.render('event/add', event)\n return;\n }\n\n Event.create(event).then(() => {\n req.flash('info', 'New event was created successfully!')\n res.redirect('/event/all');\n }).catch(err => {\n event.error = errorMessage;\n res.render('event/add', event);\n })\n}\n\nmodule.exports.deleteGet = (req, res) => {\n let id = req.params.id\n\n Event.findById(id).then(event => {\n let date = event.date.toDateString();\n event.formatedDate = date;\n res.render('event/delete', event)\n }).catch(err => {\n req.flash('error', errorMessage)\n res.redirect('/');\n })\n}\n\nmodule.exports.deletePost = (req, res) => {\n let id = req.params.id\n\n Event.findByIdAndDelete(id).then(() => {\n req.flash('info', 'The event was deleted successfully!!')\n res.redirect('/event/all')\n }).catch(err => {\n req.flash('error', errorMessage);\n res.redirect('/event/delete/' + id);\n })\n}\n\nmodule.exports.editGet = (req, res) => {\n let id = req.params.id\n\n Event.findById(id).then(event => {\n res.render('event/edit', event)\n }).catch(err => {\n req.flash('error', errorMessage);\n res.redirect('/');\n })\n}\n\nmodule.exports.editPost = (req, res) => {\n let id = req.params.id;\n let event = req.body;\n\n let message = null;\n if (!event.name) {\n message = \"The event's name is required!\"\n }\n else if (event.placesCount <= 0) {\n message = \"The event's places should be positive number!\"\n }\n else if (!event.address) {\n message = \"The event's address is required!\"\n }\n else if (!event.town) {\n message = \"The event's town is required!\"\n }\n\n if (message) {\n event.error = message;\n res.render('event/edit', event);\n return;\n }\n\n if (new Date(event.date) < Date.now()) {\n event.error = \"The event's date cannot be in the past!\";\n res.render('event/edit', event);\n return;\n }\n\n if (req.file && req.file.path) {\n entityHelper.addBinaryFileToEntity(req, event);\n }\n\n Event.findByIdAndUpdate(id, event).then(() => {\n req.flash('info', 'The event was edited successfully!');\n res.redirect('/event/details/' + id);\n }).catch((err) => {\n event.error = errorMessage\n res.render('event/edit', event);\n })\n}\n\nmodule.exports.getDetails = (req, res) => {\n let id = req.params.id;\n\n Event.findById(id)\n .then(event => {\n event.occupiedPlaces = event.users.length\n event.time = event.date.toDateString()\n entityHelper.addImageToEntity(event);\n if (req.user) {\n for (const userId of event.users) {\n if (userId.toString() === req.user.id.toString()) {\n event.currentUserIsRegistered = true\n }\n }\n } else {\n event.currentUserIsRegistered = false\n }\n res.render('event/details', event)\n }).catch(err => {\n req.flash('error', errorMessage);\n res.redirect('/')\n })\n}\n\nmodule.exports.getAllEvents = (req, res) => {\n let startDate = Date.now();\n Event.find({\"date\": {\"$gte\": startDate}}).then(events => {\n entityHelper.addImagesToEntities(events);\n res.render('event/all', {events: events})\n }).catch((err) => {\n req.flash('error', errorMessage);\n res.redirect('/')\n })\n}\n\nmodule.exports.registerForEvent = (req, res) => {\n let userId = req.user.id;\n let eventId = req.params.id;\n\n Event.findById(eventId).then(event => {\n if (event.placesCount <= event.users.length ||\n event.users.includes(userId.toString())) {\n req.flash('error', 'No more free places for this event!');\n res.redirect('/event/details/' + eventId)\n return\n }\n\n event.users.push(userId)\n event.save().then(() => {\n req.flash('info', 'Successfully registered for the event!');\n res.redirect('/event/details/' + eventId)\n }).catch(err => {\n req.flash('error', errorMessage);\n res.redirect('/event/details/' + eventId)\n })\n })\n}\n\nmodule.exports.unregisterFromEvent = (req, res) => {\n let eventId = req.params.id;\n let userId = req.user.id;\n\n Event.findById(eventId).then(event => {\n let index = event.users.indexOf(userId)\n\n if (index === -1) {\n req.flash('error', 'You are not registered for this event!');\n res.redirect('event/details/' + eventId)\n return\n }\n\n event.users.splice(index, 1)\n event.save().then(() => {\n req.flash('info', 'Successfully unregistered from this event!');\n res.redirect('/event/details/' + eventId)\n }).catch(err => {\n req.flash('error', errorMessage);\n res.redirect('/event/details/' + eventId)\n })\n })\n}\n\nmodule.exports.getRegisteredUsers = async (req, res) => {\n let id = req.params.id;\n\n try {\n let event = await Event.findById(id)\n .populate('users');\n res.render('event/registeredUsers', {users: event.users});\n } catch (e) {\n req.flash('error', errorMessage);\n res.redirect('/event/details/' + id);\n }\n}\n\nmodule.exports.renderEmailForm = (req, res) => {\n res.render('event/emailForm');\n}\n\nmodule.exports.sendEmails = async (req, res) => {\n let id = req.params.id;\n let event;\n try {\n event = await Event.findById(id)\n .populate('users', 'email');\n }catch(err){\n req.flash('error', errorMessage);\n res.redirect('/event/details/' + id);\n return;\n }\n\n const environment = require('../config/config.js').environment;\n let url = require('../config/config.js')[environment].url;\n const eventDetailsUrl = url + '/event/details/' + id;\n let body = req.body;\n\n if(!body.title || !body.content){\n body.error = 'All fields are required!';\n res.render(`event/emailForm`, body);\n return;\n }\n\n body.address = event.address;\n body.town = event.town;\n body.description = event.description;\n body.date = event.date;\n body.eventDetailsUrl = eventDetailsUrl;\n\n let html = require('../utilities/emailTemplates.js').getEventEmail(body);\n let userEmails = event.users.map(u => u.email).join(', ');\n let emailSender = require('../utilities/emailSender.js');\n let smtpTrans = emailSender.setEmailSender();\n let mailOptions = {\n to: userEmails,\n subject: 'Information about the upcoming event ' + event.name,\n html: html\n };\n\n let successfullySent = true;\n smtpTrans.sendMail(mailOptions, function (error) {\n if (error) {\n successfullySent = false;\n }\n });\n\n if(!successfullySent){\n req.flash('error', 'Error occurred. Please try again!');\n res.redirect('/event/details/' + id);\n return;\n }\n\n req.flash('info', 'Emails were successfully sent to all registered users for this event!')\n res.redirect('/event/details/' + id)\n}", "dangerousExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/dan', function (req, res) {\n5. const url = req.body.profile_url;\n6. try{\n7. res.redirect(url);\n8. }catch (e) {\n9. return res.status(500).send(\"ERROR\");\n10. }\n11. });\n12. \n13. module.exports = router;\nLine 7: A string variable URL of an unvalidated external input is used to connect.", "safeExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/safe', function (req, res) {\n5. const url = req.body.profile_url;\n6. const white_list = [\"https://www.safeurl.com\", \"https://www.verified.com\"];\n7. if (white_list.indexOf(url) < 0) {\n8. return res.status(500).send(\"url not allowed\");\n9. } else {\n10. try {\n11. res.redirect(url);\n12. } catch (e) {\n13. return res.status(500).send(\"ERROR\");\n14. }\n15. }\n16. });\n17. \n18. module.exports = router;\nLine 7-9: Validate external inputs through a filter function.", "contexts": [{"lineNo": 51, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "req"}}, {"lineNo": 58, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "redirect"}}]}} {"id": "801e9a1c3b92b955f30d74029dcf76784ca5be27b56189918ec199d63547a477", "license": {"spdx": ["Apache-2.0"], "repo": "martinjoha/generator-veracity", "path": "generators/node-spa/templates/server/src/dataFabric/setupUserAuthentication.js", "repo_head_hexsha": "4ee05dd766e09167f0f87386a056fe4bfb96709e", "stack_hexsha": "d856949e4c62e51a0f94164969c7bb42bfe3813f", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Redirection to untrusted site", "issueDescriptionEn": "The Redirection to untrusted site checker finds instances of redirecting to a URL generated with an unvalidated external input.\nAlthough connecting to a client-provided URL is often believed to be safe, an attacker can modify the request and redirect the user to a malicious site.\nMaintain a whitelist of external site URLs and domains allowed for redirection, which needs to be checked when a user input is passed as a redirect URL.", "issueLineNumber": 76, "entireCode": "// BodyParser is specifically used to parse the POST response from Azure B2C/ADFS.\nconst bodyParser = require(\"body-parser\")\n// Get the strategy we use to authenticate with Azure B2C and ADFS (it handles both for us)\nconst OIDCStrategy = require(\"passport-azure-ad\").OIDCStrategy\n// Helper for creating the strategy and enrire\nconst mergeConfig = require(\"../utils/mergeConfig\")\nconst passport = require(\"passport\")\n\n\nconst verifier = (iss, sub, profile, jwtClaims, access_token, refresh_token, params, done) => {\n\tconst\tuser = { // Extract information from the data returned from B2C/ADFS\n\t\tname: jwtClaims.name,\n\t\tid: jwtClaims.oid,\n\t\tdisplayName: profile.displayName,\n\t\ttokens: {\n\t\t\tservices: {\n\t\t\t\taccess_token,\n\t\t\t\trefresh_token\n\t\t\t},\n\t\t\t\t\n\t\t}\n\t}\n\n\tdone(null, user) // Tell passport that no error occured (null) and which user object to store with the session.\n}\n\n// Small helper that ensures the policy query parameter is set.\n// If you have links on the client that specify the p=[policy] query paramter this is not needed.\n// We do this since we know which policy to use in all cases and wish to avoid hard coding this into links for the client.\nconst ensureSignInPolicyQueryParameter = (policyName) => (req, res, next) => {\n\treq.query.p = req.query.p || policyName\n\n\tnext()\n}\n\n\n// Helper that will perform the authentication against B2C/ADFS.\nconst authenticatorGet = (req, res, next) => {\n\t// Construct middleware that can perform authentication\n\treturn passport.authenticate(\"veracity-oidc\", { \n\t\tresponse: res,\n\t\tfailureRedirect: \"/error\", // Where to route the user if the authentication fails\n\t\tcustomState: \"/\" + (req.query.redirectTo || \"\")\n\t})(req, res, next)\n}\n\nconst authenticatorPost = (req, res, next) => {\n\t// Construct middleware that can perform authentication\n\treturn passport.authenticate(\"veracity-oidc\", { \n\t\tresponse: res,\n\t\tfailureRedirect: \"/error\", // Where to route the user if the authentication fails\n\t})(req, res, next)\n}\n\nmodule.exports = {\n\tsetupStrategy: (config, passport) => {\n\t\tconst authConfig = mergeConfig(config)\n\t\t\n\t\t// Create and configure the strategy instance that will perform authentication\n\t\tconst strategy = new OIDCStrategy(authConfig.oidcConfig, verifier)\n\t\t\n\t\tpassport.use(\"veracity-oidc\", strategy)\n\t},\n\n\tsetupEndpoints: (app, config) => {\n\t\t// Our login route. This is where the authentication magic happens.\n\t\t// We must ensure that the policy query parameter is set and we therefore include our small middleware before the actual login process.\n\t\tapp.get(\"/login\", ensureSignInPolicyQueryParameter(config.policyName), authenticatorGet, (req, res) => {\n\t\t\tres.redirect(\"/error\") // This redirect will never be used unless something failed. The return-url when login is complete is configured as part of the application registration.\n\t\t})\n\t\t\n\t\t// This route is where we retrieve the authentication information posted back from Azure B2C/ADFS.\n\t\t// To perform the necessary steps it needs to parse post data as well as sign in correctly. This is done using the body-parser middleware.\n\t\t// Make sure the url is one of the urls from your developer.veracity.com links\n\t\tapp.post(\"/signin-oidc\", bodyParser.urlencoded({ extended: true }), authenticatorPost, (req, res) => {\n\t\t\tres.redirect(\"/login-data?redirectTo=\" + req.body.state)\n\t\t})\n\t},\n}", "dangerousExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/dan', function (req, res) {\n5. const url = req.body.profile_url;\n6. try{\n7. res.redirect(url);\n8. }catch (e) {\n9. return res.status(500).send(\"ERROR\");\n10. }\n11. });\n12. \n13. module.exports = router;\nLine 7: A string variable URL of an unvalidated external input is used to connect.", "safeExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/safe', function (req, res) {\n5. const url = req.body.profile_url;\n6. const white_list = [\"https://www.safeurl.com\", \"https://www.verified.com\"];\n7. if (white_list.indexOf(url) < 0) {\n8. return res.status(500).send(\"url not allowed\");\n9. } else {\n10. try {\n11. res.redirect(url);\n12. } catch (e) {\n13. return res.status(500).send(\"ERROR\");\n14. }\n15. }\n16. });\n17. \n18. module.exports = router;\nLine 7-9: Validate external inputs through a filter function.", "contexts": [{"lineNo": 76, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "req"}}, {"lineNo": 76, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "redirect"}}]}} {"id": "d5942af52a709a069e62ee6c1d513834e39a79661b34aba7aa226493102cd5ea", "license": {"spdx": ["MIT"], "repo": "mannyvergel/oils-plugin-forums", "path": "controllers/forums-post.js", "repo_head_hexsha": "8286287fb562b5346382d0a434ab5bb04444ffdd", "stack_hexsha": "d2d1f39a1914bb2a8f4e3eaaa147c4f1268c4dc0", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Redirection to untrusted site", "issueDescriptionEn": "The Redirection to untrusted site checker finds instances of redirecting to a URL generated with an unvalidated external input.\nAlthough connecting to a client-provided URL is often believed to be safe, an attacker can modify the request and redirect the user to a malicious site.\nMaintain a whitelist of external site URLs and domains allowed for redirection, which needs to be checked when a user input is passed as a redirect URL.", "issueLineNumber": 153, "entireCode": "'use strict';\n\nconst pluginConf = web.plugins['oils-plugin-forums'].conf;\nconst Post = web.models('ForumsPost');\n\nconst path = require('path');\nconst Topic = web.models('ForumsTopic');\nconst Category = web.models('ForumsCategory');\nconst forumsStringUtils = require('../lib/stringUtils.js');\n\nmodule.exports = {\n get: [web.auth.loginUtils.handleLogin, async function(req, res) {\n\n \tlet queryPostId = req.query._id;\n\n // await validatePostAuth(req, queryPostId);\n\n let post = await Post.findOne({_id: queryPostId}).populate('topic').lean().exec();\n\n if (queryPostId && !post) {\n throw new Error(\"Invalid request [p8]\")\n }\n\n let topic = null;\n if (post) {\n if (!req.user._id.equals(post.user)) {\n console.error(\"Someone attempted to edit a post that's not them\", req.user, post)\n throw new Error(\"Invalid request [5]\");\n }\n\n topic = post.topic;\n }\n\n let categoryId = (topic ? topic.category : null) || req.query.category;\n\n renderForumsPost(req, res, post, topic, categoryId)\n \t\n }],\n\n post: [web.auth.loginUtils.handleLogin, async function(req, res) {\n\n const params = req.body;\n const queryPostId = req.query._id;\n const isCreateMode = !queryPostId;\n let post, topic;\n\n if (queryPostId) {\n post = await Post.findOne({_id: queryPostId}).populate('topic').exec();\n if (!req.user._id.equals(post.user)) {\n console.error(\"Someone attempted to edit a post that's not them\", req.user, post)\n throw new Error(\"Invalid request [5]\");\n }\n post.isEdited = 'Y';\n\n topic = post.topic;\n } else {\n post = new Post();\n topic = new Topic();\n topic.user = req.user._id;\n topic.createBy = req.user._id;\n post.createBy = req.user._id;\n }\n \n\n topic.title = req.body.title || \"\";\n topic.title = topic.title.trim();\n\n post.isFirst = 'Y';\n\n post.topic = topic._id;\n post.msg = req.body.msg || \"\";\n post.msg = post.msg.trim();\n\n let category = req.body.category;\n\n try {\n\n if (web.stringUtils.isEmpty(topic.title)) {\n throw new Error(\"Title is required.\");\n }\n\n if (topic.title.length > 80) {\n throw new Error(\"Title is too long. Please limit to 80 characters.\")\n }\n\n if (web.stringUtils.isEmpty(post.msg)) {\n throw new Error(\"Message is required.\");\n }\n\n topic.category = category;\n\n let tags = [];\n let tagStr = req.body.tags;\n let arrUncleanTags;\n \n if (tagStr.indexOf(\"#\") != -1) {\n arrUncleanTags = tagStr.split('#');\n } else {\n arrUncleanTags = tagStr.split(',');\n }\n\n for (let i in arrUncleanTags) {\n let cleanTag = arrUncleanTags[i].trim().toLowerCase();\n if (!web.stringUtils.isEmpty(cleanTag) && tags.indexOf(cleanTag) == -1) {\n tags.push(cleanTag);\n }\n \n }\n\n topic.tags = tags;\n\n topic.updateBy = req.user._id;\n topic.updateDt = new Date();\n\n let hasUrl = false;\n if (forumsStringUtils.hasUrl(post.msg)) {\n topic.status = 'P';\n post.status = 'P';\n hasUrl = true;\n }\n\n await topic.save();\n\n\n post.user = req.user._id;\n post.updateBy = req.user._id;\n post.updateDt = new Date();\n\n await post.save();\n\n Topic.addActiveUser(topic._id, req.user);\n\n // web.subs.subscribe('topic_' + post.topic, req.user._id);\n\n try {\n const listId = pluginConf.defaultForumsId + '_topic_' + post.topic;\n await web.huhumails.ensureMailingList({\n listId,\n listDesc: pluginConf.defaultForumsName + ' Topic ' + topic.title\n });\n\n await web.huhumails.subscribe({\n listIds: [listId],\n emails: [req.user.email],\n })\n } catch (ex) {\n console.error(\"Error in mailing list\", ex);\n }\n\n if (hasUrl) {\n req.flash('error', 'Your topic may contain links and has been submitted for review.');\n if (category) {\n res.redirect('/forums/category/' + category);\n } else {\n res.redirect('/forums');\n }\n \n } else {\n req.flash('info', 'Topic posted');\n res.redirect('/forums/topic/' + topic._id + '/' + topic.titleSlug);\n }\n \n\n\n } catch (ex) {\n console.error(ex);\n req.flash('error', ex.message);\n\n if (isCreateMode) {\n topic._id = null;\n post._id = null;\n }\n \n renderForumsPost(req, res, post, topic, category);\n }\n\n }]\n}\n\n\nasync function renderForumsPost(req, res, post, topic, categoryId) {\n\n let category = await Category.findOne({_id: categoryId}).lean().exec();\n if (!category) {\n category = await Category.findOne({name:'Uncategorized'}).lean().exec();\n }\n let categories = await Category.find({}).sort({seq: 1, name: 1}).lean().exec();\n\n let numOfPostsOfUser = await Post.find({user: req.user._id}).limit(1).estimatedDocumentCount().exec();\n let hasPostedBefore = numOfPostsOfUser > 0;\n\n res.renderFile(path.join(pluginConf.viewsDir, 'forums-post.html'), \n { post: post, \n category: category,\n topic: topic,\n hasPostedBefore: hasPostedBefore,\n categories: categories,\n pluginConf: pluginConf });\n}", "dangerousExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/dan', function (req, res) {\n5. const url = req.body.profile_url;\n6. try{\n7. res.redirect(url);\n8. }catch (e) {\n9. return res.status(500).send(\"ERROR\");\n10. }\n11. });\n12. \n13. module.exports = router;\nLine 7: A string variable URL of an unvalidated external input is used to connect.", "safeExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/safe', function (req, res) {\n5. const url = req.body.profile_url;\n6. const white_list = [\"https://www.safeurl.com\", \"https://www.verified.com\"];\n7. if (white_list.indexOf(url) < 0) {\n8. return res.status(500).send(\"url not allowed\");\n9. } else {\n10. try {\n11. res.redirect(url);\n12. } catch (e) {\n13. return res.status(500).send(\"ERROR\");\n14. }\n15. }\n16. });\n17. \n18. module.exports = router;\nLine 7-9: Validate external inputs through a filter function.", "contexts": [{"lineNo": 74, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "req"}}, {"lineNo": 152, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "152"}}, {"lineNo": 153, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "redirect"}}]}} {"id": "2fecc6426b13397af0977b5d86f8cd9217ecb6b76a1292691be13ec776c23d61", "license": {"spdx": ["MIT"], "repo": "tashk85/sailor_mern_backend", "path": "controllers/comment_controller.js", "repo_head_hexsha": "9094aa2a68662310fc277b6a5280c5154fcd7cc0", "stack_hexsha": "505300afbf97c4472a54e342028c1772cd5a8987", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Redirection to untrusted site", "issueDescriptionEn": "The Redirection to untrusted site checker finds instances of redirecting to a URL generated with an unvalidated external input.\nAlthough connecting to a client-provided URL is often believed to be safe, an attacker can modify the request and redirect the user to a malicious site.\nMaintain a whitelist of external site URLs and domains allowed for redirection, which needs to be checked when a user input is passed as a redirect URL.", "issueLineNumber": 73, "entireCode": "const ArticleModel = require(\"./../database/models/article_model\");\nconst UserModel = require(\"./../database/models/user_model\");\n\n//render comments with users info\nasync function index(req, res, next) {\n let { articleId } = req.params;\n //find the article\n let article = await ArticleModel.findById(articleId);\n\n // send back all users' first&last name&userId for mention functions\n let users = await UserModel.find({});\n let filteredUsers = [];\n users.forEach(user => {\n let { firstName, lastName, email, _id: userId } = user;\n filterdUser = { firstName, lastName, email, userId };\n filteredUsers.push(filterdUser);\n return filteredUsers;\n });\n\n return res.send({ article, filteredUsers });\n}\n\n// API to create comment\nasync function createComment(req, res) {\n // access comments' body, user_metadata & mention info\n let { articleId } = req.params;\n let { body, user_metadata, date_posted, mentions } = req.body;\n\n //add comment to ArticleModel with commentors' info\n let article = await ArticleModel.findById(articleId);\n article.comments.push({ body, user_metadata, date_posted });\n await article.save();\n\n\n // Article Data\n let mentionedArticle = {\n mentioned_artileTitle: article.metadata.title,\n mentioned_url: `/article/${articleId}`\n };\n\n // add notification via mention to UserModel\n\n // find the mentionees in UserModel\n// push commentors' & mentionedAritcle' info into notifications;\n mentions.taggedUsers.forEach(email => {\n UserModel.find({ \"email\": email })\n .then(mentionee => {\n if (!mentionee[0].notifications.includes({ user_metadata, mentionedArticle })) {\n mentionee[0].notifications.unshift({ user_metadata, mentionedArticle });\n mentionee[0].save();\n }\n })\n })\n\n res.json(article.comments);\n}\n\nasync function destroyComment(req, res) {\n let { articleId } = req.params;\n let { _id: commentId, admin } = req.body;\n\n // access current article and the comment array\n let article = await ArticleModel.findById(articleId);\n let comment = await article.comments;\n\n //find the comment by commentId & delete by admin Only;\n let index = comment.indexOf(commentId);\n if (admin === true) {\n comment.splice(index, 1);\n await article.save();\n }\n\n res.redirect(`/article/${articleId}`);\n}\n\nmodule.exports = {\n index,\n createComment,\n destroyComment\n};", "dangerousExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/dan', function (req, res) {\n5. const url = req.body.profile_url;\n6. try{\n7. res.redirect(url);\n8. }catch (e) {\n9. return res.status(500).send(\"ERROR\");\n10. }\n11. });\n12. \n13. module.exports = router;\nLine 7: A string variable URL of an unvalidated external input is used to connect.", "safeExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/safe', function (req, res) {\n5. const url = req.body.profile_url;\n6. const white_list = [\"https://www.safeurl.com\", \"https://www.verified.com\"];\n7. if (white_list.indexOf(url) < 0) {\n8. return res.status(500).send(\"url not allowed\");\n9. } else {\n10. try {\n11. res.redirect(url);\n12. } catch (e) {\n13. return res.status(500).send(\"ERROR\");\n14. }\n15. }\n16. });\n17. \n18. module.exports = router;\nLine 7-9: Validate external inputs through a filter function.", "contexts": [{"lineNo": 59, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 73, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "articleId"}}, {"lineNo": 73, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "redirect"}}]}} {"id": "4618341129e78c04ae76cfb0af4e1c5e7342023773a61292cba0104a7820b433", "license": {"spdx": ["MIT"], "repo": "Nathn/NTChat", "path": "controllers/chatController.js", "repo_head_hexsha": "c46ed63d78b15bc788049dd107a1b305a4c15a52", "stack_hexsha": "35eacf11a2b4ccd7d6e4d9bf9dadd59def198b39", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Redirection to untrusted site", "issueDescriptionEn": "The Redirection to untrusted site checker finds instances of redirecting to a URL generated with an unvalidated external input.\nAlthough connecting to a client-provided URL is often believed to be safe, an attacker can modify the request and redirect the user to a malicious site.\nMaintain a whitelist of external site URLs and domains allowed for redirection, which needs to be checked when a user input is passed as a redirect URL.", "issueLineNumber": 219, "entireCode": "const User = require('../models/User');\nconst ChatMessage = require('../models/ChatMessage');\nconst Channel = require('../models/Channel');\nconst Question = require('../models/Question');\nconst cloudinary = require('cloudinary').v2;\nconst moment = require('moment');\nconst levenshtein = require('js-levenshtein');\n// require(\"copy-paste\").global();\n\nmoment.locale('fr');\n\nexports.chatPage = async (req, res) => {\n\ttry {\n\t\tif (!req.query.chan) return res.render('error', {\n\t\t\terrormsg: 'No channel selected'\n\t\t});\n\t\tvar channelsList = await Channel.find()\n\t\tvar channel = await Channel.findOne({\n\t\t\tselector: req.query.chan\n\t\t})\n\t\tif (!channel) return res.render('error', {\n\t\t\terrormsg: 'Selected channel not found'\n\t\t});\n\t\tvar messages = await ChatMessage.find({\n\t\t\tchannel: req.query.chan\n\t\t}).populate('author').sort({\n\t\t\tcreated: 'asc'\n\t\t}).limit(300);\n\t\tif (req.query.chan == 'ann') {\n\t\t\tfunction filter_users(message) {\n\t\t\t\treturn message.author.moderator == true;\n\t\t\t}\n\t\t\tmessages = messages.filter(filter_users);\n\t\t}\n\t\tres.render('chat', {\n\t\t\tmessages,\n\t\t\tchannel,\n\t\t\tchannelsList: channelsList,\n\t\t\tmoment\n\t\t});\n\t} catch (e) {\n\t\tconsole.log(e);\n\t\tres.render('error', {\n\t\t\terrormsg: e\n\t\t});\n\t}\n}\n\nexports.uploadImage = async (req, res, next) => {\n\ttry {\n\t\tif (req.files) {\n\t\t\tconst image = req.files.image;\n\t\t\tif (image) {\n\t\t\t\ttry {\n\t\t\t\t\tawait cloudinary.uploader.upload(image.tempFilePath, {\n\t\t\t\t\t\t\tformat: 'png',\n\t\t\t\t\t\t\ttransformation: [{\n\t\t\t\t\t\t\t\twidth: 500,\n\t\t\t\t\t\t\t\tcrop: \"scale\"\n\t\t\t\t\t\t\t}]\n\t\t\t\t\t\t},\n\t\t\t\t\t\tasync function (err, result) {\n\t\t\t\t\t\t\tconsole.log(result, err)\n\t\t\t\t\t\t\tif (result) {\n\t\t\t\t\t\t\t\tconst imageurl = result.secure_url.toString()\n\t\t\t\t\t\t\t\treq.imageurl = imageurl\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t)\n\t\t\t\t} catch (e) {\n\t\t\t\t\tconsole.log(e);\n\t\t\t\t\tres.render('error', {\n\t\t\t\t\t\terrormsg: e\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t\tnext();\n\t\t} else {\n\t\t\tnext();\n\t\t}\n\t} catch (e) {\n\t\tconsole.log(e);\n\t\tres.render('error', {\n\t\t\terrormsg: e\n\t\t});\n\t}\n}\n\nasync function html(str, channels) {\n\tvar replacedText, replacePattern1, replacePattern2, replacePattern3, replacePattern4, replacePattern5;\n\n\t//URLs starting with http://, https://, or ftp://\n\treplacePattern1 = /(\\b(https?|ftp):\\/\\/[-A-Z0-9+&@#\\/%?=~_|!:,.;]*[-A-Z0-9+&@#\\/%=~_|])/gim;\n\treplacedText = str.replace(replacePattern1, `$1`);\n\n\t//URLs starting with \"www.\" (without // before it, or it'd re-link the ones done above).\n\treplacePattern2 = /(^|[^\\/])(www\\.[\\S]+(\\b|$))/gim;\n\treplacedText = replacedText.replace(replacePattern2, '$1$2');\n\n\treplacePattern3 = /\\*\\*([^]+)\\*\\*/gim;\n\treplacedText = replacedText.replace(replacePattern3, '$1')\n\n\treplacePattern4 = /\\*([^*]+)\\*/gim;\n\treplacedText = replacedText.replace(replacePattern4, '$1')\n\n\treplacePattern5 = /\\`([^`]+)\\`/gim;\n\treplacedText = replacedText.replace(replacePattern5, '$1')\n\n\tvar chanList = \"\\\\B\\\\#(\";\n\tfor (let i = 0; i < channels.length; i++) {\n\t\tchanList += channels[i].name.toLowerCase();\n\t\tif (i != channels.length - 1) chanList += \"|\"\n\t}\n\tchanList += \")\\\\b\"\n\treplacedText = await replacedText.replace(new RegExp(chanList, \"gim\"), function (match, input) {\n\t\tfor (let i = 0; i < channels.length; i++) {\n\t\t\tif (input.toLowerCase() == channels[i].name.toLowerCase()) chan = channels[i]\n\t\t\tif (i != channels.length - 1) chanList += \"|\"\n\t\t}\n\t\tif (chan) var chanselector = chan.selector\n\t\tvar post = match\n\t\tif (chanselector) post = `${match}`;\n\t\treturn post;\n\t})\n\n\treturn replacedText\n}\n\nexports.sendmsg = async (req, res) => {\n\ttry {\n\t\tif (req.imageurl) {\n\t\t\treq.body.image = req.imageurl\n\t\t} else if (!req.body.text) {\n\t\t\treturn res.redirect('back')\n\t\t} else if (!req.body.text.replace(/\\s/g, '').length) {\n\t\t\treturn res.redirect('back')\n\t\t}\n\t\tif (!req.user) return res.redirect('/fs');\n\t\tif (req.params.channel == 'ann' && !req.user.moderator) res.redirect('/fs');\n\t\treq.body.author = req.user._id;\n\t\treq.body.channel = req.params.channel;\n\t\tvar channels = await Channel.find()\n\t\tif (req.body.text) req.body.content = await html(req.body.text.replace(/\\/g, \">\"), channels)\n\t\t// Interactive quizz implementation\n\t\tvar quizzChan = await Channel.findOne({\n\t\t\tquizzchan: true\n\t\t})\n\t\tif (quizzChan && req.params.channel == quizzChan.selector) {\n\t\t\tvar currentQuestion = await Question.findOne({\n\t\t\t\tcurrent: true\n\t\t\t})\n\t\t\tif (currentQuestion.type == \"maths\" || currentQuestion.type == \"date\") {\n\t\t\t\tvar maxDist = 0\n\t\t\t} else {\n\t\t\t\tvar maxDist = 3\n\t\t\t}\n\t\t\tif (req.body.text && levenshtein(req.body.text.toLowerCase(), currentQuestion.answer.toLowerCase()) <= maxDist) {\n\t\t\t\treq.body.content = \"\" + currentQuestion.answer.charAt(0).toUpperCase() + currentQuestion.answer.slice(1) + \"\"\n\t\t\t\tconst msg = new ChatMessage(req.body);\n\t\t\t\tawait msg.save();\n\t\t\t\tvar quizzBot = await User.findOne({\n\t\t\t\t\tusername: \"quizzbot\"\n\t\t\t\t})\n\t\t\t\tvar bestUser = await User.findOne({\n\t\t\t\t\tquizzFirst: true\n\t\t\t\t})\n\t\t\t\tawait User.findOneAndUpdate({\n\t\t\t\t\t_id: req.user._id\n\t\t\t\t}, {\n\t\t\t\t\t$inc: {\n\t\t\t\t\t\tquestionsAnswered: 1\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\tif (req.user.quizzFirst != true && req.user.questionsAnswered > bestUser.questionsAnswered) {\n\t\t\t\t\tawait User.findOneAndUpdate({\n\t\t\t\t\t\t_id: req.user._id\n\t\t\t\t\t}, {\n\t\t\t\t\t\t$set: {\n\t\t\t\t\t\t\tquizzFirst: true\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t\tawait User.findOneAndUpdate({\n\t\t\t\t\t\t_id: bestUser._id\n\t\t\t\t\t}, {\n\t\t\t\t\t\t$set: {\n\t\t\t\t\t\t\tquizzFirst: false\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tawait Question.findOneAndUpdate({\n\t\t\t\t\t_id: currentQuestion._id\n\t\t\t\t}, {\n\t\t\t\t\t$set: {\n\t\t\t\t\t\tcurrent: false\n\t\t\t\t\t}\n\t\t\t\t})\n\n\t\t\t\tif (quizzBot) {\n\t\t\t\t\tif (currentQuestion.trivia) {\n\t\t\t\t\t\tvar randomMessage = currentQuestion.trivia\n\t\t\t\t\t} else {\n\t\t\t\t\t\tvar ggMessages = [\"Quel crack celui là !\", \"GGWP.\", \"Juste le boss en fait.\", \"Poggers !\", \"Il doit avoir un QI d'au moins 143.\", \"Je suis jaloux...\", \"J'avais peur que personne ne soit à la hauteur...\", \"Tu es trop fort... That's kinda sus.\", \"L'humanité n'attendait plus que toi !\", \"Mais c'est une vraie machine de guerre celui-là !\"]\n\t\t\t\t\t\tvar randomMessage = ggMessages[Math.floor(Math.random() * ggMessages.length)];\n\t\t\t\t\t}\n\t\t\t\t\tvar botMsg = new ChatMessage({\n\t\t\t\t\t\tauthor: quizzBot._id,\n\t\t\t\t\t\tchannel: req.params.channel,\n\t\t\t\t\t\ttext: `**C'était bien ${currentQuestion.answer}, ${req.user.name} a trouvé la bonne réponse ! ${randomMessage}**`,\n\t\t\t\t\t\tcontent: `C'était bien ${currentQuestion.answer}, ${req.user.name} a trouvé la bonne réponse ! ${randomMessage}`\n\t\t\t\t\t});\n\t\t\t\t\tsetTimeout(async function saveMsg() {await botMsg.save()}, 1500);\n\t\t\t\t\tsendNewQuestion(req.params.channel, quizzBot)\n\t\t\t\t}\n\t\t\t\treturn res.redirect('/fs?chan=' + req.params.channel);\n\t\t\t}\n\t\t}\n\t\tconst msg = new ChatMessage(req.body);\n\t\tawait msg.save();\n\t\tres.redirect('/fs?chan=' + req.params.channel);\n\t} catch (e) {\n\t\tconsole.log(e);\n\t\tres.redirect('/fs?err=400')\n\t}\n}\n\nasync function sendNewQuestion(channel, quizzBot) {\n\tawait Question.countDocuments().exec(async function (err, count) {\n\t\tvar random = Math.floor(Math.random() * count)\n\t\tQuestion.findOne().skip(random).exec(\n\t\t\tasync function (err, result) {\n\t\t\t\tif (err) return res.render('error', {\n\t\t\t\t\terrormsg: err\n\t\t\t\t});\n\t\t\t\tawait Question.findOneAndUpdate({\n\t\t\t\t\t_id: result._id\n\t\t\t\t}, {\n\t\t\t\t\t$set: {\n\t\t\t\t\t\tcurrent: true\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\tvar newQMessages = [\"Nouvelle question : \", \"Question suivante : \", \"Nouvelle question ! \", \"On passe à la question suivante : \"]\n\t\t\t\tvar randomMessage = newQMessages[Math.floor(Math.random() * newQMessages.length)];\n\t\t\t\tif (result.type == \"maths\") randomMessage = \"Un peu de maths pour cette prochaine question : \"\n\t\t\t\tvar botMsg = new ChatMessage({\n\t\t\t\t\tauthor: quizzBot._id,\n\t\t\t\t\tchannel: channel,\n\t\t\t\t\ttext: `**${randomMessage}${result.question}**`,\n\t\t\t\t\tcontent: `${randomMessage}${result.question}`\n\t\t\t\t});\n\t\t\t\t// 5 seconds between each question\n\t\t\t\tsetTimeout(async function saveMsg() {await botMsg.save()}, 5000);\n\t\t\t}\n\t\t)\n\t})\n}\n\n\nexports.deletemsg = async (req, res) => {\n\ttry {\n\t\tconst message = await ChatMessage.findOne({\n\t\t\t_id: req.params.id\n\t\t});\n\t\tif (message) channel = message.channel\n\t\tif (req.user && req.user.moderator && message) {\n\t\t\tawait ChatMessage.deleteOne(message);\n\t\t}\n\t\tres.redirect('/chat?chan=' + channel);\n\t} catch (e) {\n\t\tconsole.log(e);\n\t\tres.redirect('/fs?err=400')\n\t}\n}\n\nexports.ban = async (req, res) => {\n\ttry {\n\t\tif (req.user && req.user.moderator) {\n\t\t\tawait User.findOneAndUpdate({\n\t\t\t\t_id: req.params.id\n\t\t\t}, {\n\t\t\t\tbanned: true\n\t\t\t});\n\t\t}\n\t\tres.redirect('/chat?chan=' + req.params.channel);\n\t} catch (e) {\n\t\tconsole.log(e);\n\t\tres.render('error', {\n\t\t\terrormsg: e\n\t\t});\n\t}\n}\n/*\nexports.copymsg = async (req, res) => {\n\ttry {\n\t\tconst message = await ChatMessage.findOne({\n\t\t\t\t_id: req.params.id\n\t\t\t});\n\t\tchannel = message.channel\n\t\tif (message){\n\t\t\tif (message.code){\n\t\t\t\tcopy(message.code)\n\t\t\t}\n\t\t}\n\t\tres.redirect('/chat-'+channel);\n\t} catch (e) {\n\t\tconsole.log(e);\n\t\tres.render('error', {\n\t\t\t\t\t\terrormsg: e\n\t\t\t\t\t});\n\t}\n}\n*/\nexports.postcode = async (req, res) => {\n\ttry {\n\t\tif (!req.body.code) {\n\t\t\treturn res.redirect('back')\n\t\t} else if (!req.body.code.replace(/\\s/g, '').length) {\n\t\t\treturn res.redirect('back')\n\t\t}\n\t\tif (!req.user) return res.redirect('/fs');\n\t\treq.body.author = req.user._id;\n\t\treq.body.channel = req.params.channel;\n\t\tconst msg = new ChatMessage(req.body);\n\t\tawait msg.save();\n\t\tres.redirect('/fs?chan=' + req.params.channel);\n\t} catch (e) {\n\t\tconsole.log(e);\n\t\tres.render('error', {\n\t\t\terrormsg: e\n\t\t});\n\t}\n}", "dangerousExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/dan', function (req, res) {\n5. const url = req.body.profile_url;\n6. try{\n7. res.redirect(url);\n8. }catch (e) {\n9. return res.status(500).send(\"ERROR\");\n10. }\n11. });\n12. \n13. module.exports = router;\nLine 7: A string variable URL of an unvalidated external input is used to connect.", "safeExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/safe', function (req, res) {\n5. const url = req.body.profile_url;\n6. const white_list = [\"https://www.safeurl.com\", \"https://www.verified.com\"];\n7. if (white_list.indexOf(url) < 0) {\n8. return res.status(500).send(\"url not allowed\");\n9. } else {\n10. try {\n11. res.redirect(url);\n12. } catch (e) {\n13. return res.status(500).send(\"ERROR\");\n14. }\n15. }\n16. });\n17. \n18. module.exports = router;\nLine 7-9: Validate external inputs through a filter function.", "contexts": [{"lineNo": 133, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "req"}}, {"lineNo": 219, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "redirect"}}]}} {"id": "2adeb0ad87f2a82afc7e71964639e1e27b3b1d97ca98c2bd7dc7d6f7f95a1d66", "license": {"spdx": ["Unlicense", "Apache-2.0", "MIT"], "repo": "gree/pulse", "path": "src/controllers/viewCheck.js", "repo_head_hexsha": "199cb9d36c9533893adba65c8077113956bb6ccb", "stack_hexsha": "3639021fa183a03c7605b310dec16a93a2401404", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Redirection to untrusted site", "issueDescriptionEn": "The Redirection to untrusted site checker finds instances of redirecting to a URL generated with an unvalidated external input.\nAlthough connecting to a client-provided URL is often believed to be safe, an attacker can modify the request and redirect the user to a malicious site.\nMaintain a whitelist of external site URLs and domains allowed for redirection, which needs to be checked when a user input is passed as a redirect URL.", "issueLineNumber": 50, "entireCode": "var url = require('url');\nvar CheckDisplays = require('../model/checkDisplays')\nvar serviceListener = require(\"../model/serviceListener\");\nvar logger = require(\"../helpers/logger\").getInstance();\nvar Checks = require(\"../model/checks\");\nvar template = require(\"../model/template\");\n\nfunction handleRequest(req, res) {\n logger.error(\"viewCheck called\");\n var queryString = url.parse(req.url, true).query;\n if (req.method === \"POST\") {\n queryString = req.body;\n }\n \n var healthCheck;\n var action;\n var title;\n var services = serviceListener.getServices();\n \n\tif (services.length != 0) {\n if (queryString.action === \"add\") {\n var Check = Checks.HealthCheck;\n healthCheck = new Check();\n healthCheck.init(0, '', queryString.service_id, '', 60, '', '', '', '', 300, new Date(), new Date(),'','','',\"enabled\");\n action = \"add\";\n title = \"Adding\";\n } else {\n dbHealthCheck = serviceListener.getHealthCheck(queryString.id, queryString.service_id);\n if (dbHealthCheck) {\n healthCheck = dbHealthCheck;\n if(typeof healthCheck.dynamic_config === \"object\"){\n var temp = healthCheck.dynamic_config;\n if(temp){\n if(typeof temp === \"object\"){\n temp = temp.sort();\n }\n healthCheck.dynamic_config = \"\";\n for(var x in temp){\n healthCheck.dynamic_config+=temp[x]+\",\\n\";\n }\n }\n }\n action = \"edit\";\n title = \"Editing\"\n }\n }\n \n if (healthCheck === undefined) {\n logger.error(\"Could not create health check\");\n res.redirect('/viewServiceChecks?service_id=' + queryString.service_id);\n return;\n }\n \n var service_name = \"\";\n \n var service = services[queryString.service_id];\n var service_name = undefined;\n if (service !== undefined) {\n service_name = service.name;\n }\n res.render(\"checks/viewCheck.jade\", {\n check: healthCheck,\n title: \"Health Dashboard - \" + title + \" Health Check\",\n action: action,\n services: services,\n check_types: CheckDisplays.getAllHealthCheckDisplays(),\n json_check_types: JSON.stringify(CheckDisplays.getAllHealthCheckDisplays()),\n businessintelligence: healthCheck.businessintelligence,\n templates:template.getAllTemplatesSorted()\n });\n } else {\n // If there are no services, force the user to create one\n res.redirect(\"/viewService?action=add\");\n }\n}\n\nexports.handleRequest = handleRequest;", "dangerousExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/dan', function (req, res) {\n5. const url = req.body.profile_url;\n6. try{\n7. res.redirect(url);\n8. }catch (e) {\n9. return res.status(500).send(\"ERROR\");\n10. }\n11. });\n12. \n13. module.exports = router;\nLine 7: A string variable URL of an unvalidated external input is used to connect.", "safeExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/safe', function (req, res) {\n5. const url = req.body.profile_url;\n6. const white_list = [\"https://www.safeurl.com\", \"https://www.verified.com\"];\n7. if (white_list.indexOf(url) < 0) {\n8. return res.status(500).send(\"url not allowed\");\n9. } else {\n10. try {\n11. res.redirect(url);\n12. } catch (e) {\n13. return res.status(500).send(\"ERROR\");\n14. }\n15. }\n16. });\n17. \n18. module.exports = router;\nLine 7-9: Validate external inputs through a filter function.", "contexts": [{"lineNo": 10, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "parse"}}, {"lineNo": 48, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "48"}}, {"lineNo": 50, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "queryString"}}, {"lineNo": 50, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "redirect"}}]}} {"id": "d2c6a090411a991869431975c6c57bd5eb09bd33f044e22a24bbb77b9877212f", "license": {"spdx": ["MIT"], "repo": "JuanHenriquez/blog-rest", "path": "app.js", "repo_head_hexsha": "b1244427c23299cca53fc4020cc1098d41bc8eaf", "stack_hexsha": "93cb270e96fc2cc54a86595e4aa29702f9f3bbb6", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Redirection to untrusted site", "issueDescriptionEn": "The Redirection to untrusted site checker finds instances of redirecting to a URL generated with an unvalidated external input.\nAlthough connecting to a client-provided URL is often believed to be safe, an attacker can modify the request and redirect the user to a malicious site.\nMaintain a whitelist of external site URLs and domains allowed for redirection, which needs to be checked when a user input is passed as a redirect URL.", "issueLineNumber": 108, "entireCode": "var express = require('express'),\n\tbodyParser = require('body-parser'),\n\tmongoose = require('mongoose'),\n\tmethodOverride = require('method-override'),\n\texpressSanitizer = require('express-sanitizer'),\n\tBlog = require('./models/blog.js'),\n\tapp = express();\n\n// App Config.\napp.use(express.static('public'));\napp.use(bodyParser.urlencoded({ extended: true }));\n\n// Take the route query string with _method paramter and coverto \n// to a specific method.\napp.use(methodOverride('_method'));\n\n// Use allways after body-parser.\napp.use(expressSanitizer());\n\napp.set('view engine', 'ejs');\n\n\n// ===============\n// DB Setup ======\n// ===============\nmongoose.connect('mongodb://localhost/blog-rest');\n\n\n\n\t// Blog.create({\n\t// \ttitle: 'Messi is the BEST!',\n\t// \timage: 'http://placehold.it/350x200',\n\t// \tbody: 'Messi won again the Golden Ball and now he have 5 balls in his house'\n\t// });\n\n// ===============\n// ROUTES ========\n// ===============\n\napp.get('/', function(req, res){\n\tres.redirect('/blogs');\n});\n\n// Index Route.\napp.get('/blogs', function(req, res){\n\tBlog.find({}, function(err, blogs){\n\t\tif (err) {\n\t\t\tconsole.log('ERROR: ' + err);\n\t\t} else {\n\t\t\tres.render('index', { blogs: blogs });\n\t\t}\n\t});\n});\n\n// New Route.\napp.get('/blogs/new', function(req, res){\n\tres.render('new');\n});\n\n// Create Route.\napp.post('/blogs', function(req, res){\n\n\t// Sanitize the post description.\n\treq.body.blog.body = req.sanitize(req.body.blog.body);\n\n\tBlog.create(req.body.blog, function(err, blog){\n\t\tif (err) {\n\t\t\tres.render('new');\n\t\t} else {\n\t\t\tres.redirect('/blogs');\n\t\t}\n\t});\n});\n\n// Show Route.\napp.get('/blogs/:id', function(req, res){\n\tBlog.findById(req.params.id, function(err, blog){\n\t\tif (err) {\n\t\t\tres.redirect('/blogs');\n\t\t} else {\n\t\t\tres.render('show', { blog: blog });\n\t\t}\n\t});\n});\n\n// Edit Route.\napp.get('/blogs/:id/edit', function(req, res){\n\tBlog.findById(req.params.id, function(err, blog){\n\t\tif (err) {\n\t\t\tres.redirect('/blogs');\n\t\t} else {\n\t\t\tres.render('edit', { blog: blog });\n\t\t}\n\t});\n});\n\n// Update Route.\napp.put('/blogs/:id', function(req, res){\n\n\t// Sanitize the post description.\n\treq.body.blog.body = req.sanitize(req.body.blog.body);\n\n\tBlog.findByIdAndUpdate(req.params.id, req.body.blog, function(err, blog){\n\t\tif (err) {\n\t\t\tconsole.log('Error: ' + err);\n\t\t\tres.redirect('/blogs');\n\t\t} else {\n\t\t\tres.redirect('/blogs/' + req.params.id);\n\t\t}\n\t})\n});\n\n// Delete Route.\napp.delete('/blogs/:id', function(req, res){\n\tBlog.findByIdAndRemove(req.params.id, function(err){\n\t\tif (err) {\n\t\t\tconsole.log('Error: ' + err);\n\t\t\tres.redirect('/blogs');\n\t\t} else {\n\t\t\tres.redirect('/blogs');\n\t\t}\n\t});\n});\n\napp.listen(process.env.PORT || 3000, process.env.IP, function() {\n\tconsole.log('Blog REST Server has started.');\n});\n\n", "dangerousExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/dan', function (req, res) {\n5. const url = req.body.profile_url;\n6. try{\n7. res.redirect(url);\n8. }catch (e) {\n9. return res.status(500).send(\"ERROR\");\n10. }\n11. });\n12. \n13. module.exports = router;\nLine 7: A string variable URL of an unvalidated external input is used to connect.", "safeExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/safe', function (req, res) {\n5. const url = req.body.profile_url;\n6. const white_list = [\"https://www.safeurl.com\", \"https://www.verified.com\"];\n7. if (white_list.indexOf(url) < 0) {\n8. return res.status(500).send(\"url not allowed\");\n9. } else {\n10. try {\n11. res.redirect(url);\n12. } catch (e) {\n13. return res.status(500).send(\"ERROR\");\n14. }\n15. }\n16. });\n17. \n18. module.exports = router;\nLine 7-9: Validate external inputs through a filter function.", "contexts": [{"lineNo": 104, "eventType": "source", "messageKey": "synz.COMMON.branch.false.assumed", "params": {"arg0": "107"}}, {"lineNo": 108, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "req"}}, {"lineNo": 108, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "redirect"}}]}} {"id": "467c41ea8e02459028c510f9ac4bf006670180fd9023e5624fef48ccbad378d3", "license": {"spdx": ["Apache-2.0", "MIT"], "repo": "peteblakemore/epao-certification", "path": "app/views/claim-management/version-2/find-a-claim/routes.js", "repo_head_hexsha": "a8f3534dc1f9754f93d82eb16466a6ad5adc933f", "stack_hexsha": "f80cbbc05921972ba3f228e5a937051fbfe088ec", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Redirection to untrusted site", "issueDescriptionEn": "The Redirection to untrusted site checker finds instances of redirecting to a URL generated with an unvalidated external input.\nAlthough connecting to a client-provided URL is often believed to be safe, an attacker can modify the request and redirect the user to a malicious site.\nMaintain a whitelist of external site URLs and domains allowed for redirection, which needs to be checked when a user input is passed as a redirect URL.", "issueLineNumber": 6, "entireCode": "const express = require('express')\n\nconst router = new express.Router()\n\nrouter.get('/', (req, res) => {\n res.redirect(`/${req.feature}/${req.sprint}/find-a-claim/search`)\n})\n\nrouter.get('/search', (req, res) => {\n const findNino = req.query.findNino\n res.render(`${req.feature}/${req.sprint}/find-a-claim/search`, {findNino})\n})\n\nrouter.post('/search', (req, res) => {\n const findNino = req.body.findNino.toUpperCase()\n if (findNino === 'AA111999A') {\n res.redirect(`/${req.feature}/${req.sprint}/find-a-claim/claim1`)\n } else if (findNino === 'BC123456E') {\n res.redirect(`/${req.feature}/${req.sprint}/find-a-claim/claim2`)\n } else {\n res.render(`${req.feature}/${req.sprint}/find-a-claim/search`, {findNino})\n }\n})\n\nmodule.exports = router", "dangerousExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/dan', function (req, res) {\n5. const url = req.body.profile_url;\n6. try{\n7. res.redirect(url);\n8. }catch (e) {\n9. return res.status(500).send(\"ERROR\");\n10. }\n11. });\n12. \n13. module.exports = router;\nLine 7: A string variable URL of an unvalidated external input is used to connect.", "safeExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/safe', function (req, res) {\n5. const url = req.body.profile_url;\n6. const white_list = [\"https://www.safeurl.com\", \"https://www.verified.com\"];\n7. if (white_list.indexOf(url) < 0) {\n8. return res.status(500).send(\"url not allowed\");\n9. } else {\n10. try {\n11. res.redirect(url);\n12. } catch (e) {\n13. return res.status(500).send(\"ERROR\");\n14. }\n15. }\n16. });\n17. \n18. module.exports = router;\nLine 7-9: Validate external inputs through a filter function.", "contexts": [{"lineNo": 6, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "req"}}, {"lineNo": 6, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "redirect"}}]}} {"id": "153b7dcd8f666a284ff7543cf484c85dc70d735b0af6276ea1e35bbef543758f", "license": {"spdx": ["MIT"], "repo": "RedaLegzali/StackUnderflow", "path": "routes/questions.js", "repo_head_hexsha": "d99f6c36b1208c6a4ebd216abb9d217cc0e836c6", "stack_hexsha": "6a801824643d65f54bc7f4f7ab6e60b8467e59a0", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Redirection to untrusted site", "issueDescriptionEn": "The Redirection to untrusted site checker finds instances of redirecting to a URL generated with an unvalidated external input.\nAlthough connecting to a client-provided URL is often believed to be safe, an attacker can modify the request and redirect the user to a malicious site.\nMaintain a whitelist of external site URLs and domains allowed for redirection, which needs to be checked when a user input is passed as a redirect URL.", "issueLineNumber": 61, "entireCode": "const router = require(\"express\").Router();\nconst Question = require(\"../models/Question\");\nconst { isConnected } = require(\"../middleware/security\");\nconst ObjectId = require(\"mongoose\").Types.ObjectId;\nconst isValid = require(\"mongoose\").Types.ObjectId.isValid;\n\n// Get Single question\nrouter.get(\"/:id\", isConnected, async (req, res) => {\n if (isValid(req.params.id)) {\n let question = await Question.aggregate([\n {\n $lookup: {\n from: \"users\",\n localField: \"user\",\n foreignField: \"email\",\n as: \"user\"\n }\n },\n { $unwind: \"$user\" },\n { $match: { _id: ObjectId(req.params.id) } }\n ]);\n if (question.length == 0) res.redirect(\"/questions\");\n else {\n question = question[0];\n res.render(\"app/question\", {\n title: question.subject,\n question\n });\n }\n } else res.redirect(\"/questions\");\n});\n// Post answer question\nrouter.post(\"/:id\", isConnected, async (req, res) => {\n let { best, body } = req.body;\n let id = req.params.id;\n let locals;\n let success = \"\";\n if (best) {\n let id = req.params.id;\n let question = await Question.findOne({ _id: id });\n question.best = best;\n await question.save();\n success = \"Answer voted successfully\";\n locals = { success };\n } else {\n let errors = [];\n if (!body) errors.push(\"Answer can't be blank\");\n if (errors.length == 0) {\n let question = await Question.findOne({ _id: id });\n question.answers.push({\n _id: ObjectId(),\n body,\n user: req.session.user.name\n });\n await question.save();\n success = \"Answer added successfully\";\n locals = { success };\n } else locals = { errors, success, body };\n }\n req.flash(\"locals\", locals);\n res.redirect(`/questions/${id}`);\n});\n// Get questions page\nrouter.get(\"/\", isConnected, async (req, res) => {\n let search = req.query.search;\n let category = req.query.category;\n let questions;\n if (typeof search == \"undefined\" && typeof category == \"undefined\") {\n questions = await Question.aggregate([\n {\n $lookup: {\n from: \"users\",\n localField: \"user\",\n foreignField: \"email\",\n as: \"user\"\n }\n },\n { $unwind: \"$user\" },\n { $match: { category: { $in: res.locals.categories } } }\n ]);\n } else if (typeof search == \"undefined\") {\n questions = await Question.aggregate([\n {\n $lookup: {\n from: \"users\",\n localField: \"user\",\n foreignField: \"email\",\n as: \"user\"\n }\n },\n { $unwind: \"$user\" },\n {\n $match: {\n $and: [\n { category: { $in: res.locals.categories } },\n { category: category }\n ]\n }\n }\n ]);\n } else if (typeof category == \"undefined\") {\n questions = await Question.aggregate([\n {\n $lookup: {\n from: \"users\",\n localField: \"user\",\n foreignField: \"email\",\n as: \"user\"\n }\n },\n { $unwind: \"$user\" },\n {\n $match: {\n $and: [\n { category: { $in: res.locals.categories } },\n { subject: { $regex: search, $options: \"gi\" } }\n ]\n }\n }\n ]);\n } else {\n questions = await Question.aggregate([\n {\n $lookup: {\n from: \"users\",\n localField: \"user\",\n foreignField: \"email\",\n as: \"user\"\n }\n },\n { $unwind: \"$user\" },\n {\n $match: {\n $and: [\n { category: { $in: res.locals.categories } },\n { category: category },\n { subject: { $regex: search, $options: \"gi\" } }\n ]\n }\n }\n ]);\n }\n res.render(\"app/questions\", {\n title: \"Questions\",\n questions, selected: category\n });\n});\n// Post Question\nrouter.post(\"/\", isConnected, async (req, res) => {\n let { subject, body, category } = req.body;\n let errors = [];\n let success = \"\";\n let locals;\n if (!subject || !body || !category) errors.push(\"All fields are required\");\n if (subject) {\n let question = await Question.findOne({ subject: subject });\n if (question) errors.push(\"This subject already exists\");\n }\n if (errors.length == 0) {\n let question = new Question({\n user: req.session.user.email,\n subject,\n body,\n category\n });\n await question.save();\n success = \"Question added successfully\";\n locals = { success };\n } else locals = { errors, success, subject, body };\n req.flash(\"locals\", locals);\n res.redirect(\"/questions\");\n});\n\nmodule.exports = router;", "dangerousExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/dan', function (req, res) {\n5. const url = req.body.profile_url;\n6. try{\n7. res.redirect(url);\n8. }catch (e) {\n9. return res.status(500).send(\"ERROR\");\n10. }\n11. });\n12. \n13. module.exports = router;\nLine 7: A string variable URL of an unvalidated external input is used to connect.", "safeExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/safe', function (req, res) {\n5. const url = req.body.profile_url;\n6. const white_list = [\"https://www.safeurl.com\", \"https://www.verified.com\"];\n7. if (white_list.indexOf(url) < 0) {\n8. return res.status(500).send(\"url not allowed\");\n9. } else {\n10. try {\n11. res.redirect(url);\n12. } catch (e) {\n13. return res.status(500).send(\"ERROR\");\n14. }\n15. }\n16. });\n17. \n18. module.exports = router;\nLine 7-9: Validate external inputs through a filter function.", "contexts": [{"lineNo": 35, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 39, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "req"}}, {"lineNo": 61, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "redirect"}}]}} {"id": "2f7cf9a88a9935257fb12ddc71185c5b19582de0c046cb36a34501ffde501106", "license": {"spdx": ["MIT"], "repo": "xakepa/Video-Couses-Web-App", "path": "handlers/joinCourse.js", "repo_head_hexsha": "384439bae6eea5951c6516967d5990da9ac871c1", "stack_hexsha": "169f1665197d9e8346ae2a806212ee2a1acd3c5b", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Redirection to untrusted site", "issueDescriptionEn": "The Redirection to untrusted site checker finds instances of redirecting to a URL generated with an unvalidated external input.\nAlthough connecting to a client-provided URL is often believed to be safe, an attacker can modify the request and redirect the user to a malicious site.\nMaintain a whitelist of external site URLs and domains allowed for redirection, which needs to be checked when a user input is passed as a redirect URL.", "issueLineNumber": 14, "entireCode": "const Course = require('../models/course');\n\nmodule.exports = async (req, res) => {\n const id = req.params.id;\n const course = await Course.findById(id).lean();\n\n course.usersEnrolled.push(res.email);\n console.log(course);\n\n Course.findByIdAndUpdate(id, { $set: course }, { upsert: true })\n .then((course) => console.log('Enrolled Successfully!'))\n .catch(console.error)\n\n return res.redirect(`/details/${id}`);\n}", "dangerousExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/dan', function (req, res) {\n5. const url = req.body.profile_url;\n6. try{\n7. res.redirect(url);\n8. }catch (e) {\n9. return res.status(500).send(\"ERROR\");\n10. }\n11. });\n12. \n13. module.exports = router;\nLine 7: A string variable URL of an unvalidated external input is used to connect.", "safeExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/safe', function (req, res) {\n5. const url = req.body.profile_url;\n6. const white_list = [\"https://www.safeurl.com\", \"https://www.verified.com\"];\n7. if (white_list.indexOf(url) < 0) {\n8. return res.status(500).send(\"url not allowed\");\n9. } else {\n10. try {\n11. res.redirect(url);\n12. } catch (e) {\n13. return res.status(500).send(\"ERROR\");\n14. }\n15. }\n16. });\n17. \n18. module.exports = router;\nLine 7-9: Validate external inputs through a filter function.", "contexts": [{"lineNo": 4, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "req"}}, {"lineNo": 4, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 14, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "redirect"}}]}} {"id": "f3385f1b40a91583d63ff120b430179bb44e1f3023f4abdd153e260479869f24", "license": {"spdx": ["MIT"], "repo": "Ntn1712/LSM_project", "path": "routes/profile.js", "repo_head_hexsha": "7375c6deabeb4ff2442c2f030792e9e5ff3a92f4", "stack_hexsha": "7ce25a9da75db6c1950c7fcc1a5fc3c46ed70aae", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Redirection to untrusted site", "issueDescriptionEn": "The Redirection to untrusted site checker finds instances of redirecting to a URL generated with an unvalidated external input.\nAlthough connecting to a client-provided URL is often believed to be safe, an attacker can modify the request and redirect the user to a malicious site.\nMaintain a whitelist of external site URLs and domains allowed for redirection, which needs to be checked when a user input is passed as a redirect URL.", "issueLineNumber": 40, "entireCode": "var express = require(\"express\");\nvar router = express.Router();\nvar passport = require(\"passport\");\nvar User = require(\"../models/user\");\n\nrouter.get(\"/profile/:prof_id\", function (req, res) {\n User.findById(req.params.prof_id, function (err, foundProf) {\n if (err) {\n console.log(err);\n } else {\n res.render(\"profile/show\", {\n foundProf: foundProf,\n currentUser: req.user,\n });\n }\n });\n});\n\nrouter.get(\"/profile/:prof_id/edit\", function (req, res) {\n User.findById(req.params.prof_id, function (err, foundProf) {\n if (err) {\n console.log(err);\n } else {\n res.render(\"profile/edit\", {\n foundProf: foundProf,\n currentUser: req.user,\n });\n }\n });\n});\n\nrouter.put(\"/profile/:prof_id\", function (req, res) {\n User.findByIdAndUpdate(\n req.params.prof_id,\n req.body.user,\n function (err, updated) {\n if (err) {\n console.log(err);\n } else {\n res.redirect(\"/profile/\" + req.params.prof_id);\n }\n }\n );\n});\n\nrouter.delete(\"/profile/:prof_id\", function (req, res) {\n User.findByIdAndRemove(req.params.prof_id, function (err) {\n if (err) {\n console.log(err);\n } else {\n res.redirect(\"/\");\n }\n });\n});\n\nrouter.get(\"/profile/:prof_id/editPass\", function (req, res) {\n User.findById(req.params.prof_id, function (err, foundProf) {\n if (err) {\n console.log(err);\n } else {\n res.render(\"profile/editPass\", {\n foundProf: foundProf,\n currentUser: req.user,\n });\n }\n });\n});\n\nrouter.post(\"/profile/:prof_id\", function (req, res) {\n User.findById(req.params.prof_id, function (err, user) {\n if (err) {\n console.log(err);\n } else {\n if (!user) {\n console.log(err);\n } else {\n user.setPassword(req.body.newPassword, function (err) {\n if (err) {\n console.log(err);\n } else {\n user.save();\n res.redirect(\"/profile/\" + req.params.prof_id);\n }\n });\n }\n }\n });\n});\n\nmodule.exports = router;", "dangerousExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/dan', function (req, res) {\n5. const url = req.body.profile_url;\n6. try{\n7. res.redirect(url);\n8. }catch (e) {\n9. return res.status(500).send(\"ERROR\");\n10. }\n11. });\n12. \n13. module.exports = router;\nLine 7: A string variable URL of an unvalidated external input is used to connect.", "safeExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/safe', function (req, res) {\n5. const url = req.body.profile_url;\n6. const white_list = [\"https://www.safeurl.com\", \"https://www.verified.com\"];\n7. if (white_list.indexOf(url) < 0) {\n8. return res.status(500).send(\"url not allowed\");\n9. } else {\n10. try {\n11. res.redirect(url);\n12. } catch (e) {\n13. return res.status(500).send(\"ERROR\");\n14. }\n15. }\n16. });\n17. \n18. module.exports = router;\nLine 7-9: Validate external inputs through a filter function.", "contexts": [{"lineNo": 37, "eventType": "source", "messageKey": "synz.COMMON.branch.false.assumed", "params": {"arg0": "39"}}, {"lineNo": 40, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "req"}}, {"lineNo": 40, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "redirect"}}]}} {"id": "5a581f6c805c67b734cb41896e1dda2ea88b1effaba144906bc5b44e834b4601", "license": {"spdx": ["MIT"], "repo": "Flexgod/sportsBlog", "path": "controllers/commentController.js", "repo_head_hexsha": "cd362e6d5cb0c73476292d414ce489e40cbc8635", "stack_hexsha": "249ec0a3bf4716f08516a80fcc3111dee04b3e0e", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Redirection to untrusted site", "issueDescriptionEn": "The Redirection to untrusted site checker finds instances of redirecting to a URL generated with an unvalidated external input.\nAlthough connecting to a client-provided URL is often believed to be safe, an attacker can modify the request and redirect the user to a malicious site.\nMaintain a whitelist of external site URLs and domains allowed for redirection, which needs to be checked when a user input is passed as a redirect URL.", "issueLineNumber": 8, "entireCode": "const mongoose = require('mongoose');\nconst Comment = mongoose.model('Comment');\n//Post COmment\nexports.postComment = async (req, res) => {\n req.body.article = req.params.id;\n const comment = await (new Comment(req.body)).save();\n req.flash('success', 'COmment Posted');\n res.redirect(`/post/${req.body.post_slug}`);\n\n //res.json(req.body);\n}", "dangerousExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/dan', function (req, res) {\n5. const url = req.body.profile_url;\n6. try{\n7. res.redirect(url);\n8. }catch (e) {\n9. return res.status(500).send(\"ERROR\");\n10. }\n11. });\n12. \n13. module.exports = router;\nLine 7: A string variable URL of an unvalidated external input is used to connect.", "safeExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/safe', function (req, res) {\n5. const url = req.body.profile_url;\n6. const white_list = [\"https://www.safeurl.com\", \"https://www.verified.com\"];\n7. if (white_list.indexOf(url) < 0) {\n8. return res.status(500).send(\"url not allowed\");\n9. } else {\n10. try {\n11. res.redirect(url);\n12. } catch (e) {\n13. return res.status(500).send(\"ERROR\");\n14. }\n15. }\n16. });\n17. \n18. module.exports = router;\nLine 7-9: Validate external inputs through a filter function.", "contexts": [{"lineNo": 8, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "req"}}, {"lineNo": 8, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "redirect"}}]}} {"id": "a5e35ef4e14ec28bbec4ec89f7b83eeec5d3c076706c38397b3be39ca802bc79", "license": {"spdx": ["MIT"], "repo": "LNoe-lzy/view", "path": "routes/index.js", "repo_head_hexsha": "456b6359baa20bd668c49f314daadad7861e645d", "stack_hexsha": "ea12128b1fdadf14b424aee939136d99951a52de", "match": "repo_path"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Redirection to untrusted site", "issueDescriptionEn": "The Redirection to untrusted site checker finds instances of redirecting to a URL generated with an unvalidated external input.\nAlthough connecting to a client-provided URL is often believed to be safe, an attacker can modify the request and redirect the user to a malicious site.\nMaintain a whitelist of external site URLs and domains allowed for redirection, which needs to be checked when a user input is passed as a redirect URL.", "issueLineNumber": 128, "entireCode": "var express = require('express');\nvar router = express.Router();\nvar crypto = require('crypto');\nvar multer = require('multer');\nvar upload = multer({dest: 'public/images/tmp/'});\nvar fs = require('fs');\n\nvar User = require('../models/user');\nvar Image = require('../models/image');\nvar imgUpload = require('../modules/upload');\n\nvar request = require('request');\n\nvar youtusdk = require('tencentyoutuyun');\nvar youtuconf = youtusdk.conf;\nvar youtuauth = youtusdk.auth;\nvar youtu = youtusdk.youtu;\n\nvar t = new Date().getTime();\nvar e = new Date('July 21, 2017 01:15:00').getTime();\n// var orignal = 'u=1076306553&a=10079311&k=AKIDBIEXnsfTz7C6yfnZm4EUffU8aCj5Jhja&e=' + e + '&t='+ t +'&r=270494647&f=';\nvar userID = youtuauth.appSign(e, '1076306553');\nyoutuconf.setAppInfo('10079311', '', 'pTvCHBuWxGSWO4Zt9JI5i9PTLDxeBaqv', '1076306553', 0);\n\nconsole.log(userID);\n\n/* GET home page. */\nrouter.get('/', function (req, res) {\n\n res.render('home', {\n title: 'VIEW',\n user: req.session.user\n });\n});\n\n// signup & signin\nrouter.post('/signup', function (req, res) {\n var userData = {\n username: req.body.username,\n password: crypto.createHash('md5').update(req.body.password).digest('hex')\n };\n User.findOne({\n username: userData.username\n }, function (err, u) {\n if (err) {\n return err;\n }\n if (u) {\n req.flash('error', '用户已存在');\n res.redirect('/');\n }\n var newUser = new User({\n username: userData.username,\n password: \n });\n newUser.save(function (err) {\n if (err) {\n return err;\n }\n req.session.user = userData;\n return res.redirect('/');\n });\n })\n});\nrouter.post('/signin', function (req, res) {\n var userData = {\n username: req.body.username,\n password: crypto.createHash('md5').update(req.body.password).digest('hex')\n };\n User.findOne({\n username: userData.username\n }, function (err, u) {\n if (err) {\n return err;\n }\n if (!u || (u.password !== .password)) {\n req.flash('error', '用户名或密码错误!');\n res.redirect('/');\n }\n req.session.user = u;\n return res.redirect('/');\n });\n});\n\n// logout\nrouter.get('/logout', function (req, res) {\n req.session.user = null;\n res.redirect('/');\n});\n\n// image\nrouter.get('/image', function (req, res) {\n Image.find(null).sort({_id: -1}).exec(function (err, img) {\n if (err) {\n console.log(err);\n }\n res.render('image', {\n title: 'View',\n user: req.session.user,\n imgs: img\n });\n });\n});\n\n// tag page\nrouter.get('/tag', function (req, res) {\n res.render('tag', {\n title: 'View',\n user: req.session.user\n });\n});\n\n// 图像文件上传\nrouter.post('/send', upload.single('image'), function (req, res) {\n var currentUser = req.session.user,\n info = req.body.info,\n tag = req.body.tag,\n username = currentUser.username,\n tmp_path = req.file.path,\n file_name = req.file.filename,\n mimeType = req.file.mimetype;\n imgUpload.imgUpload(tmp_path, file_name, mimeType, username, info, tag, 'upload', req, res);\n});\n\nrouter.post('/search', upload.single('image'), function (req, res) {\n var tmp_path, file_name, mimeType, target_path, extName, store_path, tags, face, queryTxt;\n if (req.file === undefined) {\n res.redirect('/search/' + req.body.queryText);\n } else if (req.body.queryText === 'face' && req.file !== 'undefined') {\n tmp_path = req.file.path;\n file_name = req.file.filename;\n mimeType = req.file.mimetype;\n //指定存储位置\n target_path = 'public/images/search' + '/' + file_name;\n extName = '';\n switch (mimeType) {\n case 'image/pjpeg':\n extName = 'jpg';\n break;\n case 'image/jpeg':\n extName = 'jpg';\n break;\n case 'image/png':\n extName = 'png';\n break;\n case 'image/x-png':\n extName = 'png';\n break;\n }\n //判断文件是否为图像类型\n if (extName.length === 0) {\n req.flash('error', '只能上传图像!');\n return res.redirect('/');\n }\n //文件移动的目录\n store_path = target_path + '.' + extName;\n var page_path = '/images/search' + '/' + file_name + '.' + extName;\n fs.rename(tmp_path, store_path, function (err) {\n if (err) {\n console.log(err);\n }\n //删除临时文件\n fs.unlink(tmp_path, function () {\n if (err) {\n console.log(err);\n }\n });\n });\n\n youtu.detectface(store_path, 0, function (data) {\n face = data.data;\n req.session.face = face;\n req.session.faceurl = page_path;\n res.redirect('/face');\n });\n } else if (req.file.path !== 'undefined') {\n queryTxt = req.body.queryText || ' ';\n console.log(queryTxt);\n tmp_path = req.file.path;\n file_name = req.file.filename;\n mimeType = req.file.mimetype;\n //指定存储位置\n target_path = 'public/images/search' + '/' + file_name;\n extName = '';\n switch (mimeType) {\n case 'image/pjpeg':\n extName = 'jpg';\n break;\n case 'image/jpeg':\n extName = 'jpg';\n break;\n case 'image/png':\n extName = 'png';\n break;\n case 'image/x-png':\n extName = 'png';\n break;\n }\n //判断文件是否为图像类型\n if (extName.length === 0) {\n req.flash('error', '只能上传图像!');\n return res.redirect('/');\n }\n //文件移动的目录\n store_path = target_path + '.' + extName;\n fs.rename(tmp_path, store_path, function (err) {\n if (err) {\n console.log(err);\n }\n //删除临时文件\n fs.unlink(tmp_path, function () {\n if (err) {\n console.log(err);\n }\n });\n });\n\n var img_path = '/images/search' + '/' + file_name + '.' + extName;\n youtu.imagetag(store_path, function (data) {\n tags = data.data.tags;\n req.session.tags = tags;\n req.session.queryTxt = queryTxt;\n req.session.imgurl = img_path;\n res.redirect('/analyse');\n });\n }\n});\n\nrouter.get('/analyse', function (req, res) {\n res.render('analyse', {\n title: 'analyse',\n user: req.session.user,\n tags: req.session.tags,\n imgurl: req.session.imgurl,\n queryTxt: req.session.queryTxt\n });\n});\n\nrouter.get('/face', function (req, res) {\n res.render('face', {\n title: 'face',\n user: req.session.user,\n face: req.session.face,\n faceurl: req.session.faceurl\n });\n});\n\n// 返回搜索结果\nrouter.get('/search/:query', function (req, res) {\n var params = {\n // Request parameters\n \"q\": encodeURI(req.params.query),\n \"count\": \"20\",\n \"offset\": \"0\",\n \"mkt\": \"en-us\",\n \"safeSearch\": \"Moderate\"\n };\n\n request({\n url: 'https://api.cognitive.microsoft.com/bing/v5.0/images/search?' + 'q=' + params.q + '&count=' + params.count + '&offset=0&mkt=en-us&safeSearch=Moderate',\n method: \"GET\",\n json: true,\n headers: {\n \"Ocp-Apim-Subscription-Key\": \"b269334d107e442db4c02a38984eebee\"\n },\n body: \"{body}\"\n }, function (error, response, body) {\n if (!error && response.statusCode == 200) {\n // console.log(body.value);\n res.render('search', {\n title: 'search',\n user: req.session.user,\n imgs: body.value\n });\n }\n });\n});\n\nrouter.get('/food', function (req, res) {\n res.render('food', {\n title: 'food',\n user: req.session.user\n });\n});\n\nmodule.exports = router;", "dangerousExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/dan', function (req, res) {\n5. const url = req.body.profile_url;\n6. try{\n7. res.redirect(url);\n8. }catch (e) {\n9. return res.status(500).send(\"ERROR\");\n10. }\n11. });\n12. \n13. module.exports = router;\nLine 7: A string variable URL of an unvalidated external input is used to connect.", "safeExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/safe', function (req, res) {\n5. const url = req.body.profile_url;\n6. const white_list = [\"https://www.safeurl.com\", \"https://www.verified.com\"];\n7. if (white_list.indexOf(url) < 0) {\n8. return res.status(500).send(\"url not allowed\");\n9. } else {\n10. try {\n11. res.redirect(url);\n12. } catch (e) {\n13. return res.status(500).send(\"ERROR\");\n14. }\n15. }\n16. });\n17. \n18. module.exports = router;\nLine 7-9: Validate external inputs through a filter function.", "contexts": [{"lineNo": 127, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "127"}}, {"lineNo": 128, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "req"}}, {"lineNo": 128, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "redirect"}}]}} {"id": "692f62dd19dfb53bf33494d50a27381843e3f9f10c93432c87d4a9c0912e60fa", "license": {"spdx": ["MIT"], "repo": "stephenbek/doSciences_nodeJS", "path": "routes/posts.js", "repo_head_hexsha": "6703c68df019064a96ebcc0dd37bf50e138ddda3", "stack_hexsha": "62b34056b2910a9f6e5ea0103493769b2fca2c08", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Redirection to untrusted site", "issueDescriptionEn": "The Redirection to untrusted site checker finds instances of redirecting to a URL generated with an unvalidated external input.\nAlthough connecting to a client-provided URL is often believed to be safe, an attacker can modify the request and redirect the user to a malicious site.\nMaintain a whitelist of external site URLs and domains allowed for redirection, which needs to be checked when a user input is passed as a redirect URL.", "issueLineNumber": 15, "entireCode": "const express = require('express');\nconst router = express.Router();\nconst { ensureAuthenticated } = require('../config/auth');\nconst Post = require('../models/Post');\nconst Comment = require('../models/Comment');\nvar mongoose = require('mongoose');\n\nrouter.get('/', async (req, res) => { \n const posts = await Post.find().sort('-date');\n \n res.render('posts', {posts: posts , auth: req.isAuthenticated()}); \n});\n\nrouter.post('/', (req, res) => { \n res.redirect(`/posts/seepost/${req.body.postid}`,200,{id2:req.body.postid}); \n});\n\nrouter.get('/api', async (req, res) => { \n const posts = await Post.find().sort('-date'); \n res.send(posts); \n});\n\nrouter.get('/createpost', ensureAuthenticated, (req, res) => {\n res.render('createpost', { user: req.user, auth: req.isAuthenticated() });\n});\n\nrouter.post('/createpost', ensureAuthenticated, (req, res) => {\n const post = new Post({\n name: req.body.postName,\n userId: req.user._id,\n userName: req.user.name,\n content: req.body.textBox\n })\n post.save()\n .then(user => {\n req.flash('success_msg', 'Your post was submitted succesfully');\n res.redirect('/posts',200, { auth: req.isAuthenticated() });\n })\n .catch(err => console.error(err));\n});\n\nrouter.get('/seepost/:id', async (req,res)=>{\n //console.log(res.body.id2);\n const post = await Post.findById(req.params.id);\n const comments = await Comment.find({postId:req.params.id}).sort('-date');\n if (comments!=null){\n res.render('seepost',{post: post , user: req.user, comments:comments, auth: req.isAuthenticated()});\n }else{\n res.render('seepost',{post: post , user: req.user, comments:null, auth: req.isAuthenticated()}); \n }\n});\n\nrouter.get('/api/seepost/:id', async (req,res)=>{ \n const post = await Post.findById(req.params.id);\n const comments = await Comment.find({postId:req.params.id});\n const arr = [post, comments];\n res.send(arr); \n});\n\nrouter.post('/seepost/:id', ensureAuthenticated, async (req, res) => {\n if(req.body.button==\"addcomment\"){\n console.log(req.body.postid);\n const comment = new Comment({\n userId: req.user.id,\n userName:req.body.userName,\n content: req.body.textBox,\n postId: req.body.postid\n }); \n const post = await Post.findById(req.params.id); \n comment.save()\n .then(user=>{res.redirect(`/posts/seepost/${req.params.id}`,200, { post:post, user: req.user, auth: req.isAuthenticated() })})\n .catch(err => console.error(err));\n } \n});\n\nmodule.exports = router;", "dangerousExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/dan', function (req, res) {\n5. const url = req.body.profile_url;\n6. try{\n7. res.redirect(url);\n8. }catch (e) {\n9. return res.status(500).send(\"ERROR\");\n10. }\n11. });\n12. \n13. module.exports = router;\nLine 7: A string variable URL of an unvalidated external input is used to connect.", "safeExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/safe', function (req, res) {\n5. const url = req.body.profile_url;\n6. const white_list = [\"https://www.safeurl.com\", \"https://www.verified.com\"];\n7. if (white_list.indexOf(url) < 0) {\n8. return res.status(500).send(\"url not allowed\");\n9. } else {\n10. try {\n11. res.redirect(url);\n12. } catch (e) {\n13. return res.status(500).send(\"ERROR\");\n14. }\n15. }\n16. });\n17. \n18. module.exports = router;\nLine 7-9: Validate external inputs through a filter function.", "contexts": [{"lineNo": 15, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "req"}}, {"lineNo": 15, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "redirect"}}]}} {"id": "92b900c0b5ad21f947ce3eb37949b053dcfcd143e9088df69bd1805b00fa6571", "license": {"spdx": ["MIT"], "repo": "panphora/storiess-remake-app", "path": "_remake/lib/init-user-accounts.js", "repo_head_hexsha": "429449373ca3f1ee66f97f129279fcc9ec656ec8", "stack_hexsha": "42c903683eb0385d4bbc9058ff1a385cdefc8cf4", "match": "repo_path"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Redirection to untrusted site", "issueDescriptionEn": "The Redirection to untrusted site checker finds instances of redirecting to a URL generated with an unvalidated external input.\nAlthough connecting to a client-provided URL is often believed to be safe, an attacker can modify the request and redirect the user to a malicious site.\nMaintain a whitelist of external site URLs and domains allowed for redirection, which needs to be checked when a user input is passed as a redirect URL.", "issueLineNumber": 146, "entireCode": "const passport = require(\"passport\");\nconst LocalStrategy = require(\"passport-local\").Strategy;\nconst validUsernameRegex = /^[a-zA-Z0-9_-]+$/;\nconst bcrypt = require(\"bcryptjs\");\nconst crypto = require(\"crypto\");\nimport { createUserData, getUserData, setUserData } from \"./user-data\";\nimport { showConsoleError } from \"../utils/console-utils\";\nimport { capture } from \"../utils/async-utils\";\nimport { getReservedWordInfo } from \"../utils/get-reserved-word-info\";\nimport { sendEmail } from \"../utils/send-email\";\n\nfunction initUserAccounts({ app }) {\n app.use(passport.initialize());\n app.use(passport.session());\n\n // The local strategy require a `verify` function which receives the credentials\n passport.use(\n new LocalStrategy(\n {\n passReqToCallback: true,\n },\n async function (req, username, password, cb) {\n let appName = req.appName;\n\n try {\n let [currentUser] = await capture(getUserData({ username, appName }));\n\n if (!currentUser) {\n cb(null, false);\n return;\n }\n\n let [passwordMatches] = await capture(bcrypt.compare(password, currentUser.details.hash));\n\n if (!passwordMatches) {\n cb(null, false);\n return;\n }\n\n cb(null, currentUser);\n return;\n } catch (err) {\n showConsoleError(\"Error: Passport db error\", err);\n cb(err);\n }\n }\n )\n );\n\n passport.serializeUser(function (currentUser, cb) {\n cb(null, {\n username: currentUser.details.username,\n appName: currentUser.details.appName,\n });\n });\n\n passport.deserializeUser(async function (currentUserData, cb) {\n let [currentUser, err] = await capture(\n getUserData({\n username: currentUserData.username,\n appName: currentUserData.appName,\n })\n );\n\n if (currentUser) {\n cb(null, currentUser);\n } else {\n showConsoleError(\"Error: Passport db error\", err);\n cb(err);\n }\n });\n\n app.post(/(\\/app_[a-z]+[a-z0-9-]*)?\\/user\\/signup/, async function (req, res) {\n let appName = req.appName;\n let { username = \"\", password = \"\", email = \"\" } = req.body;\n\n if (password.length < 8 || username.length < 1 || !validUsernameRegex.test(username)) {\n if (password.length < 8) {\n req.flash(\"error\", \"Your password must be at least 8 characters\");\n res.redirect(\"/user/signup\");\n return;\n }\n\n if (username.length < 1) {\n req.flash(\"error\", \"Please enter a username\");\n res.redirect(\"/user/signup\");\n return;\n }\n\n if (username.startsWith(\"_\") || username.startsWith(\"-\")) {\n req.flash(\"error\", `Your username needs to start with a letter or number`);\n res.redirect(\"/user/signup\");\n return;\n }\n\n if (!validUsernameRegex.test(username)) {\n req.flash(\n \"error\",\n `Your username can only contain letters, numbers, and certain symbols (\"_\" or \"-\")`\n );\n res.redirect(\"/user/signup\");\n return;\n }\n }\n\n let reservedWordInfo = getReservedWordInfo(username);\n if (reservedWordInfo.isReserved) {\n req.flash(\n \"error\",\n `Your username can't contain the reserved word: \"${reservedWordInfo.reservedWord}\"`\n );\n res.redirect(\"/user/signup\");\n return;\n }\n\n let [usernameTaken] = await capture(getUserData({ username }));\n if (usernameTaken) {\n req.flash(\"error\", \"That username is taken, please try another one!\");\n res.redirect(\"/user/signup\");\n return;\n }\n\n let [hash] = await capture(bcrypt.hash(password, 14));\n let [newUser, newUserError] = await capture(createUserData({ appName, username, hash, email }));\n\n req.login(newUser, function (err) {\n if (!err) {\n req.session.save(err => {\n res.redirect(\"/\" + newUser.details.username);\n });\n } else {\n req.flash(\"error\", \"Error creating user account\");\n res.redirect(\"/user/login\");\n }\n });\n });\n\n app.post(\n /(\\/app_[a-z]+[a-z0-9-]*)?\\/user\\/login/,\n passport.authenticate(\"local\", {\n failureRedirect: \"/login\",\n failureFlash: \"Invalid username or password\",\n }),\n function (req, res) {\n req.session.save(err => {\n res.redirect(\"/\" + req.user.details.username);\n });\n }\n );\n\n app.get(/(\\/app_[a-z]+[a-z0-9-]*)?\\/user\\/logout/, function (req, res) {\n req.session.destroy(err => {\n req.logout();\n res.redirect(\"/user/login\");\n });\n });\n\n app.post(/(\\/app_[a-z]+[a-z0-9-]*)?\\/user\\/forgot/, async function (req, res) {\n let appName = req.appName;\n let { username } = req.body;\n let [currentUser] = await capture(getUserData({ username, appName }));\n\n if (!currentUser) {\n req.flash(\"error\", \"User not found\");\n res.redirect(\"/user/forgot\");\n return;\n }\n\n let token = crypto.randomBytes(32).toString(\"hex\");\n let details = currentUser.details;\n details.resetPasswordToken = ;\n details.resetPasswordExpires = Date.now() + 7200000; // plus two hours\n\n setUserData({ appName, username, data: details, type: \"details\" });\n\n sendEmail(\n {\n email: details.email,\n subject: `Reset your password for ${req.urlData.host}`,\n body: `Hi ${username},

    You can reset your password by following this link:

    ${\n req.protocol + \"://\" + req.urlData.host + \"/user/reset/\" + username + \"/\" + token\n }`,\n },\n function (err) {\n if (err) {\n req.flash(\"error\", `Couldn't send password reset email. Please try again.`);\n res.redirect(\"/user/forgot\");\n } else {\n req.flash(\"success\", \"An email with a link to change your password has been sent!\");\n res.redirect(\"/user/login\");\n }\n }\n );\n });\n\n app.get(/(\\/app_[a-z]+[a-z0-9-]*)?\\/user\\/reset/, async function (req, res, next) {\n let appName = req.appName;\n\n // get username and token\n let pathnameSplit = req.urlData.urlPathname.split(\"/\");\n let resetStringIndex = pathnameSplit.indexOf(\"reset\");\n let username = pathnameSplit[resetStringIndex + 1];\n let token = pathnameSplit[resetStringIndex + 2];\n\n let [currentUser] = await capture(getUserData({ username, appName }));\n\n if (!currentUser) {\n req.flash(\"error\", \"User not found\");\n res.redirect(\"/user/forgot\");\n return;\n }\n\n let expiresDate = currentUser.details.resetPasswordExpires;\n if (typeof expiresDate !== \"number\" || Date.now() > expiresDate) {\n req.flash(\"error\", \"Password reset token is invalid or has expired. Please try again.\");\n res.redirect(\"/user/forgot\");\n return;\n }\n\n if (!token || token !== currentUser.details.resetPasswordToken) {\n req.flash(\"error\", \"Password reset token is invalid or has expired. Please try again.\");\n res.redirect(\"/user/forgot\");\n return;\n }\n\n next();\n });\n\n app.post(/(\\/app_[a-z]+[a-z0-9-]*)?\\/user\\/reset/, async function (req, res) {\n let appName = req.appName;\n let { password } = req.body;\n\n // get username and token\n let pathnameSplit = req.urlData.urlPathname.split(\"/\");\n let resetStringIndex = pathnameSplit.indexOf(\"reset\");\n let username = pathnameSplit[resetStringIndex + 1];\n let token = pathnameSplit[resetStringIndex + 2];\n\n let [currentUser] = await capture(getUserData({ username, appName }));\n\n if (!currentUser) {\n req.flash(\"error\", \"User not found\");\n res.redirect(\"/user/forgot\");\n return;\n }\n\n let expiresDate = currentUser.details.resetPasswordExpires;\n if (typeof expiresDate !== \"number\" || Date.now() > expiresDate) {\n req.flash(\"error\", \"Password reset token is invalid or has expired. Please try again.\");\n res.redirect(\"/user/forgot\");\n return;\n }\n\n if (!token || token !== currentUser.details.resetPasswordToken) {\n req.flash(\"error\", \"Password reset token is invalid or has expired. Please try again.\");\n res.redirect(\"/user/forgot\");\n return;\n }\n\n if (!password || password.length < 8) {\n req.flash(\"error\", \"Your password must be at least 8 characters\");\n res.redirect(\"/user/signup\");\n return;\n }\n\n let details = currentUser.details;\n let [hash] = await capture(bcrypt.hash(password, 14));\n details.hash = hash;\n details.resetPasswordToken = ;\n details.resetPasswordExpires = null;\n setUserData({ appName, username, data: details, type: \"details\" });\n\n req.login(currentUser, function (err) {\n if (!err) {\n req.flash(\"success\", \"Your password was successfully reset!\");\n res.redirect(\"/\" + currentUser.details.username);\n } else {\n req.flash(\"success\", \"Success! Please log in with your new password\");\n res.redirect(\"/user/login\");\n }\n });\n });\n}\n\nexport { initUserAccounts };", "dangerousExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/dan', function (req, res) {\n5. const url = req.body.profile_url;\n6. try{\n7. res.redirect(url);\n8. }catch (e) {\n9. return res.status(500).send(\"ERROR\");\n10. }\n11. });\n12. \n13. module.exports = router;\nLine 7: A string variable URL of an unvalidated external input is used to connect.", "safeExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/safe', function (req, res) {\n5. const url = req.body.profile_url;\n6. const white_list = [\"https://www.safeurl.com\", \"https://www.verified.com\"];\n7. if (white_list.indexOf(url) < 0) {\n8. return res.status(500).send(\"url not allowed\");\n9. } else {\n10. try {\n11. res.redirect(url);\n12. } catch (e) {\n13. return res.status(500).send(\"ERROR\");\n14. }\n15. }\n16. });\n17. \n18. module.exports = router;\nLine 7-9: Validate external inputs through a filter function.", "contexts": [{"lineNo": 146, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "req"}}, {"lineNo": 146, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "redirect"}}]}} {"id": "c25fe8374d1fb032935cbe45bcd6d766abb135e54bec8907fd608fefa75ecda5", "license": {"spdx": ["MIT"], "repo": "yuraantonov11/soriba", "path": "controllers/products.js", "repo_head_hexsha": "f9b8a1c4e5134d8345168192450151cddd4feefa", "stack_hexsha": "453e7940eff6a1c8e172c05d569145fe6993b420", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Redirection to untrusted site", "issueDescriptionEn": "The Redirection to untrusted site checker finds instances of redirecting to a URL generated with an unvalidated external input.\nAlthough connecting to a client-provided URL is often believed to be safe, an attacker can modify the request and redirect the user to a malicious site.\nMaintain a whitelist of external site URLs and domains allowed for redirection, which needs to be checked when a user input is passed as a redirect URL.", "issueLineNumber": 140, "entireCode": "const Product = require('../models/Product');\nconst User = require('../models/User');\nconst Category = require('../models/Category');\n/**\n * GET /\n * Products page.\n */\nexports.index = (req, res) => {\n Product\n .find({})\n .exec((err, products) => {\n if (err) return res.send(err);\n // this will log all of the users with each of their posts\n Category.find({})\n .exec((err, categories) => {\n if (err) console.log(err);\n // this will log all of the users with each of their posts\n res.render('products/index', {\n title: 'All Products',\n products,\n categories: JSON.stringify(categories),\n importBtn: true,\n controls: true,\n });\n });\n });\n};\n/**\n * GET /\n * Edit Product page.\n */\nexports.editProductPage = (req, res) => {\n const { productId } = req.params;\n Product\n .findById(productId)\n .populate('categories', '_id')\n .exec((err, product) => {\n if (err) return res.send(err);\n // this will log all of the users with each of their posts\n // product.categories.map(c => c._id);\n Category.find({})\n .exec((err, c) => {\n if (err) console.log(err);\n // this will log all of the users with each of their posts\n const categories = c.map(e => ({\n name: e.name,\n _id: e._id.toString()\n }));\n product.categories = product.categories.map(c => c._id);\n res.render('products/edit', {\n title: 'Edit Product',\n categories: JSON.parse(JSON.stringify(categories)),\n productData: JSON.parse(JSON.stringify(product))\n });\n });\n });\n};\n\n/**\n * GET /\n * Unpublish Product.\n */\nexports.unpublishProduct = (req, res) => {\n const { productId } = req.params;\n Product.update({ _id: productId }, { $set: { published: false } }, (err) => {\n if (err) {\n console.error(err);\n req.flash('errors', 'Can not unpublish product.');\n } else {\n req.flash('success', { msg: 'Product has been unpublished.' });\n }\n\n res.redirect('/');\n });\n};\n\n/**\n * GET /\n * Publish Product.\n */\nexports.publishProduct = (req, res) => {\n const { productId } = req.params;\n Product.update({ _id: productId }, { $set: { published: true } }, (err) => {\n if (err) {\n console.error(err);\n req.flash('errors', 'Can not publish product.');\n } else {\n req.flash('success', { msg: 'Product has been published.' });\n }\n res.redirect('/');\n });\n};\n\n/**\n * GET /\n * Save to list Product.\n */\nexports.toggleSaved = (req, res) => {\n const { productId } = req.params;\n if (!req.user || !req.user._id) {\n req.flash('info', { msg: 'You need to authorize.' });\n return res.redirect('/');\n }\n\n User.findById(req.user._id)\n .select('savedProducts')\n .exec(function(err, object) {\n let json = JSON.parse(JSON.stringify(object.savedProducts));\n const savedProducts = new Set(json);\n if (savedProducts.has(productId)) {\n savedProducts.delete(productId);\n } else {\n savedProducts.add(productId);\n }\n object.savedProducts = [...savedProducts];\n object.save(function(err, model) {\n if (err) {\n console.error(err);\n req.flash('errors', 'Error.');\n } else {\n req.flash('success', { msg: 'Success.' });\n }\n res.redirect('/');\n });\n });\n};\n\n/**\n * POST /\n * Save Product method.\n */\nexports.editProduct = (req, res) => {\n const { body, user } = req;\n const { productId } = req.params;\n\n Product.findById(productId, (err, product) => {\n if (err) return res.sendStatus(500);\n if (product.creator.toString() !== user._id.toString()) {\n req.flash('errors', 'You do not have permission to edit this product');\n return res.redirect(`/products/${productId}`);\n }\n const data = {\n name: body.name,\n title: body.title,\n choice: (body.choice === 'on'),\n features: body.features,\n price: body.price,\n rating: body.rating,\n link: body.link,\n categories: body.categories,\n creator: user._id,\n };\n if (req.file && req.file.path) {\n data.image = req.file.path;\n }\n product.set(data);\n product.save((err, result) => {\n if (err) {\n req.flash('errors', err);\n return res.redirect(`/products/${productId}`);\n }\n // saved!\n req.flash('success', { msg: 'Product has been saved.' });\n return res.redirect('/my-products-page/');\n });\n });\n};\n\n/**\n * GET /\n * My Products page.\n */\nexports.indexMyProducts = (req, res) => {\n if (!req.user || !req.user._id) {\n req.flash('info', { msg: 'You need to authorize.' });\n return res.redirect('/');\n }\n\n Product\n .find({\n creator: req.user._id\n })\n .exec((err, products) => {\n if (err) return res.send(err);\n // this will log all of the users with each of their posts\n Category.find({})\n .exec((err, categories) => {\n if (err) console.log(err);\n // this will log all of the users with each of their posts\n res.render('products/my-products', {\n title: 'My Products',\n products,\n categories,\n controls: true\n });\n });\n });\n};\n\n\n/**\n * GET /\n * Products route.\n */\nexports.getAll = (req, res) => {\n const queries = {};\n for (const query in req.query) {\n if (req.query[query]) queries[query] = req.query[query];\n }\n Product\n .find(queries)\n .populate('categories', 'name')\n .select({\n name: 1,\n title: 1,\n rating: 1,\n price: 1,\n link: 1,\n imported: 1,\n createdAt: 1,\n categories: 1,\n })\n .exec((err, products) => {\n if (err) return res.send(err);\n // this will log all of the users with each of their posts\n res.send(products);\n });\n};\n\n/**\n * GET /\n * Product page.\n */\nexports.product = (req, res) => {\n const { productId } = req.params;\n Product\n .findById(productId)\n .populate('categories', '_id')\n .exec((err, product) => {\n if (err) return res.send(err);\n // this will log all of the users with each of their posts\n // product.categories.map(c => c._id);\n Category.find({})\n .exec((err, categories) => {\n if (err) console.log(err);\n res.render('products/product-page', {\n title: 'Product',\n main: true,\n product,\n categories\n });\n });\n });\n};\n/**\n * POST /\n * Delete Product.\n */\nexports.delete = (req, res) => {\n const { body } = req;\n Product.deleteMany({\n _id: { $in: body.ids }\n })\n .exec((err, data) => {\n if (err) return res.send(500, err);\n // this will log all of the users with each of their posts\n res.sendStatus(200);\n });\n};\n/**\n * POST /\n * Import Product.\n */\nexports.importProduct = (req, res) => {\n const { productId } = req.params;\n Product.update({ _id: productId }, { $set: { imported: true } }, (err) => {\n if (err) {\n console.error(err);\n res.sendStatus(500);\n } else {\n res.sendStatus(200);\n }\n });\n};\n/**\n * POST /\n * Export Product.\n */\nexports.exportProduct = (req, res) => {\n const { productId } = req.params;\n Product.update({ _id: productId }, { $set: { imported: false } }, (err) => {\n if (err) {\n console.error(err);\n res.sendStatus(500);\n } else {\n res.sendStatus(200);\n }\n });\n};\n\n/**\n * GET /\n * Export Products.\n */\nexports.exportProducts = (req, res) => {\n const { products } = req.body;\n if (!products) {\n // bad request!\n req.flash('error', { msg: 'Products not selected.' });\n return res.redirect('/products-page/');\n }\n\n Product.update({ _id: { $in: products } }, { $set: { imported: false } }, (err) => {\n if (err) {\n // error!\n console.error(err);\n req.flash('error', { msg: 'Error.' });\n } else {\n // saved!\n req.flash('success', { msg: 'Products are imported.' });\n }\n return res.redirect('/products-page/');\n });\n};\n\n/**\n * POST /\n * Export Products.\n */\nexports.importProducts = (req, res) => {\n const { products } = req.body;\n if (!products) {\n // bad request!\n req.flash('errors', { msg: 'Products are not selected.' });\n return res.redirect('/products-page/');\n }\n\n Product.update({ _id: { $in: products } }, { $set: { imported: true } }, (err) => {\n if (err) {\n // error!\n console.error(err);\n req.flash('errors', { msg: 'Error.' });\n } else {\n // saved!\n req.flash('success', { msg: 'Products are imported.' });\n }\n return res.redirect('/products-page/');\n });\n};\n/**\n * POST /\n * Export Products.\n */\nexports.deleteProducts = (req, res) => {\n const { products } = req.body;\n if (!products) {\n // bad request!\n req.flash('errors', { msg: 'Products are not selected.' });\n return res.redirect('/products-page/');\n }\n Product.deleteMany({\n _id: { $in: products }\n })\n .exec((err, data) => {\n // this will log all of the users with each of their posts\n if (err) {\n // error!\n console.error(err);\n req.flash('errors', { msg: 'Error.' });\n } else {\n // saved!\n req.flash('success', { msg: 'Products are deleted.' });\n }\n return res.redirect('/products-page/');\n });\n};\n\n\n/**\n * POST /\n * Add Product method.\n */\nexports.add = (req, res) => {\n const { body, user } = req;\n Product.create({\n name: body.name,\n title: body.title,\n choice: (body.choice === 'on'),\n features: body.features.filter(item => item),\n price: body.price,\n rating: body.rating,\n link: body.link,\n image: req.file.path,\n categories: body.categories,\n creator: user._id,\n }, (err) => {\n if (err) {\n req.flash('errors', err);\n return res.redirect('/login');\n }\n // saved!\n req.flash('success', { msg: 'Products has been added.' });\n return res.redirect('products/add/');\n });\n // res.render('products/product', {\n // title: 'Add new Product'\n // });\n};\n\n/**\n * GET /\n * Add Product page.\n */\nexports.addPage = (req, res) => {\n Category.find({})\n .exec((err, categories) => {\n if (err) console.log(err);\n // this will log all of the users with each of their posts\n res.render('products/add', {\n title: 'Add new Product',\n categories\n });\n });\n};", "dangerousExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/dan', function (req, res) {\n5. const url = req.body.profile_url;\n6. try{\n7. res.redirect(url);\n8. }catch (e) {\n9. return res.status(500).send(\"ERROR\");\n10. }\n11. });\n12. \n13. module.exports = router;\nLine 7: A string variable URL of an unvalidated external input is used to connect.", "safeExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/safe', function (req, res) {\n5. const url = req.body.profile_url;\n6. const white_list = [\"https://www.safeurl.com\", \"https://www.verified.com\"];\n7. if (white_list.indexOf(url) < 0) {\n8. return res.status(500).send(\"url not allowed\");\n9. } else {\n10. try {\n11. res.redirect(url);\n12. } catch (e) {\n13. return res.status(500).send(\"ERROR\");\n14. }\n15. }\n16. });\n17. \n18. module.exports = router;\nLine 7-9: Validate external inputs through a filter function.", "contexts": [{"lineNo": 134, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 138, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "138"}}, {"lineNo": 140, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "productId"}}, {"lineNo": 140, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "redirect"}}]}} {"id": "6cda4565bb05cbb044f219bfbc4d50051a62d145896b1dc4839500ffec7fc463", "license": {"spdx": ["MIT"], "repo": "dwp/gysp-agent-ui", "path": "app/routes/changes-enquiries/contact/functions.js", "repo_head_hexsha": "94a05e7a0a99eb63172aebde9bc326906a3c60c5", "stack_hexsha": "637fc0190e9fc68da1d4f56af799b806ae5ea650", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Redirection to untrusted site", "issueDescriptionEn": "The Redirection to untrusted site checker finds instances of redirecting to a URL generated with an unvalidated external input.\nAlthough connecting to a client-provided URL is often believed to be safe, an attacker can modify the request and redirect the user to a malicious site.\nMaintain a whitelist of external site URLs and domains allowed for redirection, which needs to be checked when a user input is passed as a redirect URL.", "issueLineNumber": 160, "entireCode": "const request = require('request-promise');\nconst httpStatus = require('http-status-codes');\n\nconst formValidator = require('../../../../lib/formValidator');\nconst requestHelper = require('../../../../lib/requestHelper');\nconst redirectHelper = require('../../../../lib/helpers/redirectHelper');\nconst secondaryNavigationHelper = require('../../../../lib/helpers/secondaryNavigationHelper');\nconst timelineHelper = require('../../../../lib/helpers/timelineHelper');\nconst contactDetailsObject = require('../../../../lib/contactDetailsObject');\nconst removeContactDetailsObject = require('../../../../lib/removeContactDetailsObject');\nconst contactDetailsOverview = require('../../../../lib/objects/view/contactDetailsOverview');\n\nconst contactDetailsUpdateUri = 'api/award/updatecontactdetails';\n\nconst activeSecondaryNavigationSection = 'contact';\n\nfunction isAddOrChange(details, type) {\n const telephone = new RegExp('^(?:home|mobile|work)$');\n const email = new RegExp('^(?:email)$');\n if (telephone.test(type)) {\n if (details[`${type}TelephoneNumber`] === null) {\n return 'add';\n }\n return 'change';\n }\n if (email.test(type)) {\n if (details[type] === null) {\n return 'add';\n }\n return 'change';\n }\n return 'change';\n}\n\nfunction globalErrorMessage(error) {\n if (error.statusCode === httpStatus.BAD_REQUEST) {\n return 'Error - connection refused.';\n }\n if (error.statusCode === httpStatus.NOT_FOUND) {\n return 'Error - award not found.';\n }\n return 'Error - could not save data.';\n}\n\nfunction contactDetailsView(type) {\n if (type === 'email') {\n return 'pages/changes-enquiries/contact/email';\n }\n return 'pages/changes-enquiries/contact/index';\n}\n\nfunction contactDetailsRemoveView(type) {\n if (type === 'email') {\n return 'pages/changes-enquiries/contact/remove-email';\n }\n return 'pages/changes-enquiries/contact/remove';\n}\n\nfunction getContactDetails(req, res) {\n const award = requestHelper.generateGetCall(`${res.locals.agentGateway}api/award/${req.session.searchedNino}`, {}, 'batch');\n request(award)\n .then(async (body) => {\n req.session.awardDetails = body;\n const details = contactDetailsOverview.formatter(body);\n const timelineDetails = await timelineHelper.getTimeline(req, res, 'CONTACT');\n const secondaryNavigationList = secondaryNavigationHelper.navigationItems(activeSecondaryNavigationSection);\n res.render('pages/changes-enquiries/contact/overview', {\n details, secondaryNavigationList, timelineDetails,\n });\n }).catch((err) => {\n const traceID = requestHelper.getTraceID(err);\n requestHelper.loggingHelper(err, 'cannot get contact details', traceID, res.locals.logger);\n res.render('pages/error', { status: '- Cannot get contact details.' });\n });\n}\n\nfunction getChangeContactDetails(req, res) {\n const { type } = req.params;\n const addOrChange = isAddOrChange(req.session.awardDetails.contactDetail, type);\n const viewPath = contactDetailsView(type);\n res.render(viewPath, {\n type,\n addOrChange,\n });\n}\n\nfunction postChangeContactDetailsErrorHandler(error, req, res, type, addOrChange) {\n const traceID = requestHelper.getTraceID(error);\n requestHelper.loggingHelper(error, contactDetailsUpdateUri, traceID, res.locals.logger);\n const viewPath = contactDetailsView(type);\n res.render(viewPath, {\n type,\n addOrChange,\n details: req.body,\n globalError: globalErrorMessage(error),\n });\n}\n\nfunction postChangeContactDetails(req, res) {\n const { type } = req.params;\n const addOrChange = isAddOrChange(req.session.awardDetails.contactDetail, type);\n const errors = formValidator.contactDetails(req.body, type, addOrChange);\n if (Object.keys(errors).length === 0) {\n const contactDetails = contactDetailsObject.formatter(req.body, req.session.awardDetails, type);\n const putContactDetailCall = requestHelper.generatePutCall(res.locals.agentGateway + contactDetailsUpdateUri, contactDetails, 'batch', req.user);\n request(putContactDetailCall).then(() => {\n redirectHelper.successAlertAndRedirect(req, res, `contact-details:success-message.${type}.${addOrChange}`, '/changes-and-enquiries/contact');\n }).catch((err) => {\n postChangeContactDetailsErrorHandler(err, req, res, type, addOrChange);\n });\n } else {\n const viewPath = contactDetailsView(type);\n res.render(viewPath, {\n type,\n addOrChange,\n details: req.body,\n errors,\n });\n }\n}\n\nfunction getRemoveContactDetails(req, res) {\n const { type } = req.params;\n const viewPath = contactDetailsRemoveView(type);\n res.render(viewPath, {\n type,\n });\n}\n\nfunction postRemoveContactDetailsErrorHandler(error, req, res, type) {\n const traceID = requestHelper.getTraceID(error);\n requestHelper.loggingHelper(error, contactDetailsUpdateUri, traceID, res.locals.logger);\n const viewPath = contactDetailsRemoveView(type);\n res.render(viewPath, {\n type,\n details: req.body,\n globalError: globalErrorMessage(error),\n });\n}\n\nfunction postRemoveContactDetails(req, res) {\n const { type } = req.params;\n const errors = formValidator.removeContact(req.body, type);\n if (Object.keys(errors).length === 0) {\n const input = req.body;\n if (input.removeContact === 'yes' || input.removeContactNumber === 'yes') {\n const contactDetails = removeContactDetailsObject.formatter(req.session.awardDetails, type);\n const putContactDetailCall = requestHelper.generatePutCall(\n res.locals.agentGateway + contactDetailsUpdateUri,\n contactDetails,\n 'batch',\n req.user,\n );\n request(putContactDetailCall).then(() => {\n redirectHelper.successAlertAndRedirect(req, res, `contact-details:success-message.${type}.remove`, '/changes-and-enquiries/contact');\n }).catch((err) => {\n postRemoveContactDetailsErrorHandler(err, req, res, type);\n });\n } else {\n res.redirect(`/changes-and-enquiries/contact/${type}`);\n }\n } else {\n const viewPath = contactDetailsRemoveView(type);\n res.render(viewPath, {\n type,\n details: req.body,\n errors,\n });\n }\n}\n\nmodule.exports.getContactDetails = getContactDetails;\nmodule.exports.getChangeContactDetails = getChangeContactDetails;\nmodule.exports.postChangeContactDetails = postChangeContactDetails;\nmodule.exports.getRemoveContactDetails = getRemoveContactDetails;\nmodule.exports.postRemoveContactDetails = postRemoveContactDetails;", "dangerousExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/dan', function (req, res) {\n5. const url = req.body.profile_url;\n6. try{\n7. res.redirect(url);\n8. }catch (e) {\n9. return res.status(500).send(\"ERROR\");\n10. }\n11. });\n12. \n13. module.exports = router;\nLine 7: A string variable URL of an unvalidated external input is used to connect.", "safeExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/safe', function (req, res) {\n5. const url = req.body.profile_url;\n6. const white_list = [\"https://www.safeurl.com\", \"https://www.verified.com\"];\n7. if (white_list.indexOf(url) < 0) {\n8. return res.status(500).send(\"url not allowed\");\n9. } else {\n10. try {\n11. res.redirect(url);\n12. } catch (e) {\n13. return res.status(500).send(\"ERROR\");\n14. }\n15. }\n16. });\n17. \n18. module.exports = router;\nLine 7-9: Validate external inputs through a filter function.", "contexts": [{"lineNo": 142, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 146, "eventType": "source", "messageKey": "synz.COMMON.branch.false.assumed", "params": {"arg0": "159"}}, {"lineNo": 160, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "type"}}, {"lineNo": 160, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "redirect"}}]}} {"id": "f644d34d1fb82e888b52d8971963ac53057fe1e89c220dd79bca5350214bae75", "license": {"spdx": ["MIT"], "repo": "troy0820/fixit-cali", "path": "routes/index.js", "repo_head_hexsha": "0839e89de207c0b31b14f7021f19c6a67b3f97e4", "stack_hexsha": "fff091c63138833ed61c941a88c3d69826c68534", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Redirection to untrusted site", "issueDescriptionEn": "The Redirection to untrusted site checker finds instances of redirecting to a URL generated with an unvalidated external input.\nAlthough connecting to a client-provided URL is often believed to be safe, an attacker can modify the request and redirect the user to a malicious site.\nMaintain a whitelist of external site URLs and domains allowed for redirection, which needs to be checked when a user input is passed as a redirect URL.", "issueLineNumber": 93, "entireCode": "var express = require('express');\nvar router = express.Router();\nvar request = require('request');\nvar _ = require('lodash');\nvar geocode = require('geocoder');\nvar Promise = require('bluebird');\n\nrouter.get('/health', function(req, res) {\n\tres.send('Good');\n});\n\nrouter.get('/', function(req, res) {\n var url = 'https://seeclickfix.com/api/v2/issues?place_url=santa-clara&state=CA&per_page=10&page=1';\n\n\n request(url, function(err, response, body) {\n if (err) {\n console.error(err);\n }\n var city = \"santa-clara\";\n var id = 1;\n var list = JSON.parse(body).issues;\n var metadata = JSON.parse(body).metadata;\n var per_page = metadata.pagination.per_page;\n var pages = metadata.pagination.pages;\n var lat = _.pluck(list, 'lat');\n var lng = _.pluck(list, 'lng');\n var summary = _.pluck(list, 'summary');\n var address = _.pluck(list, 'address');\n var start = 0;\n var next_page = 2;\n console.log('This is how many pages ', pages);\n if (id <= pages) {\n start = per_page * (id - 1);\n\n }\n if (id < pages) {\n next_page = (Number(id) + 1);\n }\n\n var title = city;\n var issues = pages * per_page;\n\n var getzips = function(lat, lng) {\n return new Promise(function(resolve, reject) {\n geocode.reverseGeocode(lat, lng, function(err, data) {\n if (err) { reject(err); }\n var zips = data.results[0].address_components;\n var newzips = _.reduce(zips, function(all, item, index) {\n if (item.types[0] == 'postal_code') {\n all.push(item.short_name);\n }\n return all;\n }, []);\n resolve(newzips);\n });\n });\n };\n\n Promise.all(lat.map(function(_, index) {\n return getzips(lat[index], lng[index]);\n })).then(function(data) {\n var zips = _.union(_.flatten(data));\n return zips;\n })\n .then(function(zips) {\n\n res.render('index', {\n title: title,\n list: list,\n lat: lat,\n lng: lng,\n summary: summary,\n per_page: per_page,\n pages: pages,\n start: start,\n city: city,\n next_page: next_page,\n address: address,\n issues: issues,\n zips: zips\n });\n });\n });\n});\n\nrouter.get('/:city', function(req, res) {\n var city = req.params.city;\n\n if (city == 'hampton') {\n res.redirect('/');\n } else {\n res.redirect('/' + city + '/1');\n }\n});\n\nrouter.get('/:city/:id', function(req, res) {\n var city = req.params.city;\n var id = req.params.id;\n if (city == 'hampton') {\n res.redirect('/');\n }\n var url = \"https://seeclickfix.com/api/v2/issues?place_url=\" + city + '&state=VA&per_page=10&page=' + id;\n\n request(url, function(err, response, body) {\n if (err) {\n console.error(err);\n }\n var list = JSON.parse(body).issues;\n var metadata = JSON.parse(body).metadata;\n var per_page = metadata.pagination.per_page;\n var pages = metadata.pagination.pages;\n var lat = _.pluck(list, 'lat');\n var lng = _.pluck(list, 'lng');\n var summary = _.pluck(list, 'summary');\n var address = _.pluck(list, 'address');\n var start = 0;\n var next_page = 2;\n console.log('This is how many pages ', pages);\n if (id <= pages) {\n start = per_page * (id - 1);\n\n }\n if (id < pages) {\n next_page = (Number(id) + 1);\n }\n\n if (city == 'newport-news') {\n title = 'newport news';\n } else if (city == 'virginia-beach') {\n title = 'virginia beach';\n } else if (city == 'hampton') {\n title = 'hampton';\n } else {\n title = city;\n }\n var issues = pages * per_page;\n\n var getzips = function(lat, lng) {\n return new Promise(function(resolve, reject) {\n geocode.reverseGeocode(lat, lng, function(err, data) {\n if (err) { reject(err); }\n var zips = data.results[0].address_components;\n var newzips = _.reduce(zips, function(all, item, index) {\n if (item.types[0] == 'postal_code') {\n all.push(item.short_name);\n }\n return all;\n }, []);\n resolve(newzips);\n });\n });\n };\n\n Promise.all(lat.map(function(_, index) {\n return getzips(lat[index], lng[index]);\n })).then(function(data) {\n var zips = _.union(_.flatten(data));\n return zips;\n })\n .then(function(zips) {\n\n res.render('index', {\n title: title,\n list: list,\n lat: lat,\n lng: lng,\n summary: summary,\n per_page: per_page,\n pages: pages,\n start: start,\n city: city,\n next_page: next_page,\n address: address,\n issues: issues,\n zips: zips\n });\n });\n });\n});\n\nrouter.post('/', function(req, res) {\n var city = req.body.city;\n var url = 'https://seeclickfix.com/api/v2/issues?place_url=' + city + '&state=VA'; //insert city in this link\n request(url, function(err, response, body) {\n if (err) {\n console.error(err);\n }\n var list = JSON.parse(body).issues;\n var lat = _.pluck(list, 'lat');\n var lng = _.pluck(list, 'lng');\n var summary = _.pluck(list, 'summary');\n res.render('index', { title: city, list: list, lat: lat, lng: lng, summary: summary });\n });\n\n\n});\n\nmodule.exports = router;", "dangerousExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/dan', function (req, res) {\n5. const url = req.body.profile_url;\n6. try{\n7. res.redirect(url);\n8. }catch (e) {\n9. return res.status(500).send(\"ERROR\");\n10. }\n11. });\n12. \n13. module.exports = router;\nLine 7: A string variable URL of an unvalidated external input is used to connect.", "safeExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/safe', function (req, res) {\n5. const url = req.body.profile_url;\n6. const white_list = [\"https://www.safeurl.com\", \"https://www.verified.com\"];\n7. if (white_list.indexOf(url) < 0) {\n8. return res.status(500).send(\"url not allowed\");\n9. } else {\n10. try {\n11. res.redirect(url);\n12. } catch (e) {\n13. return res.status(500).send(\"ERROR\");\n14. }\n15. }\n16. });\n17. \n18. module.exports = router;\nLine 7-9: Validate external inputs through a filter function.", "contexts": [{"lineNo": 88, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "req"}}, {"lineNo": 90, "eventType": "source", "messageKey": "synz.COMMON.branch.false.assumed", "params": {"arg0": "92"}}, {"lineNo": 93, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "redirect"}}]}} {"id": "b8963e369f922a2a2e2d9ebd99d0cdee36b398193113bd6d5f47032e75732ade", "license": {"spdx": ["0BSD"], "repo": "BubbaJoe/SE-PirateNotes", "path": "app/routes.js", "repo_head_hexsha": "d0e6763b342f9dbde342c17aee7345475529cb6c", "stack_hexsha": "13a0a0080f542103683c681242a550f9b1e1287d", "match": "repo_path"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Redirection to untrusted site", "issueDescriptionEn": "The Redirection to untrusted site checker finds instances of redirecting to a URL generated with an unvalidated external input.\nAlthough connecting to a client-provided URL is often believed to be safe, an attacker can modify the request and redirect the user to a malicious site.\nMaintain a whitelist of external site URLs and domains allowed for redirection, which needs to be checked when a user input is passed as a redirect URL.", "issueLineNumber": 506, "entireCode": "/*\n\n @author \n Software Engineering: East Carolina University\n PirateNotes\n\n routes.js - To configure the server endpoints or 'routes'.\n\n*/\n\nlet fs = require('fs')\nlet path = require('path')\nlet bcrypt\t= require('bcrypt-nodejs')\nlet async = require('async')\n\n// referenceLink = (the last link they requested before session ended)\nlet referenceLink = []\nlet forgotCode = []\n\n// Number of active users on the website\nlet numActiveUsers = 0\nlet requestArray = []\n\n// Express, Socket.IO, MySQL, and Passport\nmodule.exports = (app, io, pp) => {\n \n // Temp file cleaner\n async function trash() {\n await setTimeout( () => {\n p = __dirname+\"/../temp_uploads/\"\n fs.readdir(path.resolve(p),{},(err,files) => {\n files.forEach((file) => {\n // If the file is older than a minute\n if(file != '.gitignore' && (new Date() - Date.parse(fs.statSync(p+file).birthtime) > 60000))\n fs.unlink(p+file, () => {\n console.log('removed '+file)\n } )\n })\n })\n trash()\n }\n , 5000)\n }\n\n trash()\n\n // Socket.io handler\n io.sockets.on('connection',(socket) => {\n\n numActiveUsers ++\n\n socket.on(\"follow:department\", (data) => {\n console.log(\"dept:\")\n followDepartment(data.id,data.dept_id)\n .then(() => console.log(\"Followed\"))\n .catch(() => console.log(\"Already following!\"))\n })\n\n socket.on(\"follow:course\", (data) => {\n console.log(\"course:\")\n followCourse(data.id,data.course_id)\n .then(() => console.log(\"Followed\"))\n .catch(() => console.log(\"Already following!\"))\n })\n\n socket.on(\"like\", (data) => {\n likePost(data.id,data.post_id)\n .then(() => console.log(\"saved\"))\n .catch(() => console.log(\"Already like!\"))\n })\n\n socket.on(\"save\", (data) => {\n savePost(data.id,data.post_id)\n .catch(() => console.log(\"Already saved!\"))\n })\n\n socket.on(\"unfollow:department\", (data) => {\n unfollowDepartment(data.id,data.dept_id)\n .then(() => console.log(\"unFollowed\"))\n })\n\n socket.on(\"unfollow:course\", (data) => {\n unfollowCourse(data.id,data.course_id)\n .then(() => console.log(\"unFollowed\"))\n })\n\n socket.on(\"unlike\", (data) => {\n unlikePost(data.id,data.post_id)\n .then(() => console.log(\"unliked\"))\n })\n\n socket.on(\"unsave\", (data) => {\n unsavePost(data.id,data.post_id)\n .then(() => console.log(\"unsaved\"))\n })\n\n socket.on(\"accept\", (data) => {\n acceptPost(data)\n .then(() => console.log(\"accepted\"))\n })\n\n socket.on(\"decline\", (data) => {\n declinePost(data)\n .then(() => console.log(\"declined\"))\n })\n\n socket.on('disconnect', (socket) => {\n numActiveUsers --\n })\n\n });\n\n //Routes for endpoints\n\n app.get('/tos', (req,res) => {\n res.download(__dirname+'/../TermsOfService.pdf')\n })\n\n app.post('/forgot', (req,res) => {\n runQuery('select email from user where email = ? ',[req.fields.email])\n .then( (user) => {\n if(user[0]) {\n code = Math.floor(Math.random() * (99999 - 10000 + 1)) + 10000\n forgotCode[code] = user[0].id\n res.redirect('/')\n sendPasswordEmail(user[0].email, code) \n } else {\n req.flash('forgotError','This email is not regsitered')\n res.redirect('/#forgotpass')\n }\n })\n })\n\n app.post('/changepass', (req,res) => {\n let u = req.fields,\n code = u.verificationCode\n if(u.password == u.passwordConfirm) {\n if(!forgotCode[code]) {\n req.flash('verificationError','Verification Code Invalid')\n return res.redirect('/#resetpass') \n } else {\n updateUserPassword(id,p.newPassword)\n delete forgotCode[code]\n res.redirect('/')\n }\n } else {\n req.flash('verificationError','Passwords do not match')\n return res.redirect('/#resetpass')\n }\n })\n\n app.get('/verify/:code', (req,res) => {\n if(!req.params.code) res.redirect('/')\n uid = req.params.code\n verifyUser(uid)\n .then( () => {\n console.log()\n res.redirect('/verified')\n })\n })\n\n app.get('/account', (req, res) => {\n if(req.isAuthenticated()) {\n res.render('account',{\n user: req.user,\n first:req.flash('first'),\n last:req.flash('last'),\n desc:req.flash('desc'),\n gender:req.flash('gender'),\n major:req.flash('major'),\n accountError: req.flash('accountError')\n })\n } else {\n referenceLink[req.ip] = req.url\n res.redirect('/')\n }\n })\n\n app.get('/updateprofile',(req,res) => res.redirect('/account') )\n app.post('/updateprofile', (req, res) => {\n if(req.isAuthenticated()) {\n p = req.fields\n id = req.user.id\n console.log(p)\n refill = function(a) {\n if(!a) a = ''\n req.flash('first',p.first)\n req.flash('last',p.last)\n req.flash('desc',p.description)\n req.flash('gender',p.gender)\n req.flash('major',p.major)\n res.redirect('/account'+ a)\n }\n\n if(bcrypt.compareSync(p.password, req.user.password)) {\n\n if(p.first.trim() == '' || p.last.trim() == '') {\n req.flash('accountError','First or Last name may not be empty')\n if(p.first.trim() == '')\n return refill('#first')\n else return refill('#last')\n }\n\n updateUserName(id,p.first.trim(),p.last.trim())\n updateUserGender(id,p.gender)\n updateUserMajor(id,p.major)\n updateUserInterests(id,p.interests)\n updateProfileDesc(id,p.description)\n\n if(req.files.profile_image.size > 0) {\n if('image/x-png,image/gif,image/jpeg'.includes(req.files.profile_image.type))\n updateProfileImage(id,req.files.profile_image)\n else {\n req.flash('accountError','Incorrect file type for the picture')\n return refill('#profile_image')\n }\n }\n else setTimeout(() => fs.unlinkSync(req.files.profile_image.path), 3000)\n\n if(p.newPassword) {\n if(p.newPassword == )\n updateUserPassword(id,p.newPassword)\n else {\n req.flash('accountError','Passwords don\\'t match')\n return refill('#newPassword')\n }\n }\n res.redirect('/')\n } else {\n accountError: req.flash('accountError',\"Wrong Password\")\n return refill('#password')\n }\n } else {\n referenceLink[req.ip] = req.url\n res.redirect('/')\n }\n })\n \n app.get('/profile', (req,res) => {\n res.redirect(\"/\")\n })\n\n app.get('/department/:did', (req,res) => {\n if(req.isAuthenticated()) {\n getUserCourses( req.user.id )\n .then( (courses) =>\n getDepartment( req.params.did )\n .then( (department) => \n getDepartmentCourses(req.params.did, req.user.id)\n .then( (_courses) => {\n res.render('department',{\n user: req.user,\n department: department,\n courses: courses,\n _courses: _courses\n })\n console.log(_courses)\n req.login(req.user.id,()=>{})\n }\n )))\n }\n })\n\n app.get('/audit', (req,res) => {\n if(req.isAuthenticated()) {\n if (req.user.acc_type == 'admin' || req.user.acc_type == 'mod') {\n delete req.user.acc_type\n getUserCourses(req.user.id)\n .then( courses =>\n getAllPendingPosts()\n .then( (posts) =>\n res.render(\"audit\",{\n user: req.user,\n enabled: true,\n posts: posts,\n courses: courses\n })))\n req.login(req.user.id,()=>{})\n }\n } else {\n referenceLink[req.ip] = req.url\n res.redirect('/')\n }\n })\n\n app.get('/admin', (req,res) => {\n if(req.isAuthenticated()) {\n if (req.user.acc_type == 'admin' || req.user.acc_type == 'mod') {\n getUserCourses()\n .then( (courses) =>\n res.render(\"admin\",{\n user: req.user,\n _courses: courses\n }))\n req.login(req.user.id,()=>{})\n }\n } else {\n referenceLink[req.ip] = req.url\n res.redirect('/')\n }\n })\n\n app.post('/audit/query', (req,res) => {\n q = req.fields.query_textbox\n if(req.isAuthenticated()) {\n if (req.user.acc_type == 'admin') {\n runQuery(q)\n .then( (results) => {\n res.render(\"audit\",{\n user: req.user,\n list: results\n })\n req.login(req.user.id,()=>{})\n })\n }\n else res.send('Unauthorized')\n } else {\n referenceLink[req.ip] = req.url\n res.redirect('/')\n }\n })\n\n app.get('/course/:course_id', (req,res) => {\n course_id = req.params.course_id\n if(req.isAuthenticated()) {\n let course, posts, courses\n getCoursePosts( course_id )\n .then( results => posts = results )\n .then( () => getCourse( course_id )\n .then( results => course = results )\n .then( () => getUserCourses( req.user.id )\n .then( results => courses = results ))\n .then( () => {\n res.render('course', {\n user: req.user,\n course: course,\n posts: posts,\n courses: courses\n })\n req.login(req.user.id,()=>{})\n }))\n } else {\n referenceLink[req.ip] = req.url\n res.redirect('/')\n return\n }\n })\n\n app.get('/profile/:uid', (req,res) => {\n uid = req.params.uid\n if(req.isAuthenticated())\n if(uid == req.user.id) res.redirect('/')\n else res.send(uid)\n })\n\n app.get('/file/:file_id', (req,res) => {\n file_id = req.params.file_id\n if(req.isAuthenticated()) {\n let fileData, path\n getFile(file_id)\n .then( f => {\n path = './temp_uploads/'+Math.round(Math.random()*999999999)\n\n if(f) fs.writeFile(path, f.file_data, (err) => res.download(path,f.file_name) )\n })\n } else {\n referenceLink[req.ip] = req.url\n res.redirect('/')\n return\n }\n })\n\n app.get('/search', (req,res) => {\n if(req.isAuthenticated()) {\n getUserCourses( req.user.id )\n .then( (user_courses) => \n res.render('search-blank',{\n user: req.user,\n courses: user_courses\n })\n )\n } else {\n referenceLink[req.ip] = req.url\n res.redirect('/')\n return\n }\n })\n\n app.post('/search', (req,res) => {\n if(req.isAuthenticated()) {\n if(req.fields.q != undefined) {\n let wordArr = req.fields.q.split(\" \"),\n courseArr = [],\n userCourses = []\n departmentArr = [],\n lastCourseArr = [],\n lastDepartmentArr = []\n wordObjArray = []\n wordArr.forEach( (word, count) => {\n if(word !== ' ') {\n wordObj = {word: word, numResults: 0}\n wordObjArray.push(wordObj)\n }\n searchCourse(word)\n .then( (courses) => {\n wordObjArray[wordObjArray.indexOf(wordObjArray.find((e) => e.word == word ))].numResults += courses.length\n courses.forEach( (course, i) => {\n if(!courseArr.find((c) => c.id == course.id ))\n courseArr.push(course)\n } )\n } )\n .then( () =>\n searchDepartment(word)\n .then( (departments) => {\n wordObjArray[wordObjArray.indexOf(wordObjArray.find((e) => e.word == word ))].numResults += departments.length\n departments.forEach( (department, i) => {\n if(!departmentArr.find((d) => d.id == department.id ))\n departmentArr.push(department)\n } )\n } )\n .then( () => getUserCourses( req.user.id )\n .then( (user_courses) => userCourses = user_courses )\n )\n .then( () => {\n if(count == wordArr.length-1) {\n res.render(\"search\", {\n wordArray: wordObjArray,\n searchString: req.fields.q,\n user: req.user,\n courses: userCourses,\n _courses: courseArr,\n _departments: departmentArr\n })\n req.login(req.user.id,()=>{})\n }\n }))\n })\n }\n } else {\n referenceLink[req.ip] = req.url\n res.redirect('/')\n }\n })\n\n app.get('/profile_image', (req, res) => {\n if(res.headerSent) return res.status(404).end()\n if(req.isAuthenticated()) {\n if(req.user.profile_image) {\n p = __dirname+\"/../temp_uploads/upload_\"+Math.round(Math.random()*999999999)\n return fs.writeFile(path.resolve(p),req.user.profile_image, () => {\n res.sendFile(path.resolve(p))\n })\n } else {\n res.sendFile(path.resolve(__dirname+'/../public/images/'+ ((req.user.gender == 'male')?'m':'w')+'_profile.svg'),{}, () => {\n })\n }\n } else {\n return res.send('unauthorized')\n }\n })\n\n app.get('/profile_image/:uid', (req, res) => {\n if(res.headerSent) return res.status(404).end()\n uid = req.params.uid\n if(req.isAuthenticated()) {\n if(uid === req.user.id) {\n return res.redirect('/profile_image')\n if(req.user.profile_image) {\n p = __dirname+\"/../temp_uploads/upload_\"+Math.round(Math.random()*999999999)\n return fs.writeFile(path.resolve(p),req.user.profile_image, () => {\n res.sendFile(path.resolve(p))\n })\n } else {\n var options = {\n dotfiles: 'deny',\n headers: {\n 'x-timestamp': Date.now(),\n 'x-sent': true\n }\n };\n res.set('Content-Type','image/svg+xml')\n return res.sendFile(path.resolve(__dirname+'/../public/images/'+ ((req.user.gender == 'male')?'m':'w')+'_profile.svg'), options, (err) => {\n console.log(\"File sent\")\n })\n }\n } else {\n getProfilePictureByID(uid)\n .then( (result) => {\n if(result.profile_image) {\n p = __dirname+\"/../temp_uploads/\"+Math.round(Math.random()*999999999)\n return fs.writeFile(path.resolve(p),result.profile_image, () => {\n res.sendFile(path.resolve(p))\n })\n } else {\n return res.sendFile(path.resolve(__dirname+'/../public/images/'+ ((result.gender == 'male')?'m':'w')+'_profile.svg'))\n }\n })\n }\n } else {\n return\n }\n })\n \n app.get('/', (req,res) => {\n if(req.isAuthenticated() && referenceLink[req.ip]) {\n res.redirect(referenceLink[req.ip])\n delete referenceLink[req.ip]\n } else if(req.isAuthenticated()) {\n let courses = [], departments, myPosts = [], interests = [], notifications = [], savedPosts = []\n getUserCourses( req.user.id ).then( results => courses = results )\n .then( () => getUserPosts( req.user.id )\n .then( results => myPosts = results ))\n .then( () => getUserDepartments( req.user.id )\n .then( (depts) => departments = depts ))\n .then( () => getUserSavedPosts( req.user.id )\n .then( results => savedPosts = results ))\n .then(() => getUserNotifications( req.user.id )\n .then( results => notifications = results ))\n .then(() => {\n console.log()\n interests = (req.user.interests == '') ? interests = null : req.user.interests.split(\", \");\n res.render('home', {\n alert: req.flash('alert'),\n user: req.user,\n courses: courses,\n interests: interests,\n departments: departments,\n myPosts: myPosts,\n savedPosts: savedPosts,\n notifications: notifications\n })\n req.login(req.user.id,()=>{})\n })\n } else {\n res.render('auth', {\n firstname: req.flash('firstname'),\n lastname: req.flash('lastname'),\n email: req.flash('email'),\n loginError: req.flash('loginError'),\n registerError: req.flash('registerError'),\n forgotError: req.flash('forgotError'),\n verificationError: req.flash('verificationError')\n })\n }\n })\n\n //post\n app.get('/login',(req,res) => res.redirect('/') )\n app.post('/login', (req, res) => {\n let email = req.fields.email,\n password = req.fields.password\n login(email,password)\n .then( result => {\n if(result) {\n switch(result.acc_status) {\n case 'banned':\n req.flash('loginError','Your account is banned. You have disobeyed the terms of service.')\n res.redirect('/')\n break\n case 'unverified':\n req.flash('loginError','Your account is unverified. Please check your email!')\n res.redirect('/')\n break\n default:\n req.login(result.id, () => res.redirect('/')) \n }\n } else {\n req.flash('loginError','Incorrect login information')\n res.redirect('/')\n }\n })\n })\n\n app.get('/thankyou', (req,res) => res.redirect('/#thankyou') )\n app.get('/verified', (req,res) => res.redirect('/#verified') )\n app.get('/forgot', (req,res) => res.redirect('/#forgotpass') )\n app.get('/resetpass', (req,res) => res.redirect('/#newpass') )\n\n app.get('/register', (req,res) => res.redirect('/#register') )\n app.post('/register', (req,res) => {\n let firstname = req.fields.first_name || '',\n lastname = req.fields.last_name || '',\n email = req.fields.email || '',\n password = \n\n refill = function() {\n req.flash('firstname',firstname)\n req.flash('lastname',lastname)\n req.flash('email',email)\n res.redirect('/#register')\n }\n\n if(!req.fields.checkbox) {\n req.flash('registerError','Please agree to the terms of service')\n return refill()\n }\n\n if(!email.includes('@students.ecu.edu')) {\n req.flash('registerError','Please use your ECU student email!')\n return refill()\n }\n\n if(password != req.fields.password_confirm) {\n req.flash('registerError','Your passwords do not match')\n return refill()\n }\n \n if(firstname != \"\" || lastname != \"\" || email != \"\" || password != \"\") {\n register(firstname, lastname, email, password)\n .then((id) => {\n if(id) {\n sendVerificationEmail(email)\n res.redirect('/thankyou')\n } else {\n req.flash('registerError',\"Your account could not be created!\")\n return refill()\n }\n })\n .catch( err => {\n if(err.errno === 1062) {\n req.flash('registerError',\"Someone is already regsitered with this email\")\n return refill()\n }\n req.flash('registerError',JSON.stringify(err))\n return refill()\n })\n } else {\n req.flash('registerError','Missing information')\n return refill()\n }\n })\n\n app.get('/post',(req,res) => res.redirect('/') )\n app.post('/post', (req, res) => {\n if(req.isAuthenticated()) {\n let fileArr = []\n if(req.files.fileAttachments.length)\n fileArr = req.files.fileAttachments\n else fileArr = [req.files.fileAttachments]\n numFiles = fileArr.length\n\n let FileTooBig = false\n fileArr.forEach( (file,i) => {\n if(file.size == 0 || file.name == '')\n setTimeout(() => fs.unlinkSync(fileArr.splice(i,1)[0].path), 3000)\n if(file.size > 10000000)\n stop = true\n } )\n\n if(FileTooBig) {\n req.flash('error','The file was too big (10M max)')\n res.redirect('/')\n } else if(fileArr.length > 5) {\n req.flash('error','Too many files (5 files max)')\n res.redirect('/')\n } else\n createPost(req.user.id,req.fields.course,req.fields.post_text,fileArr)\n .then(() => res.redirect('/'))\n } else {\n referenceLink = req.url\n res.redirect('/')\n }\n })\n\n app.get('/infolog', (req,res) => {\n if(req.isAuthenticated() && (req.user.acc_type == 'admin' || req.user.acc_type == 'mod'))\n data = JSON.stringify(req.user,null,4)\n else data = \"You are not authorized to view this data\"\n res.set('Content-Type', 'application/json')\n res.send(data)\n })\n \n app.get('/logout', (req, res) => {\n if(req.isAuthenticated())\n req.logout()\n res.redirect('/')\n })\n\n // Passport Session Serialization\n\n pp.serializeUser((user, done) => done(null, user) )\n \n pp.deserializeUser((id, done) => getUserByID(id).then( result => done(null, result) ).catch( err => console.log(err) ))\n}", "dangerousExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/dan', function (req, res) {\n5. const url = req.body.profile_url;\n6. try{\n7. res.redirect(url);\n8. }catch (e) {\n9. return res.status(500).send(\"ERROR\");\n10. }\n11. });\n12. \n13. module.exports = router;\nLine 7: A string variable URL of an unvalidated external input is used to connect.", "safeExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/safe', function (req, res) {\n5. const url = req.body.profile_url;\n6. const white_list = [\"https://www.safeurl.com\", \"https://www.verified.com\"];\n7. if (white_list.indexOf(url) < 0) {\n8. return res.status(500).send(\"url not allowed\");\n9. } else {\n10. try {\n11. res.redirect(url);\n12. } catch (e) {\n13. return res.status(500).send(\"ERROR\");\n14. }\n15. }\n16. });\n17. \n18. module.exports = router;\nLine 7-9: Validate external inputs through a filter function.", "contexts": [{"lineNo": 505, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "505"}}, {"lineNo": 506, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "referenceLink"}}, {"lineNo": 506, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "redirect"}}]}} {"id": "b65aa26125daa2c62d66956e4ae71a01bbaccca90eb4ef299948c019c6a980c3", "license": {"spdx": ["Unlicense"], "repo": "biscuitapps/shopify-oauth", "path": "index.js", "repo_head_hexsha": "b4b45493238829fbc350466e881e36b4efdfd994", "stack_hexsha": "b7be9156068057f9ee47f08151bc180cb95f0e99", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Redirection to untrusted site", "issueDescriptionEn": "The Redirection to untrusted site checker finds instances of redirecting to a URL generated with an unvalidated external input.\nAlthough connecting to a client-provided URL is often believed to be safe, an attacker can modify the request and redirect the user to a malicious site.\nMaintain a whitelist of external site URLs and domains allowed for redirection, which needs to be checked when a user input is passed as a redirect URL.", "issueLineNumber": 24, "entireCode": "const crypto = require('crypto');\nconst cookie = require('cookie');\nconst nonce = require('nonce')();\nconst querystring = require('querystring');\nconst request = require('request-promise');\nconst express = require('express')\nconst router = express.Router()\n\nmodule.exports = (config, callback) => {\n\n const {forwardingAddress, apiKey, apiSecret, scopes} = config;\n\n router.get('/shopify', (req, res) => {\n const shop = req.query.shop;\n if (shop) {\n const state = nonce();\n const redirectUri = `${forwardingAddress}/shopify/callback`;\n const installUrl =\n `https://${shop}/admin/oauth/authorize?client_id=${apiKey}` +\n `&scope=${scopes}&state=${state}&grant_options[]=per-user` +\n `&redirect_uri=${redirectUri}`;\n\n res.cookie('state', state);\n res.redirect(installUrl);\n } else {\n return res.status(400).send('Missing shop parameter. Please add ?shop=your-development-shop.myshopify.com to your request');\n }\n });\n\n router.get('/shopify/callback', (req, res) => {\n\n const { shop, hmac, code, state } = req.query;\n const stateCookie = cookie.parse(req.headers.cookie).state;\n\n if (state !== stateCookie) {\n return res.status(403).send('Request origin cannot be verified');\n }\n\n if (shop && hmac && code) {\n const map = Object.assign({}, req.query);\n delete map['signature'];\n delete map['hmac'];\n const message = querystring.stringify(map);\n const providedHmac = Buffer.from(hmac, 'utf-8');\n const generatedHash = Buffer.from(\n crypto\n .createHmac('sha256', apiSecret)\n .update(message)\n .digest('hex'),\n 'utf-8'\n );\n let hashEquals = false;\n try {\n hashEquals = crypto.timingSafeEqual(generatedHash, providedHmac)\n } catch (e) {\n hashEquals = false;\n };\n\n if (!hashEquals) {\n return res.status(400).send('HMAC validation failed');\n }\n\n const accessTokenRequestUrl = `https://${shop}/admin/oauth/access_token`;\n const accessTokenPayload = {\n client_id: apiKey,\n client_secret: apiSecret,\n code,\n };\n\n request.post(accessTokenRequestUrl, { json: accessTokenPayload })\n .then((accessTokenResponse) => {\n callback(shop, accessTokenResponse, req, res);\n res.redirect('/');\n })\n .catch((error) => {\n console.log(error);\n res.status(error.statusCode).send(error.error_description);\n });\n\n } else {\n res.status(400).send('Required parameters missing');\n }\n });\n\n return router;\n}", "dangerousExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/dan', function (req, res) {\n5. const url = req.body.profile_url;\n6. try{\n7. res.redirect(url);\n8. }catch (e) {\n9. return res.status(500).send(\"ERROR\");\n10. }\n11. });\n12. \n13. module.exports = router;\nLine 7: A string variable URL of an unvalidated external input is used to connect.", "safeExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/safe', function (req, res) {\n5. const url = req.body.profile_url;\n6. const white_list = [\"https://www.safeurl.com\", \"https://www.verified.com\"];\n7. if (white_list.indexOf(url) < 0) {\n8. return res.status(500).send(\"url not allowed\");\n9. } else {\n10. try {\n11. res.redirect(url);\n12. } catch (e) {\n13. return res.status(500).send(\"ERROR\");\n14. }\n15. }\n16. });\n17. \n18. module.exports = router;\nLine 7-9: Validate external inputs through a filter function.", "contexts": [{"lineNo": 14, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "req"}}, {"lineNo": 15, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "15"}}, {"lineNo": 18, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 24, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "redirect"}}]}} {"id": "59618604ce55c06e7b8a94d1b71a41962c8d0a323ecd136403fc94d92ffc9ffa", "license": {"spdx": ["W3C"], "repo": "howard-e/aria-at-app", "path": "server/tests/util/mock-github-server.js", "repo_head_hexsha": "6369bf36c30c91e8097ca141c84fb019a8e30e60", "stack_hexsha": "c7ec130a9090c1f5e30024e872ba485b3304da19", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Redirection to untrusted site", "issueDescriptionEn": "The Redirection to untrusted site checker finds instances of redirecting to a URL generated with an unvalidated external input.\nAlthough connecting to a client-provided URL is often believed to be safe, an attacker can modify the request and redirect the user to a malicious site.\nMaintain a whitelist of external site URLs and domains allowed for redirection, which needs to be checked when a user input is passed as a redirect URL.", "issueLineNumber": 66, "entireCode": "const express = require('express');\nconst randomStringGenerator = require('./random-character-generator');\nconst { ApolloServer, gql } = require('apollo-server-express');\nconst { GracefulShutdownManager } = require('@moebius/http-graceful-shutdown');\n\nconst { GITHUB_TEAM_ADMIN } = process.env;\n\nconst setUpMockGithubServer = async () => {\n let nextGithubUsername;\n let nextIsOnAdminTeam;\n\n const typeDefs = gql`\n type Node {\n name: String\n }\n\n type Edge {\n node: Node\n }\n\n type Connection {\n edges: [Edge]\n }\n\n type Viewer {\n login: String\n }\n\n type Organization {\n teams(userLogins: String, query: String, first: Int): Connection\n }\n\n type Query {\n viewer: Viewer\n organization(login: String): Organization\n }\n `;\n\n const resolvers = {\n Query: {\n viewer: () => {\n return { login: nextGithubUsername };\n },\n organization: () => {\n return {};\n }\n },\n Organization: {\n teams: () => {\n const teamName = nextIsOnAdminTeam ? GITHUB_TEAM_ADMIN : null;\n return { edges: [{ node: { name: teamName } }] };\n }\n }\n };\n\n const apolloServer = new ApolloServer({ typeDefs, resolvers });\n\n const expressApp = express();\n\n await apolloServer.start();\n apolloServer.applyMiddleware({ app: expressApp });\n\n expressApp.get('/login/oauth/authorize', (req, res) => {\n const code = randomStringGenerator();\n const { state } = req.query;\n res.status(303).redirect(\n `${process.env.API_SERVER}/api/auth/authorize` +\n `?code=${code}&state=${state}`\n );\n });\n\n expressApp.post('/login/oauth/access_token', (req, res) => {\n const accessToken = randomStringGenerator();\n res.header('access-control-allow-origin', '*').send({\n access_token: accessToken\n });\n });\n\n let shutdownManager;\n await new Promise(resolve => {\n const listener = expressApp.listen('4466', resolve);\n shutdownManager = new GracefulShutdownManager(listener);\n });\n\n const nextLogin = ({ githubUsername, isOnAdminTeam }) => {\n nextGithubUsername = githubUsername;\n nextIsOnAdminTeam = isOnAdminTeam;\n };\n\n const tearDown = async () => {\n await new Promise(resolve => {\n shutdownManager.terminate(resolve);\n });\n await apolloServer.stop();\n };\n\n return {\n nextLogin,\n tearDown\n };\n};\n\nmodule.exports = setUpMockGithubServer;", "dangerousExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/dan', function (req, res) {\n5. const url = req.body.profile_url;\n6. try{\n7. res.redirect(url);\n8. }catch (e) {\n9. return res.status(500).send(\"ERROR\");\n10. }\n11. });\n12. \n13. module.exports = router;\nLine 7: A string variable URL of an unvalidated external input is used to connect.", "safeExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/safe', function (req, res) {\n5. const url = req.body.profile_url;\n6. const white_list = [\"https://www.safeurl.com\", \"https://www.verified.com\"];\n7. if (white_list.indexOf(url) < 0) {\n8. return res.status(500).send(\"url not allowed\");\n9. } else {\n10. try {\n11. res.redirect(url);\n12. } catch (e) {\n13. return res.status(500).send(\"ERROR\");\n14. }\n15. }\n16. });\n17. \n18. module.exports = router;\nLine 7-9: Validate external inputs through a filter function.", "contexts": [{"lineNo": 66, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "redirect"}}, {"lineNo": 68, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "state"}}]}} {"id": "f92cc6a0265a4cf2e86273a6afdf7d27dacc0c507cc8c6f272a31098f24fd8b1", "license": {"spdx": ["MIT"], "repo": "MikyeongKim/CapstoneProject", "path": "routes/service/myclassService.js", "repo_head_hexsha": "12dac7a692e6ee5710d84992e82b6f0e68637eec", "stack_hexsha": "251b171b4354513274de88a72a64c41f05fbde0a", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Redirection to untrusted site", "issueDescriptionEn": "The Redirection to untrusted site checker finds instances of redirecting to a URL generated with an unvalidated external input.\nAlthough connecting to a client-provided URL is often believed to be safe, an attacker can modify the request and redirect the user to a malicious site.\nMaintain a whitelist of external site URLs and domains allowed for redirection, which needs to be checked when a user input is passed as a redirect URL.", "issueLineNumber": 25, "entireCode": "const myclassDAO = require('../Repository/Repo_myclass');\nconst userDAO = require('../Repository/Repo_user');\nconst submitDAO = require('../Repository/Repo_task_submit');\nconst editFunc = require('../func/editfunc');\n\nconst STUDENT = 1;\n\ncreateNoticeForm = (req, res, next) => {\n const subject_no = req.params.id;\n\n if (req.session.userinfo[1] === STUDENT) {\n return res.redirect(`/myclass/${subject_no}/notice/`);\n }\n return res.render('professor/2notice/write', { subject_no: subject_no });\n};\n\ncreateQnaForm = (req, res, next) => {\n const subject_no = req.params.id;\n return res.render('professor/3qna/write', { subject_no: subject_no });\n};\n\ncreatePptForm = (req, res) => {\n const subject_no = req.params.id;\n if (req.session.userinfo[1] === STUDENT) {\n return res.redirect(`/myclass/${subject_no}/ppt/`);\n }\n return res.render('professor/4ppt/write', { subject_no: subject_no });\n};\n\ncreateTaskForm = (req, res) => {\n const subject_no = req.params.id;\n\n if (req.session.userinfo[1] === STUDENT) {\n return res.redirect(`/myclass/${subject_no}/task/`);\n }\n return res.render('professor/5task/write', { subject_no: subject_no });\n};\n\n// notice 게시글찾기\nlistAllNotice = async (req, res, next) => {\n const subject_no = req.params.id;\n const userGrade = req.session.userinfo[1];\n let result;\n try {\n result = await myclassDAO.findAllNotice(subject_no);\n } catch (e) {\n return res.send(`listAllNotice Error`);\n }\n\n const path = userGrade === STUDENT ? 'student/2notice/index' : 'professor/2notice/index';\n return res.render(path, { subject_no: subject_no, board: result });\n};\n\nlistAllQna = async (req, res, next) => {\n const subject_no = req.params.id;\n let result;\n try {\n result = await myclassDAO.findAllQna(subject_no);\n } catch (e) {\n return res.send('listAllNotice Error');\n }\n\n let path = req.session.userinfo[1] === STUDENT ? 'student/3qna/index' : 'professor/3qna/index';\n\n return res.render(path, {\n subject_no,\n board: result\n });\n};\n\nlistAllPpt = async (req, res, next) => {\n const subject_no = req.params.id;\n let result;\n try {\n result = await myclassDAO.findAllPpt(subject_no);\n } catch (e) {\n return res.send(`listAllNotice Error`);\n }\n\n const path = req.session.userinfo[1] === STUDENT ? 'student/4ppt/index' : 'professor/4ppt/index';\n\n return res.render(path, {\n subject_no: subject_no,\n board: result\n });\n};\n\nlistAllTask = async (req, res, next) => {\n const subjectNo = req.params.id;\n let result;\n try {\n result = await myclassDAO.findAllTask(subjectNo);\n } catch (e) {\n return res.send('listAlltask Error');\n }\n\n const path =\n req.session.userinfo[1] === STUDENT ? 'student/5task/index' : 'professor/5task/index';\n\n return res.render(path, {\n subject_no: subjectNo,\n board: result\n });\n};\n\nreadNotice = async (req, res, next) => {\n const subjectNo = req.params.id;\n const blogNo = req.params.no;\n let result;\n try {\n result = await myclassDAO.readNotice(subjectNo, blogNo);\n } catch (e) {\n return res.send('readNotice error');\n }\n let path =\n req.session.userinfo[1] === STUDENT ? 'student/2notice/read' : 'professor/2notice/read';\n\n return res.render(path, {\n subject_no: subjectNo,\n board: result\n });\n};\n\nreadQna = async (req, res, next) => {\n const subject_no = req.params.id;\n const blog_no = req.params.no;\n let result;\n try {\n result = await myclassDAO.readQna(subject_no, blog_no);\n } catch (e) {\n return res.send('readQna error');\n }\n const path = req.session.userinfo[1] === STUDENT ? 'student/3qna/read' : 'professor/3qna/read';\n\n return res.render(path, {\n subject_no: subject_no,\n board: result\n });\n};\n\nreadPpt = async (req, res, next) => {\n const subject_no = req.params.id;\n const blog_no = req.params.no;\n\n try {\n result = await myclassDAO.readPpt(subject_no, blog_no);\n } catch (e) {\n return res.send(`readPpt readPpt error \\n ${err}`);\n }\n\n const path = req.session.userinfo[1] === STUDENT ? 'student/4ppt/read' : 'professor/4ppt/read';\n\n return res.render(path, {\n subject_no: subject_no,\n board: result\n });\n};\n\nreadTask = async (req, res, next) => {\n const subjectNo = req.params.id;\n const blogNo = req.params.no;\n const userNo = req.session.userinfo[0];\n let blogResult, taskResult;\n let isStudent = req.session.userinfo[1] === STUDENT;\n try {\n [blogResult, taskResult] = isStudent\n ? await myclassDAO.readTaskStu(userNo, blogNo)\n : await myclassDAO.readTaskPro(blogNo);\n if (taskResult === null) {\n taskResult = await myclassDAO.readTaskFindOne(userNo, blogNo);\n }\n } catch (e) {\n return res.status(500).send('readTask readTaskStu error');\n }\n\n if (isStudent) {\n let isSubmit = taskResult === null ? false : true;\n return res.render('student/5task/read', {\n subject_no: subjectNo,\n board: blogResult,\n task: taskResult,\n isSubmit: isSubmit\n });\n }\n\n return res.render('professor/5task/read', {\n subject_no: subjectNo,\n board: blogResult,\n task: taskResult\n });\n};\n\nfindClass = async (req, res, next) => {\n const userGrade = req.session.userinfo[1];\n const userNo = req.session.userinfo[0];\n let result;\n try {\n result =\n userGrade === STUDENT\n ? await myclassDAO.findClassByStu(userNo)\n : await myclassDAO.findClassByPro(userNo);\n } catch (e) {\n return res.send('Myclass error 이것좀 작업해 종화야 에러처리 등록해라.!');\n }\n\n return userGrade === STUDENT\n ? res.render('student/myclass', { myclass: result[0].subjects })\n : res.render('professor/myclass', { myclass: result });\n};\n\nshowPlan = async (req, res, next) => {\n const subject_no = req.params.id;\n const userGrade = req.session.userinfo[1];\n const path = userGrade === STUDENT ? 'student' : 'professor';\n let result;\n try {\n result = await myclassDAO.findPlanByAll(subject_no);\n } catch (e) {\n return res.send('Myclass error 이것좀 작업해 종화야 에러처리 등록해라.!');\n }\n\n return res.render(`${path}/blog_plan`, {\n subject_no: result[0].subject_no,\n plan: result[0]\n });\n};\n\ncreateNotice = async (req, res, next) => {\n let subject_no = req.params.id;\n req.body.subject_no = subject_no;\n req.body.user_no = req.session.userinfo[0];\n\n if (req.session.userinfo[1] === STUDENT) {\n return res.status(403).send('forbidden');\n }\n\n let result;\n try {\n result = await userDAO.findUserNameByNo(req.body.user_no);\n } catch (e) {\n return res.status(500).send('createNotice findUser error');\n }\n\n if (!result) return res.status(404).send('404');\n\n try {\n await myclassDAO.createNotice(req.body, result.user_name);\n } catch (e) {\n return res.status(500).send('createNotice error');\n }\n return res.redirect(`/myclass/${subject_no}/notice`);\n};\n\ncreateQna = async (req, res, next) => {\n let subject_no = req.params.id;\n req.body.subject_no = subject_no;\n req.body.user_no = req.session.userinfo[0];\n let result;\n try {\n result = await userDAO.findUserNameByNo(req.body.user_no);\n } catch (e) {\n return res.status(500).send('createQna findUserNameByNo error');\n }\n\n try {\n await myclassDAO.createQna(req.body, result.user_name);\n } catch (e) {\n return res.status(500).send('createQna error');\n }\n\n return res.redirect(`/myclass/${subject_no}/qna`);\n};\n\ncreatePpt = async (req, res, next) => {\n let subject_no = req.params.id;\n req.body.subject_no = subject_no;\n req.body.user_no = req.session.userinfo[0];\n let result;\n\n try {\n result = await userDAO.findUserNameByNo(req.body.user_no);\n } catch (e) {\n return res.status(500).send('createPpt findUserNameByNo error');\n }\n\n try {\n await myclassDAO.createPpt(req.body, result.user_name);\n } catch (e) {\n return res.status(500).send('createPpt createPpt error');\n }\n\n return res.redirect(`/myclass/${subject_no}/ppt`);\n};\n\nreadCode = async (req, res, next) => {\n const subjectNo = req.params.subject;\n const blogNo = req.params.blog_no;\n const lang = req.params.lang;\n const filename = req.params.filename;\n const submitNo = req.params.submit_no;\n let filePath = `${__dirname}/../../uploads/submit/${filename}`;\n let result;\n try {\n let userInfo = await submitDAO.findUserBySubNo(submitNo);\n let code = await editFunc.readCode(filePath);\n result = {\n userInfo,\n code,\n lang,\n readcode: false,\n url: `/myclass/${subjectNo}/task/${blogNo}`\n };\n } catch (e) {\n return res.status(500).send('readCode error');\n }\n\n return res.render('professor/editor', { info: result });\n};\n\ntaskSubmit = (req, res) => {\n const subject_no = req.params.id;\n const blog_no = req.params.no;\n\n return res.render('student/5task/task_write');\n};\n\ntaskSubmit2 = async (req, res, next) => {\n const subjectNo = req.params.id;\n const blogNo = req.params.no;\n req.body.user_no = req.session.userinfo[0];\n let extension;\n\n if (req.file) {\n let fileName = req.file.originalname;\n let pathFileName = fileName.lastIndexOf('.') + 1; //확장자 제외한 경로+파일명\n extension = fileName.substr(pathFileName, fileName.length).toLowerCase(); //확장자명\n }\n\n try {\n req.file\n ? await myclassDAO.taskSubmitFile(req.body, blogNo, req.file, extension)\n : await myclassDAO.taskSubmit(req.body, blogNo);\n } catch (e) {\n return res.status(500).send('taskSubmit2 taskSubmit error ');\n }\n\n return res.redirect(`/myclass/${subjectNo}/task/${blogNo}`);\n};\n\ncreateTask = async (req, res, next) => {\n let subject_no = req.params.id;\n req.body.subject_no = subject_no;\n req.body.user_no = req.session.userinfo[0];\n\n let submit_period = `${req.body.yymmdd} ${req.body.hhmm}`;\n let time = new Date(submit_period);\n let time_sec = time.getSeconds();\n let result;\n\n try {\n result = await userDAO.findUserNameByNo(req.body.user_no);\n } catch (e) {\n return res.status(500).send('createFileTask findUserNameByNo error');\n }\n\n if (!result) return res.status(400).send('400 bad Request');\n\n try {\n req.file\n ? await myclassDAO.createFileTask(req.body, result.user_name, time, time_sec, req.file)\n : await myclassDAO.createTask(req.body, result.user_name, time, time_sec);\n } catch (e) {\n console.log(e);\n return res.status(500).send('createFileTask createFileTask error');\n }\n\n return res.redirect(`/myclass/${subject_no}/task`);\n};\n\ndelTaskSubmit = async (req, res, next) => {\n const subject_no = req.params.id;\n const submit_no = req.params.submit_no;\n const blog_no = req.params.blog_no;\n const user_no = req.session.userinfo[0];\n\n try {\n await myclassDAO.delTaskSubmit(submit_no);\n } catch (e) {\n return res.status(500).send('delTaskSubmit error');\n }\n return res.redirect(`/myclass/${subject_no}/task/${blog_no}`);\n};\n\nmodule.exports = {\n createNoticeForm,\n createQnaForm,\n createPptForm,\n createTaskForm,\n listAllNotice,\n listAllQna,\n listAllPpt,\n listAllTask,\n findClass,\n showPlan,\n createNotice,\n createQna,\n createPpt,\n readNotice,\n readQna,\n readPpt,\n readCode,\n readTask,\n taskSubmit,\n createTask,\n taskSubmit2,\n delTaskSubmit\n};", "dangerousExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/dan', function (req, res) {\n5. const url = req.body.profile_url;\n6. try{\n7. res.redirect(url);\n8. }catch (e) {\n9. return res.status(500).send(\"ERROR\");\n10. }\n11. });\n12. \n13. module.exports = router;\nLine 7: A string variable URL of an unvalidated external input is used to connect.", "safeExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/safe', function (req, res) {\n5. const url = req.body.profile_url;\n6. const white_list = [\"https://www.safeurl.com\", \"https://www.verified.com\"];\n7. if (white_list.indexOf(url) < 0) {\n8. return res.status(500).send(\"url not allowed\");\n9. } else {\n10. try {\n11. res.redirect(url);\n12. } catch (e) {\n13. return res.status(500).send(\"ERROR\");\n14. }\n15. }\n16. });\n17. \n18. module.exports = router;\nLine 7-9: Validate external inputs through a filter function.", "contexts": [{"lineNo": 23, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "req"}}, {"lineNo": 23, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 24, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "24"}}, {"lineNo": 25, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "redirect"}}]}} {"id": "b4e875bbae3e336ba95e3c09907a54081857c29f81f2c6c85f6b422844ba4492", "license": {"spdx": ["BSD-3-Clause"], "repo": "TheAdamBC/AdamBC", "path": "server.js", "repo_head_hexsha": "e854a64c19442e24a50e4d65ce2f2e8f6ea46f4c", "stack_hexsha": "c6a6fb9fd2ebdd789b63d7678d1e6e53e7030c69", "match": "repo_path"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Redirection to untrusted site", "issueDescriptionEn": "The Redirection to untrusted site checker finds instances of redirecting to a URL generated with an unvalidated external input.\nAlthough connecting to a client-provided URL is often believed to be safe, an attacker can modify the request and redirect the user to a malicious site.\nMaintain a whitelist of external site URLs and domains allowed for redirection, which needs to be checked when a user input is passed as a redirect URL.", "issueLineNumber": 214, "entireCode": "/**\n * Adam BC APIs:\n * Imports the neccessary configuration modules.\n * Contains the routing APIs, including the apis to start and stop the computer.\n * Manages ENV Process file.\n * \n */\n\n// Import neccessary node modules\nconst express = require('express'); // Server middleware\nconst path = require('path'); // Directory configurations\nconst fs = require('fs');\nconst cookieParser = require(\"cookie-parser\");\nconst io = require('socket.io-client');\n//const jwt = require('jsonwebtoken');\n\nconst {AdamOS} = require('./cpu/AdamOS');\nconst {setEnvValue} = require('./helpers/env_eol')\nconst {save} = require('./helpers/appwrite/appwrite')\nconst apiResponse = require(\"./helpers/apiResponse\");\n//const {writeData, readData} = require('./helpers/save');\nconst {parameterFunctions} = require('./app/config/parameterFunctions');\nconst {v4:uuidv4} = require('uuid');\nrequire(\"dotenv\").config(); // Environment event handler\n\n// Import queuing module bull\nconst Queue = require('bull');\n\n// Custom mode Worker Queue\nconst customWorker = new Queue('custom_worker', {\n limiter: {\n max: 5000, // Limit the queue to a maximum of 5000 jobs per 10 seconds\n duration: 10000\n },\n redis: {\n host: \"127.0.0.1\",\n port: \"6379\",\n password: \"\"\n } \n});\n\n// Peer mode Worker Queue\nconst peerWorker = new Queue('peer_worker', {\n limiter: {\n max: 5000, // Limit the queue to a maximum of 5000 jobs per 10 seconds\n duration: 10000\n },\n redis: {\n host: \"127.0.0.1\",\n port: \"6379\",\n password: \"\"\n } \n});\n\nvar onlineUsers = []; // Users Online\nvar onlinePeers = []; // Peers Online\n\n// Express configurations\nconst app = express()\nconst port = 6550 // Testing Port\n\napp.use(express.static(path.join(__dirname, '/public'))); // configure express to use 'public' folder\napp.set('views', __dirname + '/views'); // set express to look in this folder to render our views\napp.set('view engine', 'ejs'); // configure template engine\n// parse application/x-www-form-urlencoded\napp.use(express.urlencoded({ extended: false }));\napp.use(express.json());\napp.use(cookieParser());\napp.use(function(req, res, next) {\n res.header(\"Access-Control-Allow-Origin\", \"*\");\n res.header(\"Access-Control-Allow-Headers\", \"Origin, X-Requested-With, Content-Type, Accept\");\n next();\n});\n\n// Launch Adam BC\napp.get('/', (req, res) => {\n res.sendFile(path.join(__dirname + '/views/temp/index.html'));\n})\n\n// Adam BC settings\napp.get('/settings', (req, res) => {\n res.sendFile(path.join(__dirname + '/views/temp/settings.html'));\n})\n\n// Start Processing\napp.get('/start', AdamOS, (req, res) => {\n\n // Capture any parameters passed\n var tid = req.query.tid;\n\n // Send notifications on computation progress\n if(!tid){ \n\n // Task processing started\n require('./app').io.emit('processing-progress',`Adam BC has started ..!`);\n\n } else {\n\n // Task completed\n require('./app').io.emit('processing-progress',`Task ${tid} completed..!`);\n\n }\n\n // Read configurations from file\n fs.readFile(__dirname + '/app/config/' + 'config.json', 'utf8', (err, data) => {\n \n // Parse data to JSON \n let sts = JSON.parse(data);\n \n // Check if task is actively running \n if(sts.running==false){\n\n // Calculate duration\n let today = new Date();\n let start = new Date(`${sts.TimeStarted}`);\n let dur = parseInt(Math.abs(today.getTime()-start.getTime()) / (1000 * 60) % 60);\n let tn = parseInt(sts.tDuration-dur) // calculate time left in minutes\n\n // Capture starting time\n require('./app').io.emit('processing-duration', tn);\n \n }\n \n });\n\n // Processing completed\n res.status(200).send('Processing started ..!')\n})\n\n// Stop processing\napp.get('/stop', (req, res) => {\n res.status(200).send('Processing Terminated ..!')\n})\n\n// Task Completed\napp.get('/done', (req, res) => {\n res.status(200).send('Task has been completed ..!')\n})\n\n// API - JSON Configurations\napp.get(\"/configs\", async (req, res) => {\n\n // Read configurations from file\n let cdata = fs.readFileSync(__dirname + '/app/config/' + 'config.json', 'utf8');\n\n // Read processing logs\n let lgdata = fs.readFileSync(__dirname + '/app/config/' + 'log.txt', 'utf8');\n\n // Parse data to JSON\n let setgs = JSON.parse(cdata);\n let lcg = JSON.parse(lgdata);\n\n // Capture new 'uParams' computing parameters\n let newParams = await parameterFunctions(setgs,lcg); \n\n // Check if task is actively running\n if(setgs.running==false){\n\n // If task is not actively running, post data from 'config.json' configuration file\n // Post configurations as serializable API\n\n // Add new 'uParams' parameters to computing configuration\n setgs.uParams.push(newParams);\n\n res.status(200).end(JSON.stringify(setgs));\n\n // If task is actively running\n } else if (setgs.running==true){\n\n // If task is actively running, post data from 'log.txt' configuration file\n // Read configurations from file\n let ldata = fs.readFileSync(__dirname + '/app/config/' + 'log.txt', 'utf8');\n\n let clg = JSON.parse(ldata);\n\n // Add new 'uParams' parameters to computing configuration\n clg.uParams.push(newParams);\n \n // Post processing API\n res.status(200).end(JSON.stringify(clg));\n \n // If task has been completed, redirect to task completed page.\n } else if (setgs.running==\"done\"){\n\n res.status(200).end('{\"running\":\"done\"}');\n\n }\n\n});\n\n// Receive and store data sent from worker process\napp.post(\"/receive\", (req, res) => {\n\n // Add new process to custom queue worker\n customWorker.add({jobData:req.body});\n\n // Capture data sent\n const {data} = req.body;\n let json = JSON.parse(data);\n\n // If task still running, re-trigger \"start\" \n // Pass ID of previous task for notification of completion\n var tid = encodeURIComponent(json[\"configs\"].TaskID);\n\n // Check if processing is complete\n // Check if processing is done, if so, change 'config.json' 'running' parameter from 'true' to 'done'\n if((Number(json[\"logs\"].iPartition+json[\"logs\"].tPartition+json[\"logs\"].xPartition)>Number(json[\"logs\"].oPartition)) && process.env.PEER_MODE=='NO') {\n\n res.redirect('/done');\n\n } else {\n\n //Re-trigger task\n res.redirect('/start?tid='+tid);\n\n }\n\n});\n\n// Join peers\napp.get('/peers/join', (req, res) => {\n\n // Capture request hostname\n var hostIP = req.hostname;\n\n // Create new peer\n var newPeer = {\n hostIP:hostIP,\n location:\"Earth\",\n username:process.env.NETWORK_USERNAME,\n peer_id:process.env.WORKER_ID,\n peer_pwd:,\n contact: process.env.WORKER_CONTACT,\n joined: new Date(),\n verified:false\n };\n\n // Read peer configurations from file\n fs.readFile(__dirname + '/peers/config/' + 'store.json', 'utf8', (err, data) => {\n\n // Parse data to JSON \n let str = JSON.parse(data);\n\n // Check if peer is full\n // Not 500 or more\n if(str[0].peers.length<500){\n\n // Store new peer\n str[0].peers.push(newPeer);\n\n // Store results into file\n fs.writeFile(__dirname + '/peers/config/' + 'store.json', JSON.stringify(str), (err) => {\n\n if(err) console.log(err);\n\n // Processing completed\n res.status(200).send('New peer member added ..!');\n\n }); \n\n } else {\n\n // Admin is full\n res.status(200).send('Peer administration is not admiting new peers ..!');\n\n }\n\n });\n\n});\n\n// Join peers as administrator\napp.get('/peers/join/admin', (req, res) => {\n\n // Capture request hostname\n var hostIP = req.hostname;\n\n // Create new peer\n var newPeer = {\n hostIP:hostIP,\n location:\"Earth\",\n username:process.env.NETWORK_USERNAME,\n peer_id:process.env.WORKER_ID,\n peer_pwd:,\n contact: process.env.WORKER_CONTACT,\n joined: new Date(),\n verified:false\n };\n\n // Read peer configurations from file\n fs.readFile(__dirname + '/peers/config/' + 'store.json', 'utf8', (err, data) => {\n\n // Parse data to JSON \n let str = JSON.parse(data);\n \n // Check if admin is full\n // Not 10 or more\n if(str[0].admin.length<10){\n \n // Store new peer\n str[0].admin.push(newPeer);\n\n // Store results into file\n fs.writeFile(__dirname + '/peers/config/' + 'store.json', JSON.stringify(str), (err) => {\n\n if(err) console.log(err);\n\n // Processing completed\n res.status(200).send('New peer administrator added ..!');\n\n });\n\n } else {\n\n // Admin is full\n res.status(200).send('Peer administration is not admiting new members ..!');\n\n }\n \n });\n\n});\n\n// A list of all peer members (Both administrative and computing members).\napp.get(\"/peers\", (req, res) => {\n\n fs.readFile(__dirname + '/peers/config/' + 'store.json', 'utf8', (err, data) => {\n res.status(200).end(data);\n });\n\n});\n\n// Receive and store data sent from peer worker\napp.post(\"/peers/receive\", (req, res) => {\n\n // Add new process to peer queue worker\n peerWorker.add({jobData:req.body});\n\n});\n\n// API to check on progress of task. Failed and successful tasks.\napp.get(\"/data\", (req, res) => {\n\n fs.readFile(__dirname + '/monitor/data/' + 'data.json', 'utf8', (err, data) => {\n res.status(200).json(JSON.parse(data));\n });\n\n});\n\n// API to check on progress of task. Failed and successful tasks.\napp.get(\"/peers/data\", (req, res) => {\n\n fs.readFile(__dirname + '/peers/monitor/data/' + 'data.json', 'utf8', (err, data) => {\n res.status(200).json(JSON.parse(data));\n });\n\n});\n\n// Adam BC settings - init (GET)\napp.get('/init', (req, res) => {\n res.sendFile(path.join(__dirname + '/views/temp/settings/init.html'));\n});\n\n// Initialize Adam BC - Custom Mode\napp.get(\"/init_c\", (req, res) => {\n\n // Check if computer in Peer Mode or working remotely \n // If not in peer mode, update configurations here\n if(process.env.PEER_MODE=='NO'){\n\n // Store results into file \n fs.writeFile(__dirname + '/monitor/data/' + 'data.json', '[]', (err) => {\n \n if(err) console.log(err);\n\n }); \n \n // Read configurations from file\n fs.readFile(__dirname + '/app/config/' + 'config.json', 'utf8', (err, data) => {\n\n if(err) console.log(err);\n \n // Parse data to JSON\n let cfs = JSON.parse(data);\n\n // New configurations\n const cfgs = { \n builderID: cfs.builderID, // Developer ID\n TaskID: cfs.TaskID, // Task ID \n oPartition: cfs.oPartition, // Primary Iterator\n xPartition: cfs.xPartition, // Secondary Iterator\n iPartition: cfs.iPartition, // Initial Iterator\n tPartition: cfs.tPartition, // Transitional Iterator\n running: false, // Is task actively running \n tDuration: cfs.tDuration, // Duration\n TimeStarted: new Date(), // Time task started \n type:cfs.type, // App type\n lang:cfs.lang, // Language type\n uParams: cfs.uParams // Duration\n }\n\n // Update configuration settings \n fs.writeFile(__dirname + '/app/config/' + 'config.json', JSON.stringify(cfgs), (err) => {\n\n if(err) console.log(err);\n console.log('Configuration file initialized ..!');\n\n }); \n\n }); \n\n res.status(200).end('Adam BC (Custom Mode) is Initialized..!');\n\n } else {\n\n return apiResponse.ErrorResponse(res, `Sorry! You are in Peer Mode. This action can only be taken in Custom Mode ..! Go back to Settings and \\'Initialize the App\\' in Peer Mode.`);\n\n\n }\n});\n\n// Adam BC settings - init (GET)\napp.get('/peer/init', (req, res) => {\n res.sendFile(path.join(__dirname + '/views/temp/settings/init_peer.html'));\n});\n\n// Initialize Adam BC - Peer Mode\napp.get(\"/peer/init_p\", (req, res) => {\n\n // Check if computer in Peer Mode or working remotely \n // If not in peer mode, update configurations here\n if(process.env.PEER_MODE=='YES'){\n\n // Store results into file \n fs.writeFile(__dirname + '/peers/monitor/data/' + 'data.json', '[]', (err) => {\n \n if(err) console.log(err);\n\n }); \n \n // Read configurations from file\n fs.readFile(__dirname + '/app/config/' + 'config.json', 'utf8', (err, data) => {\n\n if(err) console.log(err);\n \n // Parse data to JSON\n let cfs = JSON.parse(data);\n\n // New configurations\n const cfgs = { \n builderID: cfs.builderID, // Developer ID\n TaskID: cfs.TaskID, // Task ID \n oPartition: cfs.oPartition, // Primary Iterator\n xPartition: cfs.xPartition, // Secondary Iterator\n iPartition: cfs.iPartition, // Initial Iterator\n tPartition: cfs.tPartition, // Transitional Iterator\n running: false, // Is task actively running \n tDuration: cfs.tDuration, // Duration\n TimeStarted: new Date(), // Time task started \n type: cfs.type, // App type\n lang: cfs.lang, // Language type\n uParams: cfs.uParams // Duration\n }\n\n // Update configuration settings \n fs.writeFile(__dirname + '/app/config/' + 'config.json', JSON.stringify(cfgs), (err) => {\n\n if(err) console.log(err);\n console.log('Configuration file initialized ..!');\n\n }); \n\n }); \n\n res.status(200).end('Adam BC (Peer Mode) is Initialized..!');\n\n } else {\n\n return apiResponse.ErrorResponse(res, `Sorry! You are in Custom Mode. This action can only be taken in Peer Mode ..! Go back to Settings and \\'Initialize the App\\' in Custom Mode.`);\n\n }\n});\n\n// Adam BC settings - environment (GET)\napp.get('/environment', (req, res) => {\n res.sendFile(path.join(__dirname + '/views/temp/settings/environment.html'));\n});\n\n// Adam BC scan, find and join peer networks (GET)\napp.get('/networks', (req, res) => {\n res.sendFile(path.join(__dirname + '/views/temp/settings/peers.html'));\n});\n\n// Adam BC Peer chat\napp.get('/messages', (req, res) => {\n\n // Register events on socket connection\n require('./app').io.on('connection', function(socket){ \n\n // Listen to chantMessage event sent by client and emit a chatMessage to the client\n socket.on('chatMessage', function(message){\n require('./app').io.to(message.receiver).emit('chatMessage', message);\n });\n \n // Listen to notifyTyping event sent by client and emit a notifyTyping to the client\n socket.on('notifyTyping', function(sender, receiver){\n require('./app').io.to(receiver.id).emit('notifyTyping', sender, receiver);\n });\n \n // Listen to newUser event sent by client and emit a newUser to the client with new list of online users\n socket.on('newUser', function(user){\n var newUser = {id: socket.id, name: user};\n function isOnline(peer){\n let detector=false;\n onlineUsers.forEach(function(userOnline, index){\n if(userOnline.name === peer.name) {\n detector=true;\n }\n });\n return detector;\n }\n if(isOnline(newUser)==false){\n onlineUsers.push(newUser);\n require('./app').io.to(socket.id).emit('newUser', newUser);\n require('./app').io.emit('onlineUsers', onlineUsers);\n }\n });\n \n // Listen to disconnect event sent by client and emit userIsDisconnected and onlineUsers (with new list of online users) to the client \n socket.on('disconnect', function(){\n onlineUsers.forEach(function(user, index){\n if(user.id === socket.id) {\n onlineUsers.splice(index, 1);\n require('./app').io.emit('userIsDisconnected', socket.id);\n require('./app').io.emit('onlineUsers', onlineUsers);\n }\n });\n });\n });\n\n res.sendFile(path.join(__dirname + '/views/temp/chat.html'));\n});\n\n// Receive and store new environment variables\napp.post(\"/environment\", (req, res) => {\n\n // Capture data sent\n const {peer_mode, network, username, contact, worker_id, crypto_id, work_id, backup} = req.body;\n\n // Update Peer Mode\n if(peer_mode!=''){\n\n setEnvValue(\"PEER_MODE\", `'${peer_mode}'`);\n\n }\n\n // Update Work id\n if(work_id!=''){\n\n setEnvValue(\"WORK_ID\", `'${uuidv4(work_id)}'`);\n\n }\n\n // Update worker id\n if(worker_id!=''){\n\n setEnvValue(\"WORKER_ID\", `'${uuidv4(worker_id)}'`);\n\n }\n\n // Update crypto id\n if(crypto_id!=''){\n\n setEnvValue(\"CRYPTO_ID\", `'${uuidv4(crypto_id)}'`);\n\n }\n\n // Update contact\n if(contact!=''){\n\n setEnvValue(\"WORKER_CONTACT\", `'${contact}'`);\n\n }\n\n // Update network settings\n if(network!=''){\n\n setEnvValue(\"GLOBAL_NETWORK\", `'${network}'`);\n\n }\n\n // Update username\n if(username!=''){\n\n setEnvValue(\"NETWORK_USERNAME\", `'${username}'`);\n\n }\n\n // Update backup settings\n if(backup!=''){\n\n setEnvValue(\"DATABASE_BACKUP\", `'${backup}'`);\n\n }\n\n res.end('Environment variables updated ..!');\n\n});\n\ncWorker()\npWorker()\n\n// Custom mode worker queue\nfunction cWorker (){\n \n customWorker.process(async (job) => {\n\n // Capture data sent\n const {data} = job.data.jobData;\n\n // Check if computer in Peer Mode or working remotely \n // If not in peer mode, update configurations here\n if(process.env.PEER_MODE=='NO'){\n\n // Read data from file \n let dataRead = await readData('/monitor/data/', 'data.json');\n\n // Parse data to JSON \n let str = JSON.parse(dataRead);\n \n // Check if file has reached its storage size limit \n if(str.length<250){\n \n // Store new data \n str.push(JSON.parse(data));\n \n await writeData('/monitor/data/', 'data.json', str);\n\n } else {\n \n // File storage is full \n console.log('File has reached storage limit ..!');\n \n }\n\n }\n\n // Update configuration settings to indicate new process settings\n \n // Parse data to JSON\n let json = JSON.parse(data);\n\n // Check if computer in Peer Mode or working remotely \n // If not in peer mode, update configurations here\n if(process.env.PEER_MODE=='NO'){\n\n // New configurations\n const logs = { \n builderID: json[\"configs\"].builderID, // Developer ID\n TaskID: json[\"configs\"].TaskID, // Task ID \n oPartition: json[\"logs\"].oPartition, // Primary Iterator\n xPartition: json[\"logs\"].xPartition, // Secondary Iterator\n iPartition: json[\"logs\"].iPartition, // Initial Iterator\n tPartition: Number(json[\"logs\"].iPartition+json[\"logs\"].tPartition+json[\"logs\"].xPartition), // Transitional Iterator\n Timestamp: new Date(), // Timestamp for latest iteration \n running: json[\"configs\"].running, // Is task actively running \n tDuration: json[\"logs\"].tDuration, // Duration\n type: json[\"logs\"].type, // App type\n lang: json[\"logs\"].lang, // Language type\n uParams: [] // Developer defined parameters\n }\n\n // Update configuration settings\n await writeData('/app/config/', 'log.txt', logs);\n\n // If task is running for the first time, update running from 'false' to 'true'\n if(json[\"configs\"].running==false) {\n\n // Read configurations from file\n let cData = await readData('/app/config/', 'config.json');\n \n // Parse data to JSON\n let cfs = JSON.parse(cData);\n\n // New configurations\n const cfgs = { \n builderID: cfs.builderID, // Developer ID\n TaskID: cfs.TaskID, // Task ID \n oPartition: cfs.oPartition, // Primary Iterator\n xPartition: cfs.xPartition, // Secondary Iterator\n iPartition: cfs.iPartition, // Initial Iterator\n tPartition: cfs.tPartition, // Transitional Iterator\n running: true, // Is task actively running \n tDuration: cfs.tDuration, // Duration\n TimeStarted: new Date(), // Time task started \n type:cfs.type, // App type\n lang:cfs.lang, // Language type\n uParams: [] // Developer defined parameters\n }\n\n // Update configuration settings \n await writeData('/app/config/', 'config.json', cfgs);\n\n }\n\n // Check if processing is done, if so, change 'config.json' 'running' parameter from 'true' to 'done'\n if(Number(json[\"logs\"].iPartition+json[\"logs\"].tPartition+json[\"logs\"].xPartition)>Number(json[\"logs\"].oPartition)) {\n\n // Read configurations from file\n let nData = await readData('/app/config/', 'config.json');\n \n // Parse data to JSON\n let csn = JSON.parse(nData);\n\n // New configurations\n const cgs = { \n builderID: csn.builderID, // Developer ID\n TaskID: csn.TaskID, // Task ID \n oPartition: csn.oPartition, // Primary Iterator\n xPartition: csn.xPartition, // Secondary Iterator\n iPartition: csn.iPartition, // Initial Iterator\n tPartition: csn.tPartition, // Transitional Iterator\n running: \"done\", // Is task actively running \n tDuration: csn.tDuration, // Duration\n TimeStarted: csn.TimeStarted, // Time task started \n type:csn.type, // App type\n lang:csn.lang, // Language type\n uParams: [] // Developer defined parameters\n }\n\n // Update configuration settings \n await writeData('/app/config/', 'config.json', cgs);\n\n }\n\n // If in peer mode, just re-trigger start\n }\n\n // Write date to file\n async function writeData(dir, file, data) {\n \n if(process.env.DATABASE_BACKUP=='ON'){\n await save(data)\n }\n \n try { \n return fs.writeFileSync(__dirname + dir + file, JSON.stringify(data));\n } \n \n catch (err) { \n console.log('Problem writing to file.')\n }\n \n }\n \n // Read data from file\n async function readData(dir, file) {\n \n try { \n return fs.readFileSync(__dirname + dir + file, 'utf8');\n }\n \n catch (err) { \n console.log('Problem fetching file.')\n }\n \n }\n\n });\n\n}\n\n// Peer mode worker queue\nfunction pWorker (){\n \n peerWorker.process(async (job) => {\n\n // Capture data sent\n const {data} = job.data.jobData;\n\n // Read data from file \n let dataRead = await readData('/peers/monitor/data/', 'data.json');\n\n // Parse data to JSON \n let str = JSON.parse(dataRead);\n \n // Check if file has reached its storage size limit \n if(str.length<250){\n \n // Store new data \n str.push(JSON.parse(data));\n \n await writeData('/peers/monitor/data/', 'data.json', str);\n\n } else {\n \n // File storage is full \n console.log('File has reached storage limit ..!');\n \n }\n\n // Update configuration settings to indicate new process settings\n \n // Parse data to JSON\n let json = JSON.parse(data);\n\n // New configurations\n const logs = { \n builderID: json[\"configs\"].builderID, // Developer ID\n TaskID: json[\"configs\"].TaskID, // Task ID \n oPartition: json[\"logs\"].oPartition, // Primary Iterator\n xPartition: json[\"logs\"].xPartition, // Secondary Iterator\n iPartition: json[\"logs\"].iPartition, // Initial Iterator\n tPartition: Number(json[\"logs\"].iPartition+json[\"logs\"].tPartition+json[\"logs\"].xPartition), // Transitional Iterator\n Timestamp: new Date(), // Timestamp for latest iteration \n running: json[\"configs\"].running, // Is task actively running \n tDuration: json[\"logs\"].tDuration, // Duration\n type: json[\"logs\"].type, // App type\n lang: json[\"logs\"].lang, // Language type\n uParams: [] // Developer defined parameters\n }\n\n // Update configuration settings\n await writeData('/app/config/', 'log.txt', logs);\n\n // If task is running for the first time, update running from 'false' to 'true'\n if(json[\"configs\"].running==false) {\n\n // Read configurations from file\n let cData = await readData('/app/config/', 'config.json');\n \n // Parse data to JSON\n let cfs = JSON.parse(cData);\n\n // New configurations\n const cfgs = { \n builderID: cfs.builderID, // Developer ID\n TaskID: cfs.TaskID, // Task ID \n oPartition: cfs.oPartition, // Primary Iterator\n xPartition: cfs.xPartition, // Secondary Iterator\n iPartition: cfs.iPartition, // Initial Iterator\n tPartition: cfs.tPartition, // Transitional Iterator\n running: true, // Is task actively running \n tDuration: cfs.tDuration, // Duration\n TimeStarted: new Date(), // Time task started \n type:cfs.type, // App type\n lang:cfs.lang, // Language type\n uParams: [] // Developer defined parameters\n }\n\n // Update configuration settings \n await writeData('/app/config/', 'config.json', cfgs);\n\n }\n\n // Check if processing is done, if so, change 'config.json' 'running' parameter from 'true' to 'done'\n if(Number(json[\"logs\"].iPartition+json[\"logs\"].tPartition+json[\"logs\"].xPartition)>Number(json[\"logs\"].oPartition)) {\n\n // Read configurations from file\n let nData = await readData('/app/config/', 'config.json');\n \n // Parse data to JSON\n let csn = JSON.parse(nData);\n\n // New configurations\n const cgs = { \n builderID: csn.builderID, // Developer ID\n TaskID: csn.TaskID, // Task ID \n oPartition: csn.oPartition, // Primary Iterator\n xPartition: csn.xPartition, // Secondary Iterator\n iPartition: csn.iPartition, // Initial Iterator\n tPartition: csn.tPartition, // Transitional Iterator\n running: \"done\", // Is task actively running \n tDuration: csn.tDuration, // Duration\n TimeStarted: csn.TimeStarted, // Time task started \n type:csn.type, // App type\n lang:csn.lang, // Language type\n uParams: [] // Developer defined parameters\n }\n\n // Update configuration settings \n await writeData('/app/config/', 'config.json', cgs);\n\n }\n\n // Write date to file\n async function writeData(dir, file, data) {\n \n if(process.env.DATABASE_BACKUP=='ON'){\n await save(data)\n }\n\n try { \n return fs.writeFileSync(__dirname + dir + file, JSON.stringify(data));\n } \n \n catch (err) { \n console.log('Problem writing to file.')\n }\n \n }\n \n // Read data from file\n async function readData(dir, file) {\n \n try { \n return fs.readFileSync(__dirname + dir + file, 'utf8');\n }\n \n catch (err) { \n console.log('Problem fetching file.')\n }\n \n }\n\n });\n\n}\n\n// Export app\nmodule.exports = app;\n", "dangerousExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/dan', function (req, res) {\n5. const url = req.body.profile_url;\n6. try{\n7. res.redirect(url);\n8. }catch (e) {\n9. return res.status(500).send(\"ERROR\");\n10. }\n11. });\n12. \n13. module.exports = router;\nLine 7: A string variable URL of an unvalidated external input is used to connect.", "safeExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/safe', function (req, res) {\n5. const url = req.body.profile_url;\n6. const white_list = [\"https://www.safeurl.com\", \"https://www.verified.com\"];\n7. if (white_list.indexOf(url) < 0) {\n8. return res.status(500).send(\"url not allowed\");\n9. } else {\n10. try {\n11. res.redirect(url);\n12. } catch (e) {\n13. return res.status(500).send(\"ERROR\");\n14. }\n15. }\n16. });\n17. \n18. module.exports = router;\nLine 7-9: Validate external inputs through a filter function.", "contexts": [{"lineNo": 199, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "data"}}, {"lineNo": 203, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "encodeURIComponent"}}, {"lineNo": 207, "eventType": "source", "messageKey": "synz.COMMON.branch.false.assumed", "params": {"arg0": "211"}}, {"lineNo": 214, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "redirect"}}]}} {"id": "2299f90e8cacb4197853d0189a6c3909206098b0da63859c5bad0befeaafdc8d", "license": {"spdx": ["MIT"], "repo": "JordanYoung-97/Jordan_Code_Samples", "path": "Shopify-Code/VIP APP/index.js", "repo_head_hexsha": "f60d2e59ff1971562eb6610f3f519b68203914e9", "stack_hexsha": "b1d9bddfb31bcd4b621e074b39a6ceb187428693", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Redirection to untrusted site", "issueDescriptionEn": "The Redirection to untrusted site checker finds instances of redirecting to a URL generated with an unvalidated external input.\nAlthough connecting to a client-provided URL is often believed to be safe, an attacker can modify the request and redirect the user to a malicious site.\nMaintain a whitelist of external site URLs and domains allowed for redirection, which needs to be checked when a user input is passed as a redirect URL.", "issueLineNumber": 39, "entireCode": "const express = require('express');\nconst bodyParser = require('body-parser');\nconst dotenv = require('dotenv').config();\nconst app = express();\nconst crypto = require('crypto');\nconst cookie = require('cookie');\nconst nonce = require('nonce')();\nconst querystring = require('querystring');\nconst request = require('request-promise');\n\n\nconst apiKey = process.env.SHOPIFY_API_KEY;\nconst apiSecret = process.env.SHOPIFY_API_SECRET;\nconst scopes = 'read_products, read_customers, write_customers';\nconst forwardingAddress = \"https://6e9ed9e6.ngrok.io\"; // Replace this with your HTTPS Forwarding address\n\nvar customerCount = {};\n\napp.get('/', (req, res) => {\n res.send('Hello World!');\n});\n\napp.listen(3000, () => {\n console.log('Example app listening on port 3000!');\n});\n\napp.get('/shopify', (req, res) => {\n const shop = req.query.shop;\n if (shop) {\n const state = nonce();\n const redirectUri = forwardingAddress + '/shopify/callback';\n const installUrl = 'https://' + shop +\n '/admin/oauth/authorize?client_id=' + apiKey +\n '&scope=' + scopes +\n '&state=' + state +\n '&redirect_uri=' + redirectUri;\n \n res.cookie('state', state);\n res.redirect(installUrl);\n } else {\n return res.status(400).send('Missing shop parameter. Please add ?shop=your-development-shop.myshopify.com to your request');\n }\n });\n\n app.get('/shopify/callback', (req, res) => {\n const { shop, hmac, code, state } = req.query;\n const stateCookie = cookie.parse(req.headers.cookie).state;\n\n if (state !== stateCookie) {\n return res.status(403).send('Request origin cannot be verified');\n }\n\n if (shop && hmac && code) {\n // DONE: Validate request is from Shopify\n const map = Object.assign({}, req.query);\n delete map['signature'];\n delete map['hmac'];\n const message = querystring.stringify(map);\n const providedHmac = Buffer.from(hmac, 'utf-8');\n const generatedHash = Buffer.from(\n crypto\n .createHmac('sha256', apiSecret)\n .update(message)\n .digest('hex'),\n 'utf-8'\n );\n let hashEquals = false;\n\n try {\n hashEquals = crypto.timingSafeEqual(generatedHash, providedHmac)\n } catch (e) {\n hashEquals = false;\n };\n\n if (!hashEquals) {\n return res.status(400).send('HMAC validation failed');\n }\n\n // DONE: Exchange temporary code for a permanent access token\n const accessTokenRequestUrl = 'https://' + shop + '/admin/oauth/access_token';\n const accessTokenPayload = {\n client_id: apiKey,\n client_secret: apiSecret,\n code,\n };\n\n request.post(accessTokenRequestUrl, { json: accessTokenPayload })\n .then((accessTokenResponse) => {\n const accessToken = accessTokenResponse.access_token;\n // DONE: Use access token to make API call to 'count' endpoint\n const shopRequestUrl = 'https://' + shop + '/admin/api/2019-07/customers/count.json';\n const shopRequestHeaders = {\n 'X-Shopify-Access-Token': accessToken,\n };\n\n // GET REQUEST FOR CUSTOMERS AND CUSTOMER INFO\n request.get(shopRequestUrl, { headers: shopRequestHeaders })\n .then((shopResponse) => {\n let customers = JSON.parse(shopResponse);\n customerCount = customers.count;\n var limit = 250; //limit of customers per page\n if(customerCount > 0){\n var pages = Math.ceil(customerCount / limit);\n console.log('pages: ' + pages);\n for (let i = 0; i < pages; i++) {\n request.get('https://' + shop + '/admin/api/2019-07/customers.json?limit=' + limit + '&page='+(i + 1), {headers: shopRequestHeaders})\n .then((customers) => {\n var customerList = JSON.parse(customers);\n var x = 0;\n\n //Cant feed all the customers through the api at once. Encase PUT call in a function, then delay the call of the functions using setTimeout()\n function go() {\n const element = customerList.customers[x];\n var tagToAdd = '';\n //first check if customer is already a wholesale customer, if so add the whexclude tag which will exclude them from the Auto Tagging feature a part of Wholesale Hero.\n if(element.tags.includes('Wholesaler')){\n tagToAdd = ',whexclude';\n } else {\n if(element.total_spent >= 300){\n if(element.default_address.country == 'United States'){\n tagToAdd = ',VIP01';\n } else {\n tagToAdd = ',VIP01-INT';\n }\n }\n if(element.total_spent >= 600){\n if(element.default_address.country == 'United States'){\n tagToAdd = ',VIP02';\n } else {\n tagToAdd = ',VIP02-INT';\n }\n }\n if(element.total_spent >= 1000){\n if(element.default_address.country == 'United States'){\n tagToAdd = ',VIP03';\n } else {\n tagToAdd = ',VIP03-INT';\n }\n }\n }\n\n //select the specific customer to update using their unique id then take their current tags and add the tags we have set to add above\n var url = 'https://' + shop + '/admin/api/2019-07/customers/' + element.id + '.json';\n var customerUpdate = {\n \"customer\" : {\n \"id\" : element.id,\n \"tags\" : element.tags + tagToAdd\n }\n };\n\n //Check if the customer has a total spent of 300, as to ignore all other customers. Then PUT the updated customer.\n if(element.total_spent >= 300){\n request.put(url, {\n method: \"PUT\",\n headers: shopRequestHeaders,\n body: customerUpdate,\n json: true\n })\n .then((responseCustomer) => {\n console.log(responseCustomer);\n res.status(200);\n })\n .catch((error) =>{\n console.log(error);\n res.status(error.statusCode).send(error.error.error_description);\n });\n }\n //each time the function runs increament x and compare it to the array length, this will slow down our api calls.\n if (x++ < customerList.customers.length - 1) {\n setTimeout(go, 2000);\n console.log(\"delay\");\n }\n }\n //start the bulk tagging process.\n go();\n })\n .catch((error) =>{\n\n });\n }\n }\n\n res.status(200).end('Started Auto-Tagging');\n })\n .catch((error) => {\n res.status(error.statusCode).send(error.error.error_description);\n });\n })\n .catch((error) => {\n res.status(error.statusCode).send(error.error.error_description);\n });\n\n } else {\n res.status(400).send('Required parameters missing');\n }\n});", "dangerousExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/dan', function (req, res) {\n5. const url = req.body.profile_url;\n6. try{\n7. res.redirect(url);\n8. }catch (e) {\n9. return res.status(500).send(\"ERROR\");\n10. }\n11. });\n12. \n13. module.exports = router;\nLine 7: A string variable URL of an unvalidated external input is used to connect.", "safeExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/safe', function (req, res) {\n5. const url = req.body.profile_url;\n6. const white_list = [\"https://www.safeurl.com\", \"https://www.verified.com\"];\n7. if (white_list.indexOf(url) < 0) {\n8. return res.status(500).send(\"url not allowed\");\n9. } else {\n10. try {\n11. res.redirect(url);\n12. } catch (e) {\n13. return res.status(500).send(\"ERROR\");\n14. }\n15. }\n16. });\n17. \n18. module.exports = router;\nLine 7-9: Validate external inputs through a filter function.", "contexts": [{"lineNo": 28, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "req"}}, {"lineNo": 29, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "29"}}, {"lineNo": 32, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 39, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "redirect"}}]}} {"id": "99f4b86925718d601e84869a69e46653d7a9eec9b3328cc0cc7e0f0ba8defbb0", "license": {"spdx": ["MIT"], "repo": "lcundiff/motorolaWebsite", "path": "modules/users/server/controllers/users/users.signuplink.server.controller.js", "repo_head_hexsha": "fbcfaa08dff45b8a4b8e853ae992c1a0c360b4b9", "stack_hexsha": "fcf38eb584c4253327a56acbcf8a9c688559a547", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Redirection to untrusted site", "issueDescriptionEn": "The Redirection to untrusted site checker finds instances of redirecting to a URL generated with an unvalidated external input.\nAlthough connecting to a client-provided URL is often believed to be safe, an attacker can modify the request and redirect the user to a malicious site.\nMaintain a whitelist of external site URLs and domains allowed for redirection, which needs to be checked when a user input is passed as a redirect URL.", "issueLineNumber": 146, "entireCode": "'use strict';\n\n/**\n * Module dependencies\n */\nvar path = require('path'),\n config = require(path.resolve('./config/config')),\n errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller')),\n mongoose = require('mongoose'),\n User = mongoose.model('User'),\n UserReq = mongoose.model('UserReq'),\n nodemailer = require('nodemailer'),\n async = require('async'),\n crypto = require('crypto');\n\nvar smtpTransport = nodemailer.createTransport(config.mailer.options);\n\n/**\n * Forgot for reset password (forgot POST)\n */\n\nexports.requestLink = function (req, res) {\n if (req.body.email) {\n\n var email = Promise.resolve(String(req.body.email).toLowerCase());\n var firstName = Promise.resolve(String(req.body.firstName));\n var lastName = Promise.resolve(String(req.body.lastName));\n\n Promise.all([email, firstName, lastName]).then(async function([ue, uf, ul]){\n var userReq = new UserReq();\n await(userReq);\n await(userReq.firstName = uf);\n await(userReq.lastName = ul);\n await(userReq.email = ue);\n\n await(userReq.save(function (err) {\n res.send({\n message: 'Your request has been submitted.'\n });\n }));\n })\n\n } else {\n return res.status(422).send({\n message: 'Email field must not be blank'\n });\n }\n};\n\nexports.signupLink = function (req, res, next) {\n async.waterfall([\n // Generate random token\n function (done) {\n crypto.randomBytes(20, function (err, buffer) {\n var token = buffer.toString('hex');\n done(err, token);\n });\n },\n // Lookup user by username\n function (token, done) {\n if (req.body.email) {\n var email = Promise.resolve(String(req.body.email).toLowerCase());\n var signupLinkToken = Promise.resolve(token);\n var signupLinkExpires = Promise.resolve(Date.now() + (3600000*24)); // 1 hour\n\n Promise.all([email, signupLinkToken, signupLinkExpires]).then(async function([ue, ut, us]){\n await(req.body.email = ue);\n await(req.body.signupLinkToken = ut);\n await(req.body.signupLinkExpires = us);\n await(delete req.body.__v);\n\n await(UserReq.findOneAndUpdate({email: ue}, req.body, {upsert: true})\n .then(function(response){\n done(null, token, req.body);\n })\n .catch(function(err){\n res.status(400).send({\n message: 'Failure sending email'\n });\n }));\n });\n } else {\n return res.status(422).send({\n message: 'Email field must not be blank'\n });\n }\n },\n function (token, user, done) {\n var httpTransport = 'https://';\n if (config.secure && config.secure.ssl === true) {\n httpTransport = 'https://';\n }\n var baseUrl = config.domain || httpTransport + req.headers.host;\n res.render(path.resolve('modules/users/server/templates/signup-link-email'), {\n name: user.firstName + ' '+ user.lastName,\n appName: config.app.title,\n url: baseUrl + '/api/auth/signup/' + token\n }, function (err, emailHTML) {\n done(err, emailHTML, user);\n });\n },\n // If valid email, send reset email using service\n function (emailHTML, user, done) {\n var mailOptions = {\n to: user.email,\n from: config.mailer.from,\n subject: 'IMPORTANT: MSI Career Mentoring and Shadowing Program Sign-Up',\n html: emailHTML\n };\n smtpTransport.sendMail(mailOptions, function (err) {\n if (!err) {\n res.send({\n message: 'An email has been sent to the provided email with further instructions.'\n });\n } else {\n console.log(err);\n return res.status(400).send({\n message: 'Failure sending email'\n });\n }\n\n done(err);\n });\n }\n ], function (err) {\n if (err) {\n return next(err);\n }\n });\n};\n\n/**\n * Reset password GET from email token\n */\nexports.validateSignupToken = function (req, res) {\n UserReq.findOne({\n signupLinkToken: req.params.token,\n signupLinkExpires: {\n $gt: Date.now()\n }\n }, function (err, userReq) {\n if (err || !userReq) {\n return res.redirect('/authentication/signup/invalid');\n }\n\n res.redirect('/authentication/signup/' + req.params.token);\n });\n};", "dangerousExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/dan', function (req, res) {\n5. const url = req.body.profile_url;\n6. try{\n7. res.redirect(url);\n8. }catch (e) {\n9. return res.status(500).send(\"ERROR\");\n10. }\n11. });\n12. \n13. module.exports = router;\nLine 7: A string variable URL of an unvalidated external input is used to connect.", "safeExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/safe', function (req, res) {\n5. const url = req.body.profile_url;\n6. const white_list = [\"https://www.safeurl.com\", \"https://www.verified.com\"];\n7. if (white_list.indexOf(url) < 0) {\n8. return res.status(500).send(\"url not allowed\");\n9. } else {\n10. try {\n11. res.redirect(url);\n12. } catch (e) {\n13. return res.status(500).send(\"ERROR\");\n14. }\n15. }\n16. });\n17. \n18. module.exports = router;\nLine 7-9: Validate external inputs through a filter function.", "contexts": [{"lineNo": 146, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "req"}}, {"lineNo": 146, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "redirect"}}]}} {"id": "63264e69d78143780f65b024d15abbe39eb4f0a60a4ba4b45d27244a86c49212", "license": {"spdx": ["MIT"], "repo": "DEFRA/echo-prototype", "path": "app/routes/v5/EXUCD-11-save-and-continue.js", "repo_head_hexsha": "fab6f243a940e66fc4700b86a03868cb9794a8db", "stack_hexsha": "b45cff9d07e2105ba71c410a76d8a9a30f6ee316", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Redirection to untrusted site", "issueDescriptionEn": "The Redirection to untrusted site checker finds instances of redirecting to a URL generated with an unvalidated external input.\nAlthough connecting to a client-provided URL is often believed to be safe, an attacker can modify the request and redirect the user to a malicious site.\nMaintain a whitelist of external site URLs and domains allowed for redirection, which needs to be checked when a user input is passed as a redirect URL.", "issueLineNumber": 20, "entireCode": "module.exports = function(router) {\n // Load helper functions\n var tools = require('../tools.js')\n\n\n // ADD extra routing here if needed.\n // require('./extra-stories.js')(router)\n const fs = require('fs');\n\n // CHANGE VERSION TO THE VERSION\n const version = 'beta/v5'\n const base_url = version + \"/EXUCD-11-save-and-continue\"\n const file_url = version + \"/core\"\n\n router.post('/'+base_url+'*/certificate/save-and-continue-later', function(req, res) {\n console.log(\"working\")\n if(req.body.save_and_continue ==\"yes\"){\n res.redirect(301, '/' + base_url +req.params[0]+ '/dashboard?has_unfinished_certificate=yes');\n }else{\n res.redirect(301, '/' + base_url +req.params[0]+ \"/\"+req.query.save_return);\n }\n })\n}", "dangerousExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/dan', function (req, res) {\n5. const url = req.body.profile_url;\n6. try{\n7. res.redirect(url);\n8. }catch (e) {\n9. return res.status(500).send(\"ERROR\");\n10. }\n11. });\n12. \n13. module.exports = router;\nLine 7: A string variable URL of an unvalidated external input is used to connect.", "safeExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/safe', function (req, res) {\n5. const url = req.body.profile_url;\n6. const white_list = [\"https://www.safeurl.com\", \"https://www.verified.com\"];\n7. if (white_list.indexOf(url) < 0) {\n8. return res.status(500).send(\"url not allowed\");\n9. } else {\n10. try {\n11. res.redirect(url);\n12. } catch (e) {\n13. return res.status(500).send(\"ERROR\");\n14. }\n15. }\n16. });\n17. \n18. module.exports = router;\nLine 7-9: Validate external inputs through a filter function.", "contexts": [{"lineNo": 17, "eventType": "source", "messageKey": "synz.COMMON.branch.false.assumed", "params": {"arg0": "19"}}, {"lineNo": 20, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "req"}}, {"lineNo": 20, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "redirect"}}]}} {"id": "3f0ae62037cab94ed51ee1ce2dc97d80227cb073e574bab81fec4fa63a3b6921", "license": {"spdx": ["Apache-2.0"], "repo": "chenyutcmn/Node_Blog", "path": "modles/reply.js", "repo_head_hexsha": "b993fe0af108e20781e9dcbd20632e35673d9a44", "stack_hexsha": "439e2bd3205eb601eceae317df59a0949f508ab7", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Redirection to untrusted site", "issueDescriptionEn": "The Redirection to untrusted site checker finds instances of redirecting to a URL generated with an unvalidated external input.\nAlthough connecting to a client-provided URL is often believed to be safe, an attacker can modify the request and redirect the user to a malicious site.\nMaintain a whitelist of external site URLs and domains allowed for redirection, which needs to be checked when a user input is passed as a redirect URL.", "issueLineNumber": 31, "entireCode": "var moment = require('moment');\nvar MongoClient = require('mongodb').MongoClient;\nvar async = require('async');\nvar mongoose = require('mongoose');\nvar settings = require('../settings');\n\nexports.add_reply = function(req , res){\n\tvar reply = {\n\t\t'article_id' : req.params.article_id,\n\t\t'reply_author' : req.session.user.username,\n\t\t'reply_content' : req.body.reply_content,\n\t\t'reply_date' : moment(new Date()).format('YYYY_MM_DD HH:mm')\n\t};\n\tasync.waterfall([\n\t\tfunction(cb){\n\t\t\tMongoClient.connect(settings.uri , cb);\n\t\t},\n\t\tfunction(db , cb){\n\t\t\tDb = db;\n\t\t\tdb.collection('reply' , cb);\n\t\t},\n\t\tfunction(db_coll , cb){\n\t\t\tdb_coll.insert(reply , {safe : true});\n\t\t\tcb(null);\n\t\t}\n\t\t] , function(err , result){\n\t\t\tDb.close();\n\t\t\tif(err){\n\t\t\t\tconsole.log(err);\n\t\t\t}else{\n\t\t\t\tres.redirect('/update_reply_num/' + req.params.article_id + '/' + 1);\n\t\t\t}\n\t});\n};\n\nexports.delete_reply = function(article_id , callback){\n\tasync.waterfall([\n\t\tfunction(cb){\n\t\t\tMongoClient.connect(settings.uri , cb);\n\t\t},\n\t\tfunction(db , cb){\n\t\t\tDb = db;\n\t\t\tdb.collection('reply' , cb);\n\t\t},\n\t\tfunction(db_coll , cb){\n\t\t\tdb_coll.remove({\n\t\t\t\t'article_id' : article_id\n\t\t\t},\n\t\t\t{safe : true} , cb);\n\t\t}\n\t\t] , function(err , result){\n\t\t\tDb.close();\n\t\t\tcallback(err);\n\t});\n};\n\nexports.find_reply = function(article_Id , callback){\n\tvar article_id = article_Id;\n\tasync.waterfall([\n\t\tfunction(cb){\n\t\t\tMongoClient.connect(settings.uri , cb);\n\t\t},\n\t\tfunction(db , cb){\n\t\t\tDb = db;\n\t\t\tdb.collection('reply' , cb);\n\t\t},\n\t\tfunction(db_coll , cb){\n\t\t\tdb_coll.find({'article_id' : article_id}).sort({reply_date : -1}).toArray(cb);\n\t\t}\n\t\t] , function(err , result){\n\t\t\tDb.close();\n\t\t\tif(err){\n\t\t\t\tconsole.log(err);\n\t\t\t\tcallback(err , null);\n\t\t\t}else{\n\t\t\t\tcallback(null , result);\n\t\t\t}\n\t});\n};\n\nexports.update_reply_num = function(req , res){\n\tasync.waterfall([\n\t\tfunction(cb){\n\t\t\tMongoClient.connect(settings.uri , cb);\n\t\t},\n\t\tfunction(db , cb){\n\t\t\tDb = db;\n\t\t\tdb.collection('article' , cb);\n\t\t},\n\t\tfunction(db_coll , cb){\n\t\t\tdb_Coll = db_coll;\n\t\t\tdb_coll.find({'_id' : mongoose.Types.ObjectId(req.params.article_id)}).toArray(cb);\n\t\t},\n\t\tfunction(result , cb){\n\t\t\tauthor = result[0]['author'];\n\t\t\tvar now_num = parseInt(result[0]['reply_num']);\n\t\t\tvar update_num = parseInt(req.params.update_num);\n\t\t\tvar reply_num = now_num + update_num;\n\t\t\tdb_Coll.update(\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t//update the read_num\n\t\t\t\t{'_id' : mongoose.Types.ObjectId(req.params.article_id)},\n\t\t\t\t{ $set: { 'reply_num': reply_num} },\n\t\t\t\t{ safe: true });\n\t\t\tcb(null);\n\t\t}\n\t\t],function(err , result){\n\t\t\tDb.close();\n\t\t\tif(err){\n\t\t\t\tconsole.log(err);\n\t\t\t}else{\n\t\t\t\tres.redirect('/' + author + '/' + req.params.article_id + '/detail');\n\t\t\t}\n\t\t});\n};", "dangerousExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/dan', function (req, res) {\n5. const url = req.body.profile_url;\n6. try{\n7. res.redirect(url);\n8. }catch (e) {\n9. return res.status(500).send(\"ERROR\");\n10. }\n11. });\n12. \n13. module.exports = router;\nLine 7: A string variable URL of an unvalidated external input is used to connect.", "safeExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/safe', function (req, res) {\n5. const url = req.body.profile_url;\n6. const white_list = [\"https://www.safeurl.com\", \"https://www.verified.com\"];\n7. if (white_list.indexOf(url) < 0) {\n8. return res.status(500).send(\"url not allowed\");\n9. } else {\n10. try {\n11. res.redirect(url);\n12. } catch (e) {\n13. return res.status(500).send(\"ERROR\");\n14. }\n15. }\n16. });\n17. \n18. module.exports = router;\nLine 7-9: Validate external inputs through a filter function.", "contexts": [{"lineNo": 28, "eventType": "source", "messageKey": "synz.COMMON.branch.false.assumed", "params": {"arg0": "30"}}, {"lineNo": 31, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "req"}}, {"lineNo": 31, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "redirect"}}]}} {"id": "9fe6665c45044f80da373018a70144a36d49db896358039084ae12537d3a44db", "license": {"spdx": ["MIT", "Unlicense"], "repo": "vperlerin/AMSCam", "path": "public/routes/detections.js", "repo_head_hexsha": "a2ebfbcf75f99e8a7c3bde04db357ae5e1d728d8", "stack_hexsha": "a21faefe6379995e301ad08e0f46c15f3b12bcb7", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Redirection to untrusted site", "issueDescriptionEn": "The Redirection to untrusted site checker finds instances of redirecting to a URL generated with an unvalidated external input.\nAlthough connecting to a client-provided URL is often believed to be safe, an attacker can modify the request and redirect the user to a malicious site.\nMaintain a whitelist of external site URLs and domains allowed for redirection, which needs to be checked when a user input is passed as a redirect URL.", "issueLineNumber": 73, "entireCode": "var PythonShell = require('python-shell');\nvar express = require('express');\nvar router = express.Router(); \n \nvar utils = require('../utils/browser');\nvar constants = require('../utils/constants');\nvar cookie = require('../utils/cookie');\n\n/******************************************************************************************************************************************\n* Detections\n***********************************************/\nexports.load = function(req, res) {\n \n // Detection type\n var type = req.params.type;\n \n // Get the eventual pagination parameters passed in argument\n var page; \n page = (typeof req.query.page === \"undefined\")?1:req.query.page; \n \n // Get all maybe detections\n var opts = {\n mode: 'json',\n args: ['/var/www/html/out/'+type+'/',page,constants.DETECTION_PER_PAGE],\n scriptPath: constants.python_path+'/detections'\n };\n \n // Test Browser\n browser = utils.get_browser(req)\n \n PythonShell.run('list_detection_files.py', opts, function (err, ress) {\n if (err) throw err;\n \n var org_url = req.protocol + '://' + req.get('host') + req.originalUrl;\n \n // Render options\n opts_render = {\n results: ress,\n folder: '/'+type,\n type:type,\n browser: browser,\n curURL: org_url.substring(0, org_url.indexOf('?')),\n title:(type==='maybe')?'Uncertain detections':((type==='false')?'False detections':'Fireballs')\n };\n \n if(typeof req.query.success !== \"undefined\") {\n opts_render.success = req.query.success.split(\"$\");\n }\n \n cookie.get_config_cookie_and_render(req, res, opts_render, 'detections'); \n \n });\n};\n\n/******************************************************************************************************************************************\n* Delete Detections (single)\n***********************************************/\nexports.delete_single_detect = function(req, res) {\n \n // Detection type\n var type = req.params.type;\n var ev = req.params.ev;\n \n // Get select detection \n var opts = { \n mode: 'text',\n args: ['/var/www/html/out/'+type+'/',ev],\n scriptPath: constants.python_path+'/file_management'\n };\n \n PythonShell.run('delete_file.py', opts, function (err, ress) {\n if (err) throw err;\n res.redirect('/detection/'+type+'?success='+ress[0]);\n });\n \n};\n\n\n/******************************************************************************************************************************************\n* Detection false deletion (multiple)\n***********************************************/\nexports.delete_multiple_detect = function(req, res) { \n \n // Detection type\n var type = req.params.type;\n var evs = req.body.events;\n \n var opts = { \n mode: 'text',\n args: ['/var/www/html/out/'+type+'/',evs],\n scriptPath: constants.python_path+'/file_management'\n }; \n \n PythonShell.run('delete_file.py', opts, function (err, ress) {\n if (err) throw err;\n res.redirect('/detection/'+type+'?success='+ress[0]);\n });\n \n};\n\n\n/******************************************************************************************************************************************\n* Detection ALL deletion \n***********************************************/\nexports.delete_all_detect = function(req, res) { \n \n // Detection type\n var type = req.params.type; \n \n var opts = { \n mode: 'text',\n args: ['/var/www/html/out/'+type+'/'],\n scriptPath: constants.python_path+'/file_management'\n }; \n \n PythonShell.run('delete_file.py', opts, function (err, ress) {\n if (err) throw err;\n res.redirect('/detection/'+type+'?success='+ress[0]);\n });\n \n};", "dangerousExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/dan', function (req, res) {\n5. const url = req.body.profile_url;\n6. try{\n7. res.redirect(url);\n8. }catch (e) {\n9. return res.status(500).send(\"ERROR\");\n10. }\n11. });\n12. \n13. module.exports = router;\nLine 7: A string variable URL of an unvalidated external input is used to connect.", "safeExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/safe', function (req, res) {\n5. const url = req.body.profile_url;\n6. const white_list = [\"https://www.safeurl.com\", \"https://www.verified.com\"];\n7. if (white_list.indexOf(url) < 0) {\n8. return res.status(500).send(\"url not allowed\");\n9. } else {\n10. try {\n11. res.redirect(url);\n12. } catch (e) {\n13. return res.status(500).send(\"ERROR\");\n14. }\n15. }\n16. });\n17. \n18. module.exports = router;\nLine 7-9: Validate external inputs through a filter function.", "contexts": [{"lineNo": 61, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "req"}}, {"lineNo": 73, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "redirect"}}]}} {"id": "cb7e33bb187312ef2ad49eecdaf41856d50f1052fde213ad12bd7180682e98af", "license": {"spdx": ["MIT"], "repo": "AndroMikulic/thema-chat", "path": "server.js", "repo_head_hexsha": "fda8b11046d36bcdecbd87add181a43136d29812", "stack_hexsha": "ff70f5d99f98687468cdee1460789d0a7f448770", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Redirection to untrusted site", "issueDescriptionEn": "The Redirection to untrusted site checker finds instances of redirecting to a URL generated with an unvalidated external input.\nAlthough connecting to a client-provided URL is often believed to be safe, an attacker can modify the request and redirect the user to a malicious site.\nMaintain a whitelist of external site URLs and domains allowed for redirection, which needs to be checked when a user input is passed as a redirect URL.", "issueLineNumber": 45, "entireCode": "\nvar server\n\n//Requirements\nconst express = require('express')\nconst bodyParser = require('body-parser')\nconst expressip = require('express-ip')\nconst path = require('path')\nconst https = require('https')\nconst fs = require('fs')\n\nconst app = express()\nconst redirectServer = express()\nconst port = 443\n\nvar lastTopic\n\n//SSL Keys\nvar privateKey = fs.readFileSync('demo.key', 'utf8')\nvar certificate = fs.readFileSync('demo.cert', 'utf8')\n//Apply the SSL\nvar credentials = {\n\tkey: privateKey,\n\tcert: certificate\n}\n\n//Set up the app engine\napp.engine('.html', require('ejs').__express)\napp.set('view engine', 'html')\napp.use(bodyParser.urlencoded({ extended: false }))\napp.use(bodyParser.json())\napp.use(express.static(path.join(__dirname, \"/Client\")))\napp.use(expressip().getIpInfoMiddleware)\n\n//Start listening on https\n\nserver = https.createServer(credentials, app)\nserver.listen(port, function () {\n\tconsole.log(\"Listening to port \" + port)\n})\n\n//Set up http->https redirect server\n\nredirectServer.get('*', function (req, res) {\n\tres.redirect('https://' + req.headers.host + req.url)\n})\n\nredirectServer.listen(80, function () {\n\tconsole.log(\"Listening on port 80 (http) to redirect to 443 (https)\")\n})\n\napp.get('/', function (req, res) {\n\tres.render(path.join(__dirname, '/Client', '/home.html'))\n})\n\napp.get('/info', function (req, res) {\n\tres.render(path.join(__dirname, '/Client', '/info.html'))\n})\n\n//TCP Chat server setup\nvar users = []\nconst io = require('socket.io')(server, {\n\t// below are engine.IO options\n\tpingInterval: 1000,\n\tpingTimeout: 3000,\n\tcookie: false\n});\n\n//New conenction\nio.on('connection', function (socket) {\n\t//Handle disconnect\n\tsocket.on('disconnect', function () {\n\t\tif (io.sockets.connected[socket.partner] != null)\n\t\t{\n\t\t\tio.sockets.connected[socket.partner].emit(\"partnerLeft\", \"The other person left.\")\n\t\t\tio.sockets.connected[socket.partner].disconnect(true)\n\t\t} else\n\t\t{\n\t\t\tvar i = 0\n\t\t\tusers.forEach(user => {\n\t\t\t\tif (user.id === socket.id)\n\t\t\t\t{\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\ti++\n\t\t\t})\n\t\t\tusers.splice(i, 1)\n\t\t}\n\t})\n\n\tsocket.on('randomTopic', function (msg) {\n\t\tvar randomTopic\n\t\ttry\n\t\t{\n\t\t\trandomTopic = users[Math.floor(Math.random() * users.length)].topic\n\t\t} catch (e)\n\t\t{\n\t\t\trandomTopic = ''\n\t\t}\n\t\tsocket.emit('randomTopic', randomTopic)\n\t})\n\n\t//User entered topic, find a partner or put on waiting\n\tsocket.on('topic', function (topic) {\n\t\tif (topic.toString().length > 32)\n\t\t{\n\t\t\treturn;\n\t\t}\n\t\ttopic = topic.replace(//g, \">\")\n\t\tlastTopic = topic\n\t\tvar isNew = true\n\t\ttopic = topic.toLowerCase()\n\t\tlet namespace = null\n\t\tlet ns = io.of(namespace || \"/\")\n\t\tfor (var i = 0; i < users.length; i++)\n\t\t{\n\t\t\tif (users[i].topic === topic)\n\t\t\t{\n\t\t\t\tif (ns.connected[users[i].id] != null)\n\t\t\t\t{\n\t\t\t\t\tisNew = false\n\t\t\t\t\t//Found user with same topic, connecting them together\n\t\t\t\t\tsocket.partner = users[i].id\n\t\t\t\t\tns.connected[users[i].id].partner = socket.id\n\t\t\t\t\tsocket.emit(\"found\", \"\")\n\t\t\t\t\tio.to(users[i].id).emit(\"found\", \"\")\n\t\t\t\t\tusers.splice(i, 1)\n\t\t\t\t\tbreak\n\t\t\t\t} else\n\t\t\t\t{\n\t\t\t\t\tusers.splice(i, 1)\n\t\t\t\t\ti--\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t//A new topic has been added to the list\n\t\tif (isNew)\n\t\t{\n\t\t\tvar usr = {\n\t\t\t\t\"topic\": topic,\n\t\t\t\t\"ip\": socket.handshake.address,\n\t\t\t\t\"id\": socket.id\n\t\t\t}\n\t\t\tusers.push(usr)\n\t\t}\n\t})\n\n\tsocket.on('msg', function (msg) {\n\t\tmsg = msg.replace(//g, \">\")\n\t\tio.to(socket.partner).emit(\"msg\", msg)\n\t})\n\n\tsocket.on('typing', function (msg) {\n\t\tio.to(socket.partner).emit(\"typing\", msg)\n\t})\n\n\tsocket.on('stats', function (msg) {\n\t\tvar statsJSON = {}\n\t\tstatsJSON[\"usersWaiting\"] = users.length\n\t\tstatsJSON[\"lastTopic\"] = lastTopic\n\t\tsocket.emit('stats', JSON.stringify(statsJSON))\n\t})\n})\n\n//Clean up disconnected users every 10 seconds\nsetInterval(function () {\n\tvar cnt = 0\n\tfor (var i = 0; i < users.length; i++)\n\t{\n\t\tif (io.sockets.connected[users[i].id] == null)\n\t\t{\n\t\t\tif (io.sockets.connected[users[i].partner] != null)\n\t\t\t{\n\t\t\t\tio.sockets.connected[socket.partner].emit(\"partnerLeft\", \"The other person left.\")\n\t\t\t\tio.sockets.connected[socket.partner].disconnect(true)\n\t\t\t}\n\t\t\tusers.splice(i, 1)\n\t\t\ti--\n\t\t\tcnt++\n\t\t}\n\t}\n\tif (cnt > 0)\n\t{\n\t\tconsole.log(\"Cleaned up: \" + cnt)\n\t}\n}, 10 * 1000)\n\n\n/*\n Set up user input for server\n*/\n\n// Get process.stdin as the standard input object.\nvar standard_input = process.stdin\n\n// Set input character encoding.\nstandard_input.setEncoding('utf-8')\n\n// When user input data and click enter key.\nstandard_input.on('data', function (data) {\n\tconsole.log(\"Waiting users:\")\n\tconsole.log(users)\n})", "dangerousExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/dan', function (req, res) {\n5. const url = req.body.profile_url;\n6. try{\n7. res.redirect(url);\n8. }catch (e) {\n9. return res.status(500).send(\"ERROR\");\n10. }\n11. });\n12. \n13. module.exports = router;\nLine 7: A string variable URL of an unvalidated external input is used to connect.", "safeExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/safe', function (req, res) {\n5. const url = req.body.profile_url;\n6. const white_list = [\"https://www.safeurl.com\", \"https://www.verified.com\"];\n7. if (white_list.indexOf(url) < 0) {\n8. return res.status(500).send(\"url not allowed\");\n9. } else {\n10. try {\n11. res.redirect(url);\n12. } catch (e) {\n13. return res.status(500).send(\"ERROR\");\n14. }\n15. }\n16. });\n17. \n18. module.exports = router;\nLine 7-9: Validate external inputs through a filter function.", "contexts": [{"lineNo": 45, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "req"}}, {"lineNo": 45, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "redirect"}}]}} {"id": "e84aeb19fcc6cd83018a7c36e13bd4cb2dd9fe368217fa9fe2d53184eaaf6369", "license": {"spdx": ["MIT"], "repo": "AleHts29/BackEnd-CODER", "path": "Clase_10-Pug-Ejs/Ejs/index.js", "repo_head_hexsha": "9bfa2d09550dc691a02e11a3ea54b1d26af0f423", "stack_hexsha": "b3bbd04c052e88eef63b06ffa6ed73595ccd6e11", "match": "repo_path"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Redirection to untrusted site", "issueDescriptionEn": "The Redirection to untrusted site checker finds instances of redirecting to a URL generated with an unvalidated external input.\nAlthough connecting to a client-provided URL is often believed to be safe, an attacker can modify the request and redirect the user to a malicious site.\nMaintain a whitelist of external site URLs and domains allowed for redirection, which needs to be checked when a user input is passed as a redirect URL.", "issueLineNumber": 79, "entireCode": "const express = require(\"express\");\nconst methodOverride = require(\"method-override\");\n\nconst app = express();\nconst port = 8083;\n\n// midleware\napp.use(express.json());\napp.use(express.urlencoded({ extended: false }));\napp.use(express.static(__dirname + \"/public\"));\napp.use(methodOverride(\"_method\", { methods: [\"POST\", \"GET\"] }));\n\n// seteo el motro de plantillas\napp.set(\"view engine\", \"ejs\");\napp.set(\"views\", \"./views\");\n\nconst array = [\n {\n name: \" - Arturia Micro Freak\",\n price: 250,\n id: 1,\n },\n {\n name: \"\",\n price: 210,\n id: 2,\n },\n {\n name: \"\",\n price: 457,\n id: 3,\n },\n];\n\napp.get(\"/\", (req, res) => {\n res.render(\"index\", {\n texto: \"Variable desde get en index.js\",\n admin: true,\n });\n});\n\napp.get(\"/products\", (req, res) => {\n res.render(\"products\", { data: array });\n});\n\napp.get(\"/update\", (req, res) => {\n res.render(\"update\", { data: array, items: true });\n});\n\napp.get(\"/update/:id\", (req, res) => {\n let idProduct = req.params.id;\n let product = array.find((item) => item.id == idProduct);\n // res.render(\"update\", { data: product });\n console.log(product);\n\n // product = \"undefine\";\n if (!product) {\n return res.render(\"update\", {\n MSG_NOT_FOUNT: \"ID not found..\",\n items: false,\n });\n }\n // Como la busqueda devuelve un objeto, se lo encapsula en un array para no generar conficto con el fetch en products.ejs\n // Se muestra renderizado el producto buscado\n // res.render(\"update\", { data: [product], items: true });\n\n res.render(\"update\", { data: [product], items: true });\n});\n\n// app.get(\"/products/:id\", (req, res) => {\n// let { id } = req.params;\n// let product = array.find((item) => item.id == id);\n// res.send({ data: product });\n// });\n\n// Puente\napp.post(\"/update\", (req, res) => {\n let id = req.body.id;\n res.redirect(\"/update/\" + id);\n});\n\napp.put(\"/update/:id\", (req, res) => {\n console.log(\"Hola soy un PUT\");\n console.log(req.params.id); // me indica el id que es pasdado por queryParams\n let { newName, newPrice } = req.body;\n\n // Busqueda item a actualizar\n let { id } = req.params;\n let product = array.find((item) => item.id == id);\n\n // Actualiza item\n product.name = newName;\n product.price = newPrice;\n\n res.redirect(\"/products\");\n});\n\napp.all(\"*\", (req, res) => {\n res.status(404).send(\"Error: not found page\");\n});\n\napp.listen(port, () => {\n console.log(`💊 Server run on poort ${port}`);\n});", "dangerousExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/dan', function (req, res) {\n5. const url = req.body.profile_url;\n6. try{\n7. res.redirect(url);\n8. }catch (e) {\n9. return res.status(500).send(\"ERROR\");\n10. }\n11. });\n12. \n13. module.exports = router;\nLine 7: A string variable URL of an unvalidated external input is used to connect.", "safeExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/safe', function (req, res) {\n5. const url = req.body.profile_url;\n6. const white_list = [\"https://www.safeurl.com\", \"https://www.verified.com\"];\n7. if (white_list.indexOf(url) < 0) {\n8. return res.status(500).send(\"url not allowed\");\n9. } else {\n10. try {\n11. res.redirect(url);\n12. } catch (e) {\n13. return res.status(500).send(\"ERROR\");\n14. }\n15. }\n16. });\n17. \n18. module.exports = router;\nLine 7-9: Validate external inputs through a filter function.", "contexts": [{"lineNo": 78, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "req"}}, {"lineNo": 79, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "redirect"}}]}} {"id": "e54a6f90ea4e8d2bf7337539f0dadad79c62ce66603939cb0004ca36f3bff923", "license": {"spdx": ["MIT"], "repo": "krasimiruzunov/express-architecture", "path": "server/controllers/authors.js", "repo_head_hexsha": "6b0bb0d95e04c79cc4a1b72010894ad74aa1c59e", "stack_hexsha": "6e338b0d7ce93f13da98677cdec271e85e3ea28f", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Redirection to untrusted site", "issueDescriptionEn": "The Redirection to untrusted site checker finds instances of redirecting to a URL generated with an unvalidated external input.\nAlthough connecting to a client-provided URL is often believed to be safe, an attacker can modify the request and redirect the user to a malicious site.\nMaintain a whitelist of external site URLs and domains allowed for redirection, which needs to be checked when a user input is passed as a redirect URL.", "issueLineNumber": 45, "entireCode": "const fs = require('fs')\nconst Author = require('mongoose').model('Author')\nconst Book = require('mongoose').model('Book')\nconst BookStore = require('mongoose').model('BookStore')\n\nmodule.exports = {\n index: (req, res) => {\n let page = parseInt(req.query.page || 1)\n let limit = parseInt(req.session.authorsLimit || 1)\n let field = req.session.sortAuthorField || ''\n let direction = req.session.sortAuthorDirection || ''\n let options = {\n select: '-image',\n populate: 'createdBy',\n offset: (page - 1) * limit,\n limit: limit\n }\n\n if (field) {\n options.sort = { [field]: direction === 'asc' ? 1 : -1 }\n }\n\n Author.paginate({}, options).then(result => {\n let pages = Math.ceil(result.total / limit)\n res.render('authors/index', { authors: result.docs, pages: pages, page: page, authorsLimit: limit, field: field, direction: direction })\n })\n },\n create: (req, res) => {\n if (req.session.body === undefined || (req.headers.referer && req.headers.referer.indexOf('/author/create') < 0)) {\n req.session.body = null\n req.session.errors = null\n }\n res.render('authors/author', { action: { text: 'Add', url: `/author/store` }, body: req.session.body, errors: req.session.errors })\n },\n store: (req, res) => {\n req.check('firstName', 'FirstName is required').notEmpty()\n req.check('firstName', 'FirstName must be minimum 2 characters').isLength({ min: 2 })\n req.check('lastName', 'LastName is required').notEmpty()\n req.check('lastName', 'LastName must be minimum 2 characters').isLength({ min: 2 })\n\n let errors = req.validationErrors()\n if (errors) {\n req.session.body = req.body\n req.session.errors = errors\n res.redirect(req.headers.referer)\n } else {\n req.session.body = null\n req.session.errors = null\n let author = new Author({\n firstName: req.body.firstName,\n lastName: req.body.lastName,\n createdBy: req.user\n })\n if (req.file) {\n author.image = req.file.path.split('public').pop()\n }\n author.save((err) => {\n if (err) {\n req.session.body = req.body\n req.session.errors = [{ msg: 'There is already an author with this name' }]\n res.redirect(req.headers.referer)\n } else {\n req.session.body = null\n req.session.errors = null\n res.redirect('/authors')\n }\n })\n }\n },\n details: (req, res) => {\n Author.findById(req.params.id)\n .populate('createdBy')\n .exec()\n .then(author => {\n res.render('authors/details', { author: author })\n })\n },\n edit: (req, res) => {\n Author.findById(req.params.id)\n .populate('createdBy')\n .exec()\n .then(author => {\n if (req.session.body === undefined || (req.headers.referer && req.headers.referer.indexOf('/author/' + req.params.id + '/edit') < 0)) {\n req.session.body = null\n req.session.errors = null\n }\n res.render('authors/author', { author: author, action: { text: 'Update', url: `/author/${author.id}/update` }, body: req.session.body, errors: req.session.errors })\n })\n },\n update: (req, res) => {\n req.check('firstName', 'FirstName is required').notEmpty()\n req.check('firstName', 'FirstName must be minimum 2 characters').isLength({ min: 2 })\n req.check('lastName', 'LastName is required').notEmpty()\n req.check('lastName', 'LastName must be minimum 2 characters').isLength({ min: 2 })\n\n let errors = req.validationErrors()\n if (errors) {\n req.session.body = req.body\n req.session.errors = errors\n res.redirect(req.headers.referer)\n } else {\n req.session.body = null\n req.session.errors = null\n Author.findOne({\n _id: { $ne: req.params.id },\n firstName: req.body.firstName,\n lastName: req.body.lastName\n })\n .exec()\n .then(author => {\n if (author) {\n req.session.body = req.body\n req.session.errors = [{ msg: 'There is already an author with this name' }]\n res.redirect(req.headers.referer)\n } else {\n req.session.body = null\n req.session.errors = null\n Author.findById(req.params.id)\n .exec()\n .then(author => {\n if (author) {\n author.firstName = req.body.firstName\n author.lastName = req.body.lastName\n if (req.file) {\n author.image = req.file.path.split('public').pop()\n }\n author.save(err => {\n if (err) console.log(err)\n res.redirect('/authors')\n })\n }\n })\n }\n })\n }\n },\n delete: (req, res) => {\n Author.findById(req.params.id)\n .populate('createdBy')\n .exec()\n .then(author => {\n author.remove()\n Book.find()\n .select('_id')\n .where('author').equals(author)\n .then(books => {\n let bookIds = books.map((book) => { return book._id.toString() })\n if (books.length > 0) {\n BookStore.find()\n .where('books')\n .all(bookIds)\n .then(bookstores => {\n if (bookstores.length > 0) {\n for (let i = 0; i < bookstores.length; i++) {\n bookstores[i].books = bookstores[i].books.filter((book) => { return bookIds.indexOf(book.toString()) < 0 })\n bookstores[i].save((err) => {\n if (err) console.log(err)\n Book.remove()\n .where('_id').in(bookIds)\n .then(result => {\n res.redirect(req.headers.referer)\n })\n })\n }\n } else {\n Book.remove()\n .where('_id').in(bookIds)\n .then(result => {\n res.redirect(req.headers.referer)\n })\n }\n })\n } else {\n res.redirect(req.headers.referer)\n }\n })\n })\n },\n deleteImage: (req, res) => {\n Author.findById(req.params.id)\n .populate('createdBy')\n .exec()\n .then(author => {\n if (author) {\n fs.unlink('./public/' + author.image, (err) => {\n if (err) console.log(err)\n author.image = ''\n author.save(err => {\n if (err) console.log(err)\n res.send({ success: true, message: 'Image was successfully removed' })\n })\n })\n } else {\n res.send({ success: false, message: 'There is not a book with provided id' })\n }\n })\n },\n limit: (req, res) => {\n req.session.authorsLimit = req.body.limit\n res.send({ success: true, message: 'Limit was successfully set' })\n },\n sort: (req, res) => {\n req.session.sortAuthorField = req.body.field\n req.session.sortAuthorDirection = req.body.direction\n res.send({ success: true, message: 'Sort was successfully set' })\n }\n}", "dangerousExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/dan', function (req, res) {\n5. const url = req.body.profile_url;\n6. try{\n7. res.redirect(url);\n8. }catch (e) {\n9. return res.status(500).send(\"ERROR\");\n10. }\n11. });\n12. \n13. module.exports = router;\nLine 7: A string variable URL of an unvalidated external input is used to connect.", "safeExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/safe', function (req, res) {\n5. const url = req.body.profile_url;\n6. const white_list = [\"https://www.safeurl.com\", \"https://www.verified.com\"];\n7. if (white_list.indexOf(url) < 0) {\n8. return res.status(500).send(\"url not allowed\");\n9. } else {\n10. try {\n11. res.redirect(url);\n12. } catch (e) {\n13. return res.status(500).send(\"ERROR\");\n14. }\n15. }\n16. });\n17. \n18. module.exports = router;\nLine 7-9: Validate external inputs through a filter function.", "contexts": [{"lineNo": 42, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "42"}}, {"lineNo": 45, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "req"}}, {"lineNo": 45, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "redirect"}}]}} {"id": "7f83a7a5eb3322c0c22968490ceaa4690003b2a475d0f5b8b6e9a69f5b0fcd24", "license": {"spdx": ["MIT"], "repo": "DFE-Digital/login.dfe.profile", "path": "src/app/register/getComplete.js", "repo_head_hexsha": "d91efc5213530fef42de2d63a6ec12544c6e372b", "stack_hexsha": "300116bcfa53813b0a0419af136ff2210ad9ae73", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Redirection to untrusted site", "issueDescriptionEn": "The Redirection to untrusted site checker finds instances of redirecting to a URL generated with an unvalidated external input.\nAlthough connecting to a client-provided URL is often believed to be safe, an attacker can modify the request and redirect the user to a malicious site.\nMaintain a whitelist of external site URLs and domains allowed for redirection, which needs to be checked when a user input is passed as a redirect URL.", "issueLineNumber": 12, "entireCode": "const { getInvitationById } = require('./../../infrastructure/invitations');\nconst { getApplication } = require('./../../infrastructure/applications');\n\nconst getComplete = async (req, res) => {\n const invitation = await getInvitationById(req.params.id);\n\n if (!invitation) {\n return res.status(404).render('register/views/invitationNotFound');\n }\n\n if (!req.session.registration || !req.session.registration.userId) {\n return res.redirect(`/register/${req.params.id}`);\n }\n\n const client = await getApplication(invitation.origin.clientId, req.id);\n res.render('register/views/complete', {\n clientName: client.name,\n redirectUri: invitation.origin.redirectUri,\n hideNav: true,\n title: 'Registration complete - DfE Sign-in',\n blacklisted: req.query && req.query.bklisted === 'true' ? true : false\n });\n};\n\nmodule.exports = getComplete;", "dangerousExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/dan', function (req, res) {\n5. const url = req.body.profile_url;\n6. try{\n7. res.redirect(url);\n8. }catch (e) {\n9. return res.status(500).send(\"ERROR\");\n10. }\n11. });\n12. \n13. module.exports = router;\nLine 7: A string variable URL of an unvalidated external input is used to connect.", "safeExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/safe', function (req, res) {\n5. const url = req.body.profile_url;\n6. const white_list = [\"https://www.safeurl.com\", \"https://www.verified.com\"];\n7. if (white_list.indexOf(url) < 0) {\n8. return res.status(500).send(\"url not allowed\");\n9. } else {\n10. try {\n11. res.redirect(url);\n12. } catch (e) {\n13. return res.status(500).send(\"ERROR\");\n14. }\n15. }\n16. });\n17. \n18. module.exports = router;\nLine 7-9: Validate external inputs through a filter function.", "contexts": [{"lineNo": 11, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "11"}}, {"lineNo": 12, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "req"}}, {"lineNo": 12, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "redirect"}}]}} {"id": "8721f29ae79d07bd5976efbff3e30162934def5b9d8efbe84568c52a3cc80544", "license": {"spdx": ["MIT"], "repo": "ctzoo/myinfo_server", "path": "src/app.js", "repo_head_hexsha": "c2970ed965ebae1eec42a6a5abd62b727a87a6e4", "stack_hexsha": "b6a7d9ff7146a69e08d9cca416e3d76a19fb1976", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Redirection to untrusted site", "issueDescriptionEn": "The Redirection to untrusted site checker finds instances of redirecting to a URL generated with an unvalidated external input.\nAlthough connecting to a client-provided URL is often believed to be safe, an attacker can modify the request and redirect the user to a malicious site.\nMaintain a whitelist of external site URLs and domains allowed for redirection, which needs to be checked when a user input is passed as a redirect URL.", "issueLineNumber": 46, "entireCode": "const express = require('express');\nconst bodyParser = require('body-parser');\nconst oauthServer = require('oauth2-server');\nconst jwt = require('jsonwebtoken');\nconst myInfoApi = require('./api');\nconst getClients = require('./data').getClients;\nconst getTemplate = require('./data').getTemplate;\nconst contentPath = require('config').get('content');\nconst oauthConfig = require('config').get('oauth');\nconst emitter = require('./emitter')\n\nconst app = express();\nconst router = express();\n\nrouter.use(\n bodyParser.urlencoded({\n extended: true,\n })\n);\n\nrouter.use(bodyParser.json());\n\nrouter.oauth = oauthServer({\n model: require('./model'),\n grants: ['client_credentials'],\n accessTokenLifetime: oauthConfig.expire,\n});\n\nrouter.all('/oauth/token', router.oauth.grant());\n\nrouter.get('/', router.oauth.authorise(), (req, res) => {\n // 回调增加state\n const user = req.user;\n emitter.emit('info', `Client Request query data: ${user.clientId} -> ${JSON.stringify(req.query)}`)\n const state = jwt.sign({\n clientId: user.clientId,\n templateId: req.query.templateId,\n state: req.query.state\n },\n oauthConfig.stateSecret\n );\n const template = getTemplate()[req.query.templateId];\n const loginType = req.query.loginType;\n const authoriseUrl = myInfoApi.getAuthoriseUrl(state, user.purpose, template, loginType);\n emitter.emit('info', `Client Request redirect: ${user.clientId} -> ${authoriseUrl}`)\n res.redirect(authoriseUrl);\n});\n\nrouter.get('/callback', (req, res) => {\n emitter.emit('info', `Myinfo Callback Start for Client---------------------------------------`)\n const data = req.query;\n emitter.emit('info', `Myinfo Callback Get data: ${JSON.stringify(data)}`)\n try {\n emitter.emit('info', `Myinfo Callback Verify state data start: ${JSON.stringify(data)}`)\n const state = jwt.verify(data.state, oauthConfig.stateSecret);\n emitter.emit('info', `Myinfo Callback Verify state data success: ${JSON.stringify(state)}`)\n const users = getClients().filter(item => item.clientId === state.clientId);\n const template = getTemplate()[state.templateId];\n if (!users.length) {\n emitter.emit('warn', `Myinfo Callback Not find client[${state.clientId}]`);\n res.send({\n status: 'ERROR',\n msg: `NO CLIENT[${state.clientId}] INFORMATION`,\n });\n } else if (!template) {\n emitter.emit('warn', `Myinfo Callback Not find template[${state.templateId}]`);\n const user = users[0];\n const errMsg = {\n status: 'ERROR',\n msg: `NO TEMPLATE[${state.templateId}] INFORMATION`\n }\n res.redirect(\n `${user.redirectUrl}?state=${state.state}&data=${jwt.sign(errMsg, user.clientSecret)}`\n );\n } else if (!data.code) {\n emitter.emit('warn', `Myinfo Callback Not Return myinfo authorise codo[${JSON.stringify(data)}]`);\n const user = users[0];\n const errMsg = {\n status: 'ERROR',\n msg: 'NO FOUND myinfo authorise code'\n }\n res.redirect(\n `${user.redirectUrl}?state=${state.state}&data=${jwt.sign(errMsg, user.clientSecret)}`\n );\n } else {\n emitter.emit('info', `Myinfo Callback Success`);\n const user = users[0];\n emitter.emit('info', `Myinfo Server Start Get Token for Myinfo---------------------------------------`)\n myInfoApi\n .getTokenApi(data.code, template)\n .then(token => {\n emitter.emit('info', `Myinfo Server Get Token Success: ${JSON.stringify(token)}`)\n emitter.emit('info', `Myinfo Server Start Get Person for Myinfo---------------------------------------`)\n return myInfoApi.getPersonApi(token.access_token, template)\n })\n .then(data => {\n // Myinfo平台接口记录来源系统、使用目的、客户NRIC/FIN, 提取数据的栏位名、提取时间\n emitter.emit('person', {\n client: user.clientId,\n purpose: user.purpose,\n nric: data.msg.uinfin,\n attributes: template.attributes\n })\n emitter.emit('info', `Myinfo Server Get Person Success: ${state.state}`)\n res.redirect(\n `${user.redirectUrl}?state=${state.state}&data=${jwt.sign(data, user.clientSecret)}`\n );\n })\n .catch(e => {\n emitter.emit('warn', `Myinfo Server Get Person Data Failed: ${state.state} -> ${JSON.stringify(e)}`)\n if (e.status) {\n res.redirect(\n `${user.redirectUrl}?state=${state.state}&data=${jwt.sign({ status: e.status, msg: e.msg }, user.clientSecret)}`\n );\n } else {\n res.redirect(\n `${user.redirectUrl}?state=${state.state}&data=${jwt.sign({ status: \"ERROR\", msg: \"Network error\" }, user.clientSecret)}`\n );\n }\n });\n }\n } catch (error) {\n emitter.emit('warn', `Myinfo Server Error: Client Query -> [${JSON.stringify(data)}], Error Info -> [${JSON.stringify(error)}]`);\n res.send({\n status: 'ERROR',\n msg: 'Myinfo Authorization error'\n });\n }\n});\n\nrouter.use(router.oauth.errorHandler());\n\napp.use(`/${contentPath}`, router);\n\napp.listen(3001);", "dangerousExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/dan', function (req, res) {\n5. const url = req.body.profile_url;\n6. try{\n7. res.redirect(url);\n8. }catch (e) {\n9. return res.status(500).send(\"ERROR\");\n10. }\n11. });\n12. \n13. module.exports = router;\nLine 7: A string variable URL of an unvalidated external input is used to connect.", "safeExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/safe', function (req, res) {\n5. const url = req.body.profile_url;\n6. const white_list = [\"https://www.safeurl.com\", \"https://www.verified.com\"];\n7. if (white_list.indexOf(url) < 0) {\n8. return res.status(500).send(\"url not allowed\");\n9. } else {\n10. try {\n11. res.redirect(url);\n12. } catch (e) {\n13. return res.status(500).send(\"ERROR\");\n14. }\n15. }\n16. });\n17. \n18. module.exports = router;\nLine 7-9: Validate external inputs through a filter function.", "contexts": [{"lineNo": 43, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "req"}}, {"lineNo": 44, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "getAuthoriseUrl"}}, {"lineNo": 44, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 46, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "redirect"}}]}} {"id": "b7f1699452a468653c26056fd166128f852d025b1347cf05b63e0d2afa5e27b8", "license": {"spdx": ["MIT", "Unlicense"], "repo": "thangtyt/orama", "path": "core/modules/blog/backend/controllers/page.js", "repo_head_hexsha": "f5214f60cfe24a422e67a60b00cd2576dc281e07", "stack_hexsha": "ceb278252e8e971c3f54e1e9e7d7ea91f3993f33", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Redirection to untrusted site", "issueDescriptionEn": "The Redirection to untrusted site checker finds instances of redirecting to a URL generated with an unvalidated external input.\nAlthough connecting to a client-provided URL is often believed to be safe, an attacker can modify the request and redirect the user to a malicious site.\nMaintain a whitelist of external site URLs and domains allowed for redirection, which needs to be checked when a user input is passed as a redirect URL.", "issueLineNumber": 202, "entireCode": "'use strict';\n\nlet promise = require('bluebird');\n\nlet slug = require('slug');\nlet formidable = require('formidable');\n//let sequelize = require('sequelize');\npromise.promisifyAll(formidable);\n\nlet _module = new BackModule;\nlet route = 'blog';\n\n_module.list = function (req, res) {\n // Add buttons\n res.locals.createButton = __acl.addButton(req, route, 'page_create', '/admin/blog/pages/create');\n res.locals.deleteButton = __acl.addButton(req, route, 'page_delete');\n\n // Get current page and default sorting\n let page = req.params.page || 1;\n let column = req.params.sort || 'created_by';\n let order = req.params.order || 'desc';\n res.locals.root_link = '/admin/blog/pages/page/' + page + '/sort';\n\n // Store search data to session\n let session_search = {};\n if (req.session.search) {\n session_search = req.session.search;\n }\n session_search[route + '_page_list'] = req.url;\n req.session.search = session_search;\n\n // Config columns\n let filter = __.createFilter(req, res, route, '/admin/blog/pages', column, order, [\n {\n column: \"id\",\n width: '1%',\n header: \"\",\n type: 'checkbox'\n },\n {\n column: 'title',\n width: '25%',\n header: __.t('all_table_column_title'),\n link: '/admin/blog/pages/{id}',\n acl: 'blog.post_edit',\n filter: {\n data_type: 'string'\n }\n },\n {\n column: 'alias',\n width: '25%',\n header: __.t('all_table_column_alias'),\n filter: {\n data_type: 'string'\n }\n },\n {\n column: 'user.display_name',\n width: '20%',\n header: __.t('all_table_column_author'),\n filter: {\n data_type: 'string',\n filter_key: 'created_by'\n }\n },\n {\n column: 'created_at',\n width: '15%',\n header: __.t('m_blog_backend_page_filter_column_created_date'),\n type: 'datetime',\n filter: {\n data_type: 'datetime',\n filter_key: 'created_at'\n }\n },\n {\n column: 'published',\n width: '10%',\n header: __.t('all_table_column_status'),\n type: 'custom',\n alias: {\n \"1\": \"Publish\",\n \"0\": \"Draft\"\n },\n filter: {\n type: 'select',\n filter_key: 'published',\n data_source: [\n {\n name: 'Publish',\n value: 1\n },\n {\n name: 'Draft',\n value: 0\n }\n ],\n display_key: 'name',\n value_key: 'value'\n }\n }\n ], \" AND type='page' \");\n\n // List pages\n __models.post.findAndCountAll({\n include: [\n {\n model: __models.user, attributes: ['display_name'],\n where: ['1 = 1']\n }\n ],\n where: filter.values,\n order: filter.sort,\n limit: __config.pagination.number_item,\n offset: (page - 1) * __config.pagination.number_item\n }).then(function (results) {\n let totalPage = Math.ceil(results.count / __config.pagination.number_item);\n\n // Render view\n _module.render(req, res, 'page/index', {\n title: __.t('m_blog_backend_page_render_title'),\n totalPage: totalPage,\n items: results.rows,\n currentPage: page\n });\n }).catch(function (error) {\n req.flash.error('Name: ' + error.name + '
    ' + 'Message: ' + error.message);\n\n // Render view if has error\n _module.render(req, res, 'page/index', {\n title: __.t('m_blog_backend_page_render_title'),\n totalPage: 1,\n items: null,\n currentPage: page\n });\n });\n};\n\n_module.listAll = function (req, res) {\n let query = req.param('query') || '';\n query = query.toLowerCase();\n\n __models.post.findAll({\n where: [\"type='page' AND LOWER(title) like '%\" + query + \"%'\"],\n order: 'title asc'\n }).then(function (tags) {\n let data = [];\n if (tags.length > 0) {\n tags.forEach(function (t) {\n data.push({value: t.title, data: t.id});\n });\n }\n let result = {query: query, suggestions: data};\n res.json(result);\n });\n};\n\n_module.redirectToView = function (req, res) {\n __models.post.find({\n where: {\n alias: req.params.name\n }\n }).then(function (page) {\n res.redirect('/admin/blog/pages/' + page.id);\n }).catch(function (err) {\n res.redirect('/404.html');\n })\n};\n\n_module.view = function (req, res) {\n // Add button\n let back_link = '/admin/blog/pages/page/1';\n let search_params = req.session.search;\n if (search_params && search_params[route + '_page_list']) {\n back_link = '/admin' + search_params[route + '_page_list'];\n }\n res.locals.backButton = __acl.addButton(req, route, 'page_index', back_link);\n res.locals.saveButton = __acl.addButton(req, route, 'page_edit');\n res.locals.deleteButton = __acl.addButton(req, route, 'page_delete');\n\n promise.all([\n __models.user.findAll({\n order: \"id asc\"\n }),\n __models.post.find({\n include: [__models.user],\n where: {\n id: req.params.cid,\n type: 'page'\n }\n })\n ]).then(function (results) {\n res.locals.viewButton = results[1].alias;\n _module.render(req, res, 'page/new', {\n title: __.t('m_blog_backend_page_render_update'),\n users: results[0],\n page: results[1]\n });\n }).catch(function (error) {\n req.flash.error('Name: ' + error.name + '
    ' + 'Message: ' + error.message);\n res.redirect(back_link);\n });\n};\n\n_module.update = function (req, res, next) {\n // Add button\n let back_link = '/admin/blog/pages/page/1';\n let search_params = req.session.search;\n if (search_params && search_params[route + '_page_list']) {\n back_link = '/admin' + search_params[route + '_page_list'];\n }\n res.locals.saveButton = __acl.addButton(req, route, 'page_edit');\n res.locals.backButton = __acl.addButton(req, route, 'page_index', back_link);\n res.locals.deleteButton = __acl.addButton(req, route, 'page_delete');\n\n let data = req.body;\n if (!data.published) data.published = 0;\n data.modified_date = data.modified_date_gmt = Date.now();\n\n __models.post.find({\n include: [__models.user],\n where: {\n id: req.params.cid\n }\n }).then(function (page) {\n page.updateAttributes(data).then(function () {\n res.locals.viewButton = page.alias;\n req.messages = req.flash.success(__.t('m_blog_backend_page_flash_update_success'));\n _module.render(req, res, 'page/new', {\n title: __.t('m_blog_backend_page_render_update'),\n page: page\n });\n });\n }).catch(function (error) {\n req.flash.error('Name: ' + error.name + '
    ' + 'Message: ' + error.message);\n res.redirect(back_link);\n });\n};\n\n_module.create = function (req, res) {\n // Add button\n let back_link = '/admin/blog/pages/page/1';\n let search_params = req.session.search;\n if (search_params && search_params[route + '_page_list']) {\n back_link = '/admin' + search_params[route + '_page_list'];\n }\n res.locals.saveButton = __acl.addButton(req, route, 'page_create');\n res.locals.backButton = __acl.addButton(req, route, 'page_index', back_link);\n\n __models.user.findAll({\n order: \"id asc\"\n }).then(function (results) {\n _module.render(req, res, 'page/new', {\n title: __.t('m_blog_backend_page_render_create'),\n users: results\n });\n }).catch(function (error) {\n req.flash.error('Name: ' + error.name + '
    ' + 'Message: ' + error.message);\n res.redirect(back_link);\n });\n};\n\n_module.save = function (req, res) {\n // Add button\n let back_link = '/admin/blog/pages/page/1';\n let search_params = req.session.search;\n if (search_params && search_params[route + '_page_list']) {\n back_link = '/admin' + search_params[route + '_page_list'];\n }\n res.locals.saveButton = __acl.addButton(req, route, 'page_edit');\n res.locals.backButton = __acl.addButton(req, route, 'page_index', back_link);\n res.locals.deleteButton = __acl.addButton(req, route, 'page_delete');\n\n let data = req.body;\n data.alias = slug(data.title).toLowerCase();\n data.created_by = req.user.id;\n data.type = 'page';\n if (!data.published) data.published = 0;\n\n __models.post.create(data).then(function (page) {\n req.flash.success(__.t('m_blog_backend_page_flash_create_success'));\n res.redirect('/admin/blog/pages/' + page.id);\n }).catch(function (error) {\n req.flash.error('Name: ' + error.name + '
    ' + 'Message: ' + error.message);\n res.redirect(back_link);\n });\n};\n\n_module.delete = function (req, res) {\n __models.post.destroy({\n where: {\n id: {\n \"in\": req.body.ids.split(',')\n }\n }\n }).then(function () {\n req.flash.success(__.t('m_blog_backend_page_flash_delete_success'));\n res.send(200);\n });\n};\n\nmodule.exports = _module;", "dangerousExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/dan', function (req, res) {\n5. const url = req.body.profile_url;\n6. try{\n7. res.redirect(url);\n8. }catch (e) {\n9. return res.status(500).send(\"ERROR\");\n10. }\n11. });\n12. \n13. module.exports = router;\nLine 7: A string variable URL of an unvalidated external input is used to connect.", "safeExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/safe', function (req, res) {\n5. const url = req.body.profile_url;\n6. const white_list = [\"https://www.safeurl.com\", \"https://www.verified.com\"];\n7. if (white_list.indexOf(url) < 0) {\n8. return res.status(500).send(\"url not allowed\");\n9. } else {\n10. try {\n11. res.redirect(url);\n12. } catch (e) {\n13. return res.status(500).send(\"ERROR\");\n14. }\n15. }\n16. });\n17. \n18. module.exports = router;\nLine 7-9: Validate external inputs through a filter function.", "contexts": [{"lineNo": 174, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "req"}}, {"lineNo": 175, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "175"}}, {"lineNo": 176, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 202, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "redirect"}}]}} {"id": "4d213097c1039c4b2c29e194db3ba97c05f02606dd076cd683f48ab83e22b25d", "license": {"spdx": ["MIT"], "repo": "CrypticPoet/SingleSignOn", "path": "src/routes/auth.js", "repo_head_hexsha": "06e028c4f69daf962bdc2e90d883d2c213b44afa", "stack_hexsha": "3756241ceef12d95f19d98edf2f868c7d9662e96", "match": "repo_path"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Redirection to untrusted site", "issueDescriptionEn": "The Redirection to untrusted site checker finds instances of redirecting to a URL generated with an unvalidated external input.\nAlthough connecting to a client-provided URL is often believed to be safe, an attacker can modify the request and redirect the user to a malicious site.\nMaintain a whitelist of external site URLs and domains allowed for redirection, which needs to be checked when a user input is passed as a redirect URL.", "issueLineNumber": 223, "entireCode": "import express from 'express';\nimport { verify, decode } from 'jsonwebtoken';\nimport bcrypt from 'bcryptjs';\nimport {\n verifyToken,\n createJWTCookie,\n socialAuthenticate,\n sendVerificationEmail,\n sendPassResetEmail,\n linkSocial,\n} from '../utils/utils';\nimport {\n accessTokenName,\n refreshTokenName,\n profileNotFoundMsg,\n accountExists,\n publicKey,\n noRedirectState,\n} from '../config/keys';\nimport { Client, User } from '../models/user';\n\nconst router = express.Router();\nconst passport = require('passport');\nconst HttpsProxyAgent = require('https-proxy-agent');\n\nconst axiosDefaultConfig = {\n proxy: false,\n httpsAgent:\n process.env.NODE_ENV !== 'DEV'\n ? new HttpsProxyAgent('http://devclub.iitd.ac.in:3128')\n : null,\n};\nconst axios = require('axios').create(axiosDefaultConfig);\nconst qs = require('qs');\n// post route to check validity of tokens, clients will hit this route.\nrouter.post('/refresh-token', async (req, res) => {\n const token = req.body[accessTokenName];\n const refreshToken = req.body[refreshTokenName];\n try {\n const user = await verifyToken(req, res, true, 0, token, refreshToken);\n user.password = ;\n return res.status(200).json({\n user,\n });\n } catch (error) {\n return res.status(401).json({\n err: true,\n msg: 'Error, token not valid',\n });\n }\n});\n\nrouter.get('/email/verify/token', async (req, res) => {\n try {\n const { token } = req.query;\n const decoded = await verify(token, publicKey, {\n algorithms: ['RS256'],\n });\n const user = await User.findById(decoded.id);\n user.isverified = true;\n await user.save();\n res.render('account_verified');\n } catch (error) {\n console.log(error);\n res.clearCookie(accessTokenName, {\n domain: process.env.NODE_ENV !== 'DEV' ? 'devclub.in' : null,\n });\n res.clearCookie(refreshTokenName, {\n domain: process.env.NODE_ENV !== 'DEV' ? 'devclub.in' : null,\n });\n res.render('account_verified', { error: true });\n }\n});\n\nrouter.get('/email/verify', (req, res) => {\n res.render('email_verify');\n});\n\nrouter.post('/email/verify', async (req, res) => {\n try {\n const { email } = req.body;\n const user = await User.findOne({\n email,\n });\n if (!user)\n return res.render('email_verify', {\n message: 'Email Address not registered',\n error: true,\n });\n if (user.isverified) {\n return res.render('email_verify', {\n message:\n 'Your account is already verified, Please login to continue',\n error: true,\n });\n }\n sendVerificationEmail(user);\n return res.render('email_verify', {\n message: 'A verification email has been sent to your inbox!',\n error: true,\n });\n } catch (error) {\n res.render('email_verify', {\n message: 'Email Address not registered',\n error: true,\n });\n }\n});\n\nrouter.get('/password/reset/token', async (req, res) => {\n try {\n const { token } = req.query;\n const decoded = await verify(token, publicKey, {\n algorithms: ['RS256'],\n });\n const user = await User.findById(decoded.id);\n user.password = await bcrypt.hash(decoded.newPass, 10);\n await user.save();\n res.render('login', {\n message: 'Password reset successfully!',\n error: false,\n serviceURL: '',\n });\n } catch (error) {\n console.log(error);\n res.clearCookie(accessTokenName, {\n domain: process.env.NODE_ENV !== 'DEV' ? 'devclub.in' : null,\n });\n res.clearCookie(refreshTokenName, {\n domain: process.env.NODE_ENV !== 'DEV' ? 'devclub.in' : null,\n });\n res.render('login', {\n message: 'Invalid Token. Please try resetting your password again',\n error: true,\n serviceURL: '',\n });\n }\n});\nrouter.get('/password/reset', (req, res) => {\n res.render('pass_forgot');\n});\nrouter.post('/password/reset', async (req, res) => {\n try {\n const { email, newPass } = req.body;\n const user = await User.findOne({\n email,\n });\n if (!user)\n return res.render('pass_forgot', {\n message: 'Email Address not registered',\n error: true,\n });\n if (!newPass)\n return res.render('pass_forgot', {\n message: 'New Password not supplied',\n error: true,\n });\n sendPassResetEmail(user, newPass);\n return res.render('pass_forgot', {\n message: 'A password reset email has been sent to your inbox!',\n error: false,\n });\n } catch (error) {\n res.render('pass_forgot', {\n message: 'Email Address not registered',\n error: true,\n });\n }\n});\n\nexport default router;\n\nrouter.get('/google', (req, res, next) => {\n passport.authenticate('google', {\n scope: ['profile', 'email'],\n state: req.query.serviceURL,\n })(req, res, next);\n});\n\nrouter.get('/facebook', (req, res, next) => {\n passport.authenticate('facebook', {\n authType: 'rerequest',\n state: req.query.serviceURL,\n scope: 'email',\n })(req, res, next);\n});\n\nrouter.get('/github', (req, res, next) => {\n passport.authenticate('github', {\n state: req.query.serviceURL,\n scope: 'user:email',\n })(req, res, next);\n});\n\nrouter.get(\n '/:provider/callback',\n (req, res, next) => {\n passport.authenticate(req.params.provider, {\n session: false,\n failureRedirect: '/user/login',\n failWithError: true,\n })(req, res, next);\n },\n (err, req, res, next) => {\n if (err) return res.redirect('/user/login');\n next();\n },\n async (req, res) => {\n createJWTCookie(req.user, res);\n createJWTCookie(req.user, res, refreshTokenName);\n if (req.authInfo.message === profileNotFoundMsg) {\n return res.render('confirm', { user: req.user });\n }\n if (req.authInfo.message === accountExists) {\n return res.render('settings', {\n messages: [{ message: accountExists, error: true }],\n });\n }\n const { state: serviceURL } = req.query;\n\n if (typeof serviceURL !== 'undefined' && serviceURL) {\n // render homepage to store token and then redirect with serviceURL\n return res.redirect(`/redirecting?serviceURL=${serviceURL}`);\n }\n return res.redirect('/');\n }\n);\n\nrouter.get('/iitd', (req, res) => {\n const { serviceURL } = req.query;\n let state;\n if (!serviceURL) state = noRedirectState;\n else state = serviceURL;\n return res.redirect(\n `https://oauth.iitd.ac.in/authorize.php?response_type=code&client_id=${process.env.IITD_CLIENT_ID}&state=${state}`\n );\n});\n\nrouter.get('/iitd/confirm', async (req, res) => {\n try {\n // console.log('Code: ', req.query.code);\n const res1 = await axios.post('https://oauth.iitd.ac.in/token.php', {\n client_id: process.env.IITD_CLIENT_ID,\n client_secret: process.env.IITD_CLIENT_SECRET,\n grant_type: 'authorization_code',\n code: req.query.code,\n });\n const { access_token } = res1.data;\n // console.log('Recieved access token: ', access_token);\n\n const res2 = await axios.post(\n 'https://oauth.iitd.ac.in/resource.php',\n qs.stringify({\n access_token,\n }),\n {\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n }\n );\n const userData = res2.data;\n // console.log('Recieved User Data: ', userData);\n const iitdCallback = async (\n err = null,\n user = null,\n authInfo = null\n ) => {\n if (err || !user) {\n console.log(err, user);\n return res.sendStatus(500);\n }\n\n if (!user.roles.includes('iitd_user')) {\n user.roles.push('iitd_user');\n await user.save();\n }\n createJWTCookie(user, res);\n createJWTCookie(user, res, refreshTokenName);\n if (authInfo && authInfo.message === profileNotFoundMsg) {\n return res.render('confirm', { user });\n }\n if (authInfo && authInfo.message === accountExists) {\n return res.render('settings', {\n messages: [\n {\n message: accountExists,\n error: true,\n },\n ],\n });\n }\n const { state } = req.query;\n\n if (typeof state !== 'undefined' && state) {\n // render homepage to store token and then redirect with serviceURL\n return res.redirect(`/redirecting?serviceURL=${state}`);\n }\n return res.redirect('/');\n };\n try {\n return await linkSocial(\n req.cookies[accessTokenName],\n 'iitd',\n userData.uniqueiitdid,\n userData.email,\n iitdCallback\n );\n } catch (error) {\n return socialAuthenticate(\n 'iitd',\n iitdCallback,\n userData.uniqueiitdid,\n userData.name,\n '',\n userData.email,\n 'iitd_user'\n );\n }\n } catch (error) {\n console.log(error);\n return res.sendStatus(500);\n }\n});\n\nrouter.get('/clientVerify', async (req, res) => {\n const { q } = req.query;\n\n try {\n const user = await verifyToken(req, res);\n const { clientId } = decode(q).data;\n const client = await Client.findById(clientId);\n if (!client) {\n return res.status(400).json({\n err: true,\n msg: 'No client found',\n });\n }\n\n verify(q, client.access_token, {\n algorithms: ['HS256'],\n });\n\n const token = createJWTCookie(user, res, refreshTokenName);\n res.cookie('_rememberme', token, {\n httpOnly: false,\n domain: process.env.NODE_ENV !== 'DEV' ? 'devclub.in' : null,\n secure: process.env.NODE_ENV !== 'DEV',\n });\n return res.status(200).json({\n err: false,\n msg: 'Client verified successfully',\n });\n } catch (error) {\n console.log(error);\n return res.status(401).json({\n err: true,\n msg: 'Unauthorized Client',\n });\n }\n});\n\nrouter.post(`/sudoTestCommand/:secret/makeadminforclient`, async (req, res) => {\n if (req.params.secret === process.env.MY_SECRET) {\n try {\n const { email } = req.body;\n if (!email)\n return res.status(400).json({\n message: 'Email not specified!',\n });\n const result = await User.findOne({ email });\n\n result.isverified = true;\n result.roles.push('admin');\n\n await User.findOneAndUpdate({ email }, result);\n res.status(200).json({\n message: 'action completed',\n });\n } catch (err) {\n res.status(500).json({\n message: 'unable to process request',\n });\n }\n } else {\n res.status(401).json({\n message: 'Unauthorized',\n });\n }\n});", "dangerousExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/dan', function (req, res) {\n5. const url = req.body.profile_url;\n6. try{\n7. res.redirect(url);\n8. }catch (e) {\n9. return res.status(500).send(\"ERROR\");\n10. }\n11. });\n12. \n13. module.exports = router;\nLine 7: A string variable URL of an unvalidated external input is used to connect.", "safeExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/safe', function (req, res) {\n5. const url = req.body.profile_url;\n6. const white_list = [\"https://www.safeurl.com\", \"https://www.verified.com\"];\n7. if (white_list.indexOf(url) < 0) {\n8. return res.status(500).send(\"url not allowed\");\n9. } else {\n10. try {\n11. res.redirect(url);\n12. } catch (e) {\n13. return res.status(500).send(\"ERROR\");\n14. }\n15. }\n16. });\n17. \n18. module.exports = router;\nLine 7-9: Validate external inputs through a filter function.", "contexts": [{"lineNo": 221, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "221"}}, {"lineNo": 223, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "serviceURL"}}, {"lineNo": 223, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "redirect"}}]}} {"id": "9c24606d66aa1bd411f36d852ef6b1bdf2b12b9e8a1f3cd831545a1ed368258d", "license": {"spdx": ["CC0-1.0"], "repo": "konklone/oversight.garden", "path": "app/routes.js", "repo_head_hexsha": "1ffa7b4f29cd07f5458e653b0d9c3ff0c05aee00", "stack_hexsha": "8aef36ee3f728761479e03b83a44889357d88bbe", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Redirection to untrusted site", "issueDescriptionEn": "The Redirection to untrusted site checker finds instances of redirecting to a URL generated with an unvalidated external input.\nAlthough connecting to a client-provided URL is often believed to be safe, an attacker can modify the request and redirect the user to a malicious site.\nMaintain a whitelist of external site URLs and domains allowed for redirection, which needs to be checked when a user input is passed as a redirect URL.", "issueLineNumber": 171, "entireCode": "\"use strict\";\n\n// boilerplate includes\nvar config = require(\"../config/config\"),\n es = require(\"./boot\").es,\n helpers = require(\"./helpers\"),\n fs = require(\"fs\"),\n async = require(\"async\");\n\n// Number of reports per request for web page results and RSS results\nvar HTML_SIZE = 10;\nvar XML_SIZE = 50;\n\nmodule.exports = function(app) {\n\n // The homepage. A temporary search page.\n app.get('/', function(req, res) {\n res.render(\"index.html\", {});\n });\n\n app.get('/about', function(req, res) {\n res.redirect(302, 'https://sunlightfoundation.com/blog/2014/11/07/opengov-voices-opening-up-government-reports-through-teamwork-and-open-data/');\n });\n\n app.get('/reports', function(req, res) {\n var query_obj = parse_search_query(req.query, HTML_SIZE);\n\n search(query_obj).then(function(results) {\n res.render(\"reports.html\", {\n results: results,\n query_obj: query_obj,\n });\n }, function(err) {\n console.log(\"Noooo!\\n\\n\" + err);\n\n res.status(500);\n res.render(\"reports.html\", {\n results: null,\n query_obj: {},\n });\n });\n });\n\n app.get('/reports/featured', function(req, res) {\n var query_obj = parse_search_query(req.query, HTML_SIZE);\n query_obj.featured = true;\n\n search(query_obj).then(function(results) {\n res.render(\"reports.html\", {\n results: results,\n query_obj: query_obj,\n });\n }, function(err) {\n console.log(\"Noooo!\\n\\n\" + err);\n\n res.status(500);\n res.render(\"reports.html\", {\n results: null,\n query_obj: {},\n });\n });\n });\n\n app.get('/reports/unreleased', function(req, res) {\n var query_obj = parse_search_query(req.query, HTML_SIZE);\n query_obj.unreleased = true;\n\n search(query_obj).then(function(results) {\n res.render(\"reports.html\", {\n results: results,\n query_obj: query_obj,\n });\n }, function(err) {\n console.log(\"Noooo!\\n\\n\" + err);\n\n res.status(500);\n res.render(\"reports.html\", {\n results: null,\n query_obj: {},\n });\n });\n });\n\n app.get('/reports.xml', function(req, res) {\n var query_obj = parse_search_query(req.query, XML_SIZE);\n\n search(query_obj).then(function(results) {\n res.type(\"atom\");\n res.render(\"reports.xml.ejs\", {\n results: results,\n query_obj: query_obj,\n self_url: req.url\n });\n }, function(err) {\n console.log(\"Noooo!\\n\\n\" + err);\n\n res.status(500);\n res.type(\"text\");\n res.send(\"Server error\");\n });\n });\n\n\n app.get('/inspectors', function(req, res) {\n res.render(\"inspectors.html\");\n });\n\n app.get('/inspectors/:inspector', function(req, res) {\n var metadata = helpers.inspector_info(req.params.inspector);\n\n if (metadata) {\n var inspectorReportCount = null;\n if (helpers.counts.inspectors)\n inspectorReportCount = helpers.counts.inspectors[req.params.inspector] || 0;\n\n var query_obj = {\n query: \"*\",\n inspector: [req.params.inspector],\n page: 1,\n featured: false,\n unreleased: false,\n foiad: false,\n published_on_start: null,\n published_on_end: null,\n size: HTML_SIZE\n };\n search(query_obj).then(function(results) {\n res.render(\"inspector.html\", {\n inspector: req.params.inspector,\n metadata: metadata,\n inspectorReportCount: inspectorReportCount,\n results: results\n });\n }, function(err) {\n console.log(\"Noooo!\\n\\n\" + err);\n res.render(\"inspector.html\", {\n inspector: req.params.inspector,\n metadata: metadata,\n inspectorReportCount: inspectorReportCount,\n results: []\n });\n });\n\n } else {\n res.status(404);\n res.render(\"inspector.html\", {metadata: null});\n }\n });\n\n app.get('/reports/:inspector/:report_id', function(req, res) {\n get(req.params.inspector, req.params.report_id).then(function(result) {\n\n var noindex = noindexed(result._source);\n\n // It's in a tag as well, but just to be thorough.\n if (noindex)\n res.set(\"X-Robots-Tag\", \"noindex\");\n\n res.render(\"report.html\", {\n report: result._source,\n noindex: noindex\n });\n }, function(err) {\n console.log(\"Nooooo!\\n\\n\" + err);\n res.status(500);\n res.render(\"report.html\", {report: null});\n });\n });\n\n app.get('/report/:inspector/:report_id', function(req, res) {\n res.redirect(301, \"/reports/\" +\n encodeURIComponent(req.params.inspector) +\n \"/\" +\n encodeURIComponent(req.params.report_id));\n });\n\n app.get('/dashboard', function(req, res) {\n es.search({\n index: config.elasticsearch.index_dashboard,\n type: 'scraper_info',\n body: {\n \"size\": 100,\n \"query\": {\n \"match_all\": {}\n },\n \"sort\": [\n {\n \"severity\": \"desc\",\n },\n {\n \"_uid\": \"asc\"\n }\n ]\n }\n }).then(function(results) {\n res.render(\"dashboard.html\", {results: results});\n }, function(err) {\n console.log(\"Nooooo!\\n\\n\" + err);\n res.status(500);\n res.render(\"dashboard.html\", {results: null});\n });\n });\n\n app.put('/dashboard/upload', function(req, res) {\n if (config.dashboard && config.dashboard.secret) {\n if (req.query.secret == config.dashboard.secret) {\n async.forEachOfLimit(req.body, 5, function(scraper_info, slug, done) {\n scraper_info.timestamp = new Date().toISOString();\n es.index({\n index: config.elasticsearch.index_dashboard,\n type: 'scraper_info',\n id: slug,\n body: scraper_info\n }, done);\n }, function(err) {\n if (err) {\n console.log(\"Noooo!\\n\\n\" + err);\n\n res.status(500);\n res.end();\n } else {\n res.status(200);\n res.end();\n }\n });\n } else {\n res.status(403);\n res.end();\n }\n } else {\n res.status(500);\n res.end();\n }\n });\n\n};\n\n/*\n * Boolean answer for whether this report should be noindex'd.\n */\nfunction noindexed(report) {\n return !!(helpers.noindex[report.inspector + \"-\" + report.report_id]);\n}\n\n/* Parses query string parameters from a search request, and returns an object\n * that can be passed to the search function.\n */\nfunction parse_search_query(request_query, size) {\n var search_query, original_search_query;\n if (Array.isArray(request_query.query)) {\n search_query = original_search_query = request_query.query[0];\n } else {\n search_query = original_search_query = request_query.query;\n }\n if (!search_query) {\n search_query = \"*\";\n original_search_query = \"\";\n }\n\n var inspector;\n if (request_query.inspector) {\n if (Array.isArray(request_query.inspector)) {\n inspector = request_query.inspector;\n } else {\n inspector = [request_query.inspector];\n }\n } else {\n inspector = null;\n }\n\n var page = parseInt(request_query.page);\n if (!Number.isInteger(page)) {\n page = 1;\n }\n\n var featured = (request_query.featured == \"true\");\n var unreleased = (request_query.unreleased == \"true\");\n var foiad = (request_query.foiad == \"true\");\n\n var date_regex = /([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})/;\n var published_on_start, published_on_end;\n var start_match = date_regex.exec(request_query.published_on_start);\n if (start_match)\n published_on_start = start_match.slice(1).join(\"-\");\n else\n published_on_start = null;\n var end_match = date_regex.exec(request_query.published_on_end);\n if (end_match)\n published_on_end = end_match.slice(1).join(\"-\");\n else\n published_on_end = null;\n\n return {\n query: search_query,\n original_query: original_search_query,\n inspector: inspector,\n page: page,\n size: size,\n featured: featured,\n unreleased: unreleased,\n published_on_start: published_on_start,\n published_on_end: published_on_end,\n foiad: foiad\n };\n}\n\nfunction get(inspector, report_id) {\n return es.get({\n index: config.elasticsearch.index_read,\n type: 'reports',\n id: inspector + '-' + report_id\n });\n}\n\nfunction search(query_obj) {\n var from = (query_obj.page - 1) * query_obj.size;\n var body = {\n \"from\": from,\n \"size\": query_obj.size,\n \"query\": {\n \"bool\": {\n \"must\": {\n \"query_string\": {\n \"query\": query_obj.query,\n \"default_operator\": \"AND\",\n \"use_dis_max\": true,\n \"fields\": [\"text\", \"title\", \"summary\",\n \"pdf.title\", \"pdf.keywords\",\n \"doc.title\",\n \"docx.title\", \"docx.keywords\"]\n }\n }\n }\n },\n \"sort\": [{\n \"published_on\": \"desc\"\n }],\n \"highlight\": {\n \"encoder\": \"html\",\n \"pre_tags\": [\"\"],\n \"post_tags\": [\"\"],\n \"fields\": {\n \"text\": {},\n \"summary\": {}\n },\n \"order\": \"score\",\n \"fragment_size\": 500\n },\n \"_source\": [\"report_id\", \"year\", \"inspector\", \"agency\", \"title\", \"agency_name\", \"url\", \"landing_url\", \"inspector_url\", \"published_on\", \"type\", \"file_type\", \"featured.author\", \"featured.author_link\", \"featured.description\", \"unreleased\", \"missing\"]\n };\n\n var filters = [];\n if (query_obj.inspector) {\n if (query_obj.inspector.length == 1) {\n filters.push({\n \"term\": {\n \"inspector\": query_obj.inspector[0]\n }\n });\n } else if (query_obj.inspector.length > 1) {\n filters.push({\n \"terms\": {\n \"inspector\": query_obj.inspector\n }\n });\n }\n }\n\n if (query_obj.featured) {\n filters.push({\n \"term\": {\n \"is_featured\": true\n }\n });\n }\n\n if (query_obj.unreleased) {\n filters.push({\n \"term\": {\n \"unreleased\": true\n }\n });\n }\n\n if (query_obj.foiad) {\n filters.push({\n \"term\": {\n \"type\": \"FOIA - GovernmentAttic.org\"\n }\n });\n }\n\n if (query_obj.published_on_start || query_obj.published_on_end) {\n var date_filter = {\"range\": {\"published_on\": {}}};\n if (query_obj.published_on_start) {\n date_filter.range.published_on.from = query_obj.published_on_start;\n }\n if (query_obj.published_on_end) {\n date_filter.range.published_on.to = query_obj.published_on_end;\n }\n filters.push(date_filter);\n }\n\n if (filters.length == 1) {\n body.query.bool.filter = filters[0];\n } else if (filters.length > 1) {\n body.query.bool.filter = {\n \"bool\": {\n \"must\": filters\n }\n };\n }\n\n return es.search({\n index: config.elasticsearch.index_read,\n type: 'reports',\n body: body\n });\n}", "dangerousExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/dan', function (req, res) {\n5. const url = req.body.profile_url;\n6. try{\n7. res.redirect(url);\n8. }catch (e) {\n9. return res.status(500).send(\"ERROR\");\n10. }\n11. });\n12. \n13. module.exports = router;\nLine 7: A string variable URL of an unvalidated external input is used to connect.", "safeExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/safe', function (req, res) {\n5. const url = req.body.profile_url;\n6. const white_list = [\"https://www.safeurl.com\", \"https://www.verified.com\"];\n7. if (white_list.indexOf(url) < 0) {\n8. return res.status(500).send(\"url not allowed\");\n9. } else {\n10. try {\n11. res.redirect(url);\n12. } catch (e) {\n13. return res.status(500).send(\"ERROR\");\n14. }\n15. }\n16. });\n17. \n18. module.exports = router;\nLine 7-9: Validate external inputs through a filter function.", "contexts": [{"lineNo": 171, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "redirect"}}, {"lineNo": 174, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "req"}}, {"lineNo": 174, "eventType": "source", "messageKey": "synz.COMMON.taint.propagate", "params": {"arg0": "encodeURIComponent"}}]}} {"id": "966bd0d085daa4e727e188cc04dc4af85803bf7b9d3eec6964987a7215682904", "license": {"spdx": ["MIT"], "repo": "bekezie/StudentHousingFinder3.0", "path": "routes/index.js", "repo_head_hexsha": "7c62c522bdac8cade657ab9570dcdff372fdb402", "stack_hexsha": "fd4765160242920aa87371915539f512772467ca", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Redirection to untrusted site", "issueDescriptionEn": "The Redirection to untrusted site checker finds instances of redirecting to a URL generated with an unvalidated external input.\nAlthough connecting to a client-provided URL is often believed to be safe, an attacker can modify the request and redirect the user to a malicious site.\nMaintain a whitelist of external site URLs and domains allowed for redirection, which needs to be checked when a user input is passed as a redirect URL.", "issueLineNumber": 424, "entireCode": "let express = require(\"express\");\nlet router = express.Router();\nlet studentHousingDB = require(\"../db/myMongoDB.js\");\n\n// save a session for app\nlet session;\n\n/* GET home page. */\nrouter.get(\"/\", async function (req, res) {\n console.log(\"Attempting GET /\");\n // console.log(\"Attempting searches for GET /\");\n\n const listings = await studentHousingDB.getListings();\n // console.log(listings);\n // console.log(\"got listings\");\n\n session = req.session;\n\n if (session.userid) {\n // console.log(\"got session \" + session.userid);\n\n let user = await studentHousingDB.getUserByUsername(session.userid);\n // console.log(\"got user\", user);\n\n if (user.authorID != undefined) {\n //const authorID = owner.authorID;\n const authorID = user.authorID;\n // console.log(\"owner session: \", req.session);\n const ownerListings = await studentHousingDB.getListingsByAuthorID(\n parseInt(authorID)\n );\n console.log(\"render ownerHomePage\");\n res.render(\"ownerHomePage\", {\n title: \"StudentHousingFinderOwnerHome\",\n listings: ownerListings,\n unavailable: false,\n rank: false,\n username: user.username,\n authorID: authorID,\n });\n } else {\n console.log(\"render studentHomePage\");\n res.render(\"studentHomePage\", {\n title: \"StudentHousingFinderStudentHome\",\n listings: listings,\n available: false,\n rank: false,\n username: user.username,\n student: user.username,\n });\n }\n } else {\n console.log(\"render index\");\n res.render(\"index\", {\n title: \"StudentHousingFinderHome\",\n listings: listings,\n available: false,\n rank: false,\n });\n }\n});\n\n// After user logs in, render page depending on owner/student status\nrouter.post(\"/user\", async function (req, res) {\n console.log(\"**attempting POST /user\");\n\n // const listings = await studentHousingDB.getListings();\n // console.log(\"got listings\");\n session = req.session;\n session.userid = req.body.username;\n\n const user = await studentHousingDB.getUserByUsername(session.userid);\n // console.log(\"got user\", user);\n // const username = user.username;\n // const owner = await studentHousingDB.getOwnerByUsername(username);\n // console.log(\"got owner\", owner);\n // const student = await studentHousingDB.getOwnerByUsername(user);\n\n if (req.body.password == user.password) {\n res.redirect(\"/\");\n }\n});\n\n/* GET search page. */\nrouter.post(\"/search/Listing\", async function (req, res) {\n // console.log(\"Attempting GET /\");\n console.log(\"Attempting searches for POST /search/Listing\");\n\n let query = JSON.parse(JSON.stringify(req.body));\n console.log(query);\n let key, criteria, search;\n for (key in query) {\n criteria = key;\n // console.log(key);\n search = query[key];\n console.log(query[key]);\n }\n const listings = await studentHousingDB.searchListings(criteria, search);\n console.log(\"got listings\");\n\n session = req.session;\n\n if (session.userid) {\n console.log(\"got session \" + session.userid);\n\n let user = await studentHousingDB.getUserByUsername(session.userid);\n console.log(\"render studentHomePage \");\n try {\n res.render(\"studentHomePage\", {\n title: \"StudentHousingFinderStudentHome\",\n listings: listings,\n available: false,\n rank: false,\n username: user.username,\n student: user.firstName,\n });\n } catch (err) {\n console.log(\"failed to render\");\n }\n } else {\n // console.log(\"render index\");\n res.render(\"index\", {\n title: \"StudentHousingFinderHome\",\n listings: listings,\n available: false,\n rank: false,\n });\n }\n});\n\n/* POST available listings page. */\nrouter.post(\"/listings/available\", async function (req, res) {\n console.log(\"Attempting POST /listings/available\");\n\n const available = await studentHousingDB.getAvailableListings();\n console.log(\"got listings\");\n\n session = req.session;\n\n if (session.userid) {\n // console.log(\"got session \" + session.userid);\n\n let user = await studentHousingDB.getUserByUsername(session.userid);\n // console.log(\"got user\", user);\n\n console.log(\"render studentHomePage \");\n try {\n res.render(\"studentHomePage\", {\n title: \"StudentHousingFinderStudentHome\",\n listings: available,\n available: true,\n rank: false,\n username: user.username,\n student: user.firstName,\n });\n } catch (err) {\n console.log(\"failed to render\");\n }\n } else {\n // console.log(\"render index\");\n res.render(\"index\", {\n title: \"StudentHousingFinderHome\",\n listings: available,\n available: true,\n rank: false,\n });\n }\n});\n\n/* POST available listings page. */\nrouter.post(\"/listings/unavailable\", async function (req, res) {\n console.log(\"Attempting POST /listings/available\");\n\n session = req.session;\n let unavailable;\n\n if (session.userid) {\n // console.log(\"got session \" + session.userid);\n\n let user = await studentHousingDB.getUserByUsername(session.userid);\n // console.log(\"got user\", user);\n const authorID = user.authorID;\n\n unavailable = await studentHousingDB.getUnavailableListings(authorID);\n console.log(\"got listings\");\n\n console.log(\"render ownerHomePage \");\n try {\n res.render(\"ownerHomePage\", {\n title: \"StudentHousingFinderOwnerHome\",\n listings: unavailable,\n unavailable: true,\n username: user.username,\n authorID: authorID,\n rank: false,\n });\n } catch (err) {\n console.log(\"failed to render\");\n }\n } else {\n // console.log(\"render index\");\n res.render(\"index\", {\n title: \"StudentHousingFinderHome\",\n listings: unavailable,\n unavailable: false,\n rank: false,\n });\n }\n});\n\n/* GET logout. */\nrouter.get(\"/logout\", (req, res) => {\n req.session.destroy();\n res.redirect(\"/\");\n});\n\n/* GET register. */\nrouter.get(\"/register\", function (req, res) {\n res.render(\"registerPage\");\n});\n\n/* GET ownerRegister. */\nrouter.get(\"/owner\", function (req, res) {\n res.render(\"ownerRegisterPage\");\n});\n\n/* GET studentRegister. */\nrouter.get(\"/student\", function (req, res) {\n res.render(\"studentRegisterPage\");\n});\n\n// /* POST create listing. */\nrouter.post(\"/listings/create\", async function (req, res) {\n console.log(\"**attempting POST listings/create\");\n session = req.session;\n\n const listing = req.body;\n // console.log(\"create listing\", listing);\n const user = await studentHousingDB.getUserByUsername(session.userid);\n // console.log(\"got user\", user);\n // const owner = await studentHousingDB.getOwnerByUsername(user.username);\n // console.log(\"got owner\", owner);\n //const authorID = owner.authorID;\n const authorID = user.authorID;\n session.authorID = authorID;\n // console.log(\"got authorID\", session.authorID);\n\n try {\n await studentHousingDB.createListing(listing, authorID);\n // console.log(\"Listing created\");\n } catch (err) {\n // console.log(\"Listing not created\");\n }\n\n session = req.session;\n\n res.redirect(\"/\");\n});\n\n// /* POST rank listing by rating. */\nrouter.get(\"/rankListing\", async function (req, res) {\n console.log(\"Attempting GET /rankListing\");\n // console.log(\"Attempting searches for GET /\");\n\n let redisListings = await studentHousingDB.getSortedListings();\n if (redisListings.length > 0) {\n //console.log(listings);\n console.log(\"got listings\");\n //get listing refrence, sorted by score ranking of highest rating\n // let mongoListings = await studentHousingDB.getSortedListings();\n // console.log(mongoListings);\n\n session = req.session;\n\n if (session.userid) {\n // console.log(\"got session \" + session.userid);\n\n let user = await studentHousingDB.getUserByUsername(session.userid);\n // console.log(\"got user\", user);\n\n if (user.authorID != undefined) {\n //const authorID = owner.authorID;\n const authorID = user.authorID;\n\n const ownerListings =\n await studentHousingDB.getRankedListingsByAuthorID(authorID);\n console.log(\"render ownerHomePage\");\n res.render(\"ownerHomePage\", {\n title: \"StudentHousingFinderOwnerHome\",\n listings: ownerListings,\n unavailable: false,\n rank: true,\n username: user.username,\n authorID: authorID,\n });\n } else {\n console.log(\"render studentHomePage\");\n res.render(\"studentHomePage\", {\n title: \"StudentHousingFinderStudentHome\",\n listings: redisListings,\n available: false,\n rank: true,\n username: user.username,\n student: user.username,\n });\n }\n } else {\n console.log(\"render index\");\n res.render(\"index\", {\n title: \"StudentHousingFinderHome\",\n listings: redisListings,\n available: false,\n rank: true,\n });\n }\n\n console.log(\"Got Ranked Listing from Redis!\");\n } else {\n console.log(\"got listings\");\n const mongoListings = await studentHousingDB.getRankedListings();\n\n for (let i = 0; i < mongoListings.length; i++) {\n console.log(\"iterations \" + i);\n //increments count by 1\n //await studentHousingDB.addscore();\n //creates object of listing object\n console.log(mongoListings[i]);\n\n await studentHousingDB.rankListing(mongoListings[i]);\n //break;\n }\n //get listing refrence, sorted by score ranking of highest rating\n\n redisListings = await studentHousingDB.getSortedListings();\n console.log(redisListings);\n\n session = req.session;\n\n if (session.userid) {\n // console.log(\"got session \" + session.userid);\n\n let user = await studentHousingDB.getUserByUsername(session.userid);\n // console.log(\"got user\", user);\n\n if (user.authorID != undefined) {\n //const authorID = owner.authorID;\n const authorID = user.authorID;\n\n const ownerListings =\n await studentHousingDB.getRankedListingsByAuthorID(authorID);\n console.log(\"render ownerHomePage\");\n res.render(\"ownerHomePage\", {\n title: \"StudentHousingFinderOwnerHome\",\n listings: ownerListings,\n username: user.username,\n authorID: authorID,\n rank: true,\n });\n } else {\n console.log(\"render studentHomePage\");\n res.render(\"studentHomePage\", {\n title: \"StudentHousingFinderStudentHome\",\n listings: mongoListings,\n username: user.username,\n student: user.username,\n rank: true,\n });\n }\n } else {\n console.log(\"render index\");\n res.render(\"index\", {\n title: \"StudentHousingFinderHome\",\n listings: mongoListings,\n rank: true,\n });\n }\n console.log(\"Ranked Listings have been set! Data retrival from mongodb.\");\n }\n});\n// /* POST create rating. */\nrouter.post(\"/createRating\", async function (req, res) {\n // console.log(\"**attempting POST createRating\");\n session = req.session;\n let rateInt = parseInt(req.body.rating, 10);\n const rating = {\n rating: rateInt,\n listingID: parseInt(req.body.listingID),\n user: session.userid,\n };\n\n // console.log(rating);\n try {\n await studentHousingDB.createRating(rating);\n // console.log(\"rating created\");\n\n let redisListings = await studentHousingDB.getSortedListings();\n if (redisListings.length > 0) {\n //console.log(listings);\n console.log(\"got getRankedListings\");\n //get listing refrence, sorted by score ranking of highest rating\n const mongoListings = await studentHousingDB.getRankedListings();\n await studentHousingDB.setScore();\n for (let i = 0; i < mongoListings.length; i++) {\n console.log(\"iterations \" + i);\n\n //creates object of listing object\n console.log(mongoListings[i]);\n\n await studentHousingDB.rankListing(mongoListings[i]);\n //break;\n }\n //get listing refrence, sorted by score ranking of highest rating\n\n redisListings = await studentHousingDB.getSortedListings();\n console.log(redisListings);\n\n console.log(\"Ranked Listings have been set! Data retrival from mongodb.\");\n }\n } catch (err) {\n // console.log(\"rating not created\");\n }\n session = req.session;\n // console.log(\"update listing session\", session);\n res.redirect(\"listings/\" + req.body.listingID);\n});\n\n// /* POST update Rating. */\nrouter.post(\"/updateRating\", async function (req, res) {\n // console.log(\"**attempting POST ratings/update\");\n session = req.session;\n let rateInt = parseInt(req.body.rating, 10);\n const updatedrating = {\n rating: rateInt,\n listingID: parseInt(req.body.listingID),\n raterID: session.userid,\n };\n // console.log(updatedrating);\n\n try {\n await studentHousingDB.updateRating(updatedrating);\n // console.log(\"Listing updated\", updatedrating);\n let redisListings = await studentHousingDB.getSortedListings();\n if (redisListings.length > 0) {\n //console.log(listings);\n console.log(\"got listings\");\n //get listing refrence, sorted by score ranking of highest rating\n\n console.log(\"got getRankedListings\");\n const mongoListings = await studentHousingDB.getRankedListings();\n await studentHousingDB.setScore();\n for (let i = 0; i < mongoListings.length; i++) {\n console.log(\"iterations \" + i);\n\n //creates object of listing object\n console.log(mongoListings[i]);\n\n await studentHousingDB.rankListing(mongoListings[i]);\n //break;\n }\n //get listing refrence, sorted by score ranking of highest rating\n\n redisListings = await studentHousingDB.getSortedListings();\n console.log(redisListings);\n\n console.log(\"Ranked Listings have been set! Data retrival from mongodb.\");\n }\n } catch (err) {\n // console.log(\"Listing not updated\");\n }\n\n session = req.session;\n // console.log(\"update listing session\", session);\n\n // console.log(\"POST update listing\", listing);\n // console.log(\"update listing session\", session);\n res.redirect(\"listings/\" + req.body.listingID);\n});\n\n// /* GET listing details page. */\nrouter.get(\"/listings/:listingID\", async function (req, res) {\n // console.log(\"**attempting GET listing details\");\n\n session = req.session;\n\n if (session.userid != undefined) {\n const listingID = parseInt(req.params.listingID);\n\n console.log(\"Got listing details \", listingID);\n\n const listing = await studentHousingDB.getListingByID(listingID);\n console.log(\"Got listing by ID \", listing);\n\n // const studObj = {\n // listingID: listingID,\n // user: session.userid,\n // };\n // console.log(\"listingID, user: \", listingID, session.userid);\n\n const rating = await studentHousingDB.getRatingByIDS(\n parseInt(listing.listingID),\n session.userid\n );\n\n console.log(\"authorID:\", parseInt(listing.authorID));\n const owner = await studentHousingDB.getOwnerByAuthorID(\n listing.authorID.toString()\n );\n console.log(\"Got owner \", owner);\n const msgs = await studentHousingDB.getMessages(\n session.userid,\n owner.username,\n parseInt(listing.listingID)\n );\n\n let time = new Date().toLocaleTimeString([], {\n hour: \"2-digit\",\n minute: \"2-digit\",\n });\n\n if (time.substring(0, 1) == 0) {\n time = time.substring(1);\n }\n\n res.render(\"listingDetailsPage\", {\n listing,\n username: session.userid,\n rating,\n owner,\n time,\n msgs,\n });\n } else {\n res.redirect(\"/\");\n }\n});\n\n/* GET Update listing details. */\nrouter.get(\"/listings/update/:listingID\", async function (req, res) {\n console.log(\"**attempting POST listings/update/ID\");\n\n const listingID = parseInt(req.params.listingID);\n // console.log(\"Got listing details \", listingID);\n\n const listing = await studentHousingDB.getListingByID(listingID);\n console.log(\"Listing updated\");\n // console.log(\"here is the Listing! \", listing);\n\n session = req.session;\n // console.log(\"session.userid: \", session);\n\n res.render(\"listingUpdatePage\", {\n listing: listing,\n username: session.userid,\n });\n});\n\n/* POST update listing. */\nrouter.post(\"/listings/update\", async function (req, res) {\n // console.log(\"**attempting POST listings/update\");\n\n const listing = req.body;\n // console.log(\"POST update listing\", listing);\n\n try {\n await studentHousingDB.updateListing(listing);\n console.log(\"Listing updated\");\n } catch (err) {\n console.log(\"Listing not updated: \", err);\n }\n\n session = req.session;\n // console.log(\"update listing session\", session);\n\n res.redirect(\"/\");\n});\n\n// /* POST delete listing. */\nrouter.post(\"/listings/delete\", async function (req, res) {\n // console.log(\"**attempting POST delete listing\");\n\n const listingID = parseInt(req.body.listingID);\n const authorID = req.body.authorID;\n // console.log(listingID);\n // console.log(\"delete listing\", listingID);\n session = req.session;\n\n try {\n await studentHousingDB.deleteListing(listingID, authorID);\n // console.log(\"Listing deleted\");\n } catch (err) {\n // console.log(\"Listing not deleted\");\n }\n\n res.redirect(\"/\");\n});\n\n/* POST send message. */\nrouter.post(\"/message/create\", async function (req, res) {\n // console.log(\"Got post message/create\");\n\n const msg = req.body;\n console.log(\"Got create message\", msg);\n try {\n await studentHousingDB.createMessage(msg);\n // console.log(\"Message created\");\n } catch (err) {\n // console.log(\"Message not created:\" + err);\n }\n\n res.redirect(\"/listings/\" + msg.listingID);\n});\n\n/* POST delete message. */\nrouter.post(\"/message/delete\", async function (req, res) {\n // console.log(\"Got post message/delete\");\n\n const msg = req.body;\n // console.log(\"Got delete message\", msg);\n try {\n await studentHousingDB.deleteMessage(msg);\n console.log(\"Message deleted\");\n } catch (err) {\n console.log(\"Message not deleted:\" + err);\n }\n\n res.redirect(\"/listings/\" + msg.listingID);\n});\n\n/* POST delete message. */\nrouter.post(\"/message/owner/delete\", async function (req, res) {\n // console.log(\"Got post message/delete\");\n\n const msg = req.body;\n // console.log(\"Got delete message\", msg);\n try {\n await studentHousingDB.deleteMessage(msg);\n // console.log(\"Message deleted\");\n } catch (err) {\n // console.log(\"Message not deleted:\" + err);\n }\n\n res.redirect(\"/message/\" + msg.username);\n});\n\n/* POST view message. */\nrouter.post(\"/message/view\", async function (req, res) {\n // console.log(\"**attempting POST message/view\");\n\n res.redirect(\"/message/\" + req.body.username);\n});\n\n/* GET owner's messages page. */\nrouter.get(\"/message/:username\", async function (req, res) {\n // console.log(\"**attempting GET owner's messages page\");\n\n const username = req.params.username;\n // console.log(\"Got username\", username);\n\n const msgs = await studentHousingDB.getAllMessages(username);\n // console.log(\"Got messages\");\n\n let time = new Date().toLocaleTimeString([], {\n hour: \"2-digit\",\n minute: \"2-digit\",\n });\n\n if (time.substring(0, 1) == 0) {\n time = time.substring(1);\n }\n\n res.render(\"ownerMessagesPage\", {\n username,\n msgs,\n time,\n });\n});\n\n/* POST reply message. */\nrouter.post(\"/message/reply\", async function (req, res) {\n // console.log(\"**attempting POST message/view\");\n\n const msg = req.body;\n // console.log(\"create message\", msg);\n try {\n await studentHousingDB.createMessage(msg);\n // console.log(\"Message replied\");\n } catch (err) {\n // console.log(\"Message not replied:\" + err);\n }\n\n res.redirect(\"/message/\" + req.body.sender);\n});\n\nmodule.exports = router;", "dangerousExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/dan', function (req, res) {\n5. const url = req.body.profile_url;\n6. try{\n7. res.redirect(url);\n8. }catch (e) {\n9. return res.status(500).send(\"ERROR\");\n10. }\n11. });\n12. \n13. module.exports = router;\nLine 7: A string variable URL of an unvalidated external input is used to connect.", "safeExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/safe', function (req, res) {\n5. const url = req.body.profile_url;\n6. const white_list = [\"https://www.safeurl.com\", \"https://www.verified.com\"];\n7. if (white_list.indexOf(url) < 0) {\n8. return res.status(500).send(\"url not allowed\");\n9. } else {\n10. try {\n11. res.redirect(url);\n12. } catch (e) {\n13. return res.status(500).send(\"ERROR\");\n14. }\n15. }\n16. });\n17. \n18. module.exports = router;\nLine 7-9: Validate external inputs through a filter function.", "contexts": [{"lineNo": 424, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "req"}}, {"lineNo": 424, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "redirect"}}]}} {"id": "98c2b843f7cac349f6bf76fa411127f65fb480827f50ffbe5786a4b6b51823da", "license": {"spdx": ["MIT"], "repo": "awhite/YelpCamp", "path": "routes/comments.js", "repo_head_hexsha": "8a5cafa1434814479fcbb9a0672ba121c106920b", "stack_hexsha": "bd49684412b5287bc70d5d8aa6da5f4f58955a37", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Redirection to untrusted site", "issueDescriptionEn": "The Redirection to untrusted site checker finds instances of redirecting to a URL generated with an unvalidated external input.\nAlthough connecting to a client-provided URL is often believed to be safe, an attacker can modify the request and redirect the user to a malicious site.\nMaintain a whitelist of external site URLs and domains allowed for redirection, which needs to be checked when a user input is passed as a redirect URL.", "issueLineNumber": 23, "entireCode": "const express = require('express');\nconst router = express.Router({ mergeParams: true });\nconst Campground = require('../models/campground');\nconst Comment = require('../models/comment');\nconst middleware = require('../middleware');\n\nrouter.get('/new', middleware.checkLoggedIn, (req, res) => { // Comments NEW\n Campground.findById(req.params.id).then((campground) => {\n res.render('comments/new', { campground: campground });\n }).catch((err) => {\n console.log(err);\n });\n});\n\nrouter.post('/', middleware.checkLoggedIn, (req, res) => { // Comments CREATE\n Campground.findById(req.params.id).then((campground) => {\n Comment.create(req.body.comment).then((comment) => {\n comment.author.id = req.user._id;\n comment.author.username = req.user.username;\n comment.save().then(() => {\n campground.comments.push(comment);\n campground.save();\n res.redirect(`/campgrounds/${req.params.id}`);\n }).catch((err) => {\n console.log(err);\n })\n }).catch((err) => {\n console.log(err);\n res.redirect('/campgrounds');\n })\n }).catch((err) => {\n console.log(err);\n });\n});\n\nrouter.get('/:commentId/edit', middleware.checkLoggedIn, middleware.checkCommentOwnership, (req, res) => {\n Comment.findById(req.params.commentId).then((comment) => {\n res.render('comments/edit', { comment: comment, campgroundId: req.params.id });\n }).catch((err) => {\n console.log(err);\n });\n});\n\nrouter.put('/:commentId', middleware.checkLoggedIn, middleware.checkCommentOwnership, (req, res) => {\n Comment.findByIdAndUpdate(req.params.commentId, req.body.comment).then((comment) => {\n res.redirect(`/campgrounds/${ req.params.id }`);\n }).catch((err) => {\n console.log(err);\n });\n});\n\nrouter.delete('/:commentId', middleware.checkLoggedIn, middleware.checkCommentOwnership, (req, res) => {\n Comment.findByIdAndRemove(req.params.commentId).then((item) => {\n req.flash('success', 'Comment deleted.')\n res.redirect(`/campgrounds/${ req.params.id }`);\n }).catch((err) => {\n console.log(err);\n });\n});\n\nmodule.exports = router;", "dangerousExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/dan', function (req, res) {\n5. const url = req.body.profile_url;\n6. try{\n7. res.redirect(url);\n8. }catch (e) {\n9. return res.status(500).send(\"ERROR\");\n10. }\n11. });\n12. \n13. module.exports = router;\nLine 7: A string variable URL of an unvalidated external input is used to connect.", "safeExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/safe', function (req, res) {\n5. const url = req.body.profile_url;\n6. const white_list = [\"https://www.safeurl.com\", \"https://www.verified.com\"];\n7. if (white_list.indexOf(url) < 0) {\n8. return res.status(500).send(\"url not allowed\");\n9. } else {\n10. try {\n11. res.redirect(url);\n12. } catch (e) {\n13. return res.status(500).send(\"ERROR\");\n14. }\n15. }\n16. });\n17. \n18. module.exports = router;\nLine 7-9: Validate external inputs through a filter function.", "contexts": [{"lineNo": 23, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "req"}}, {"lineNo": 23, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "redirect"}}]}} {"id": "b0b32d9164d47c4ec17045200110af4266ee81128b2ca445e1cbba06bff983dd", "license": {"spdx": ["MIT"], "repo": "oussema-dev/credit_cards_crud", "path": "app.js", "repo_head_hexsha": "fed15ea2484917b08aca08d056b4586736fbc5cf", "stack_hexsha": "af127aa9952365dec816c54960d08eef07fa49c1", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Redirection to untrusted site", "issueDescriptionEn": "The Redirection to untrusted site checker finds instances of redirecting to a URL generated with an unvalidated external input.\nAlthough connecting to a client-provided URL is often believed to be safe, an attacker can modify the request and redirect the user to a malicious site.\nMaintain a whitelist of external site URLs and domains allowed for redirection, which needs to be checked when a user input is passed as a redirect URL.", "issueLineNumber": 93, "entireCode": "require('dotenv').config();\nconst express = require('express'),\n\tapp = express(),\n\tmethodOverride = require('method-override'),\n\tmongoose = require('mongoose'),\n\tsession = require('express-session'),\n\tflash = require('connect-flash');\n\nmongoose.connect(process.env.DATABASEURL, {\n\tuseNewUrlParser: true,\n\tuseFindAndModify: false,\n\tuseCreateIndex: true,\n\tuseUnifiedTopology: true\n});\n\napp.set('view engine', 'ejs');\napp.use(express.static('public'));\napp.use(express.urlencoded({ extended: true }));\napp.use(methodOverride('_method'));\n\napp.use(flash());\napp.use(\n\tsession({\n\t\tsecret: 'Secret',\n\t\tresave: false,\n\t\tsaveUninitialized: false\n\t})\n);\napp.use((req, res, next) => {\n\tres.locals.success = req.flash('success');\n\tres.locals.error = req.flash('error');\n\tnext();\n});\n\nconst cardSchema = new mongoose.Schema({\n\ttype: String,\n\tuser: String,\n\tnumber: String,\n\tcvv2: String,\n\texpiry: Date\n});\nconst Card = mongoose.model('Card', cardSchema);\n\napp.get('/cards', async (req, res) => {\n\tconst cards = await Card.find({});\n\tres.render('index', { cards });\n});\n\napp.get('/cards/new', (req, res) => {\n\tres.render('new');\n});\n\napp.post('/cards', async (req, res) => {\n\tawait Card.create(req.body.card);\n\treq.flash('success', 'Credit Card Created Successfully !');\n\tres.redirect('/cards');\n});\n\napp.get('/cards/:id', async (req, res) => {\n\ttry {\n\t\tconst card = await Card.findById(req.params.id);\n\t\tswitch (card.type) {\n\t\t\tcase 'Visa':\n\t\t\t\treturn res.render('visa', { card });\n\t\t\tcase 'Master Card':\n\t\t\t\treturn res.render('master', { card });\n\t\t\tcase 'BestBank':\n\t\t\t\treturn res.render('best', { card });\n\t\t}\n\t} catch (err) {\n\t\treq.flash('error', 'Credit Card Not Found');\n\t\tres.redirect('/cards');\n\t}\n});\n\napp.get('/cards/:id/edit', async (req, res) => {\n\ttry {\n\t\tconst card = await Card.findById(req.params.id);\n\t\tif (card) res.render('edit', { card });\n\t\telse {\n\t\t\treq.flash('error', 'Credit Card Not Found');\n\t\t\tres.redirect('/cards');\n\t\t}\n\t} catch (err) {\n\t\treq.flash('error', 'Credit Card Not Found');\n\t\tres.redirect('/cards');\n\t}\n});\n\napp.put('/cards/:id', async (req, res) => {\n\ttry {\n\t\tawait Card.findByIdAndUpdate(req.params.id, req.body.card);\n\t\tres.redirect('/cards/' + req.params.id);\n\t} catch (err) {\n\t\treq.flash('error', 'Credit Card Not Found');\n\t\tres.redirect('/cards');\n\t}\n});\n\napp.delete('/cards/:id', async (req, res) => {\n\ttry {\n\t\tconst deletedCard = await Card.findByIdAndRemove(req.params.id);\n\t\tif (deletedCard) {\n\t\t\treq.flash('success', 'Credit Card Removed Successfully !');\n\t\t\tres.redirect('/cards');\n\t\t} else {\n\t\t\treq.flash('error', 'Credit Card Not Found');\n\t\t\tres.redirect('/cards');\n\t\t}\n\t} catch (error) {\n\t\treq.flash('error', 'Credit Card Not Found');\n\t\tres.redirect('/cards');\n\t}\n});\n\napp.get('*', (req, res) => {\n\tres.redirect('/cards');\n});\n\napp.listen(process.env.PORT, () => {\n\tconsole.log(`Server started on port ${process.env.PORT}`);\n});", "dangerousExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/dan', function (req, res) {\n5. const url = req.body.profile_url;\n6. try{\n7. res.redirect(url);\n8. }catch (e) {\n9. return res.status(500).send(\"ERROR\");\n10. }\n11. });\n12. \n13. module.exports = router;\nLine 7: A string variable URL of an unvalidated external input is used to connect.", "safeExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/safe', function (req, res) {\n5. const url = req.body.profile_url;\n6. const white_list = [\"https://www.safeurl.com\", \"https://www.verified.com\"];\n7. if (white_list.indexOf(url) < 0) {\n8. return res.status(500).send(\"url not allowed\");\n9. } else {\n10. try {\n11. res.redirect(url);\n12. } catch (e) {\n13. return res.status(500).send(\"ERROR\");\n14. }\n15. }\n16. });\n17. \n18. module.exports = router;\nLine 7-9: Validate external inputs through a filter function.", "contexts": [{"lineNo": 93, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "req"}}, {"lineNo": 93, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "redirect"}}]}} {"id": "8409d02cb6686eda1539037b7d8730f8d2df6eedbdf2257896d2937360806972", "license": {"spdx": ["MIT"], "repo": "fati-ma/401-Entrance", "path": "server.js", "repo_head_hexsha": "ab0af61c9d73baee2be4bd81a1429621f66b58bb", "stack_hexsha": "da6336e86a703e10c772d24a21f05629f176f11e", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Redirection to untrusted site", "issueDescriptionEn": "The Redirection to untrusted site checker finds instances of redirecting to a URL generated with an unvalidated external input.\nAlthough connecting to a client-provided URL is often believed to be safe, an attacker can modify the request and redirect the user to a malicious site.\nMaintain a whitelist of external site URLs and domains allowed for redirection, which needs to be checked when a user input is passed as a redirect URL.", "issueLineNumber": 101, "entireCode": "'use strict';\n\n//APP DEPENDENCIES\nconst express = require('express');\nrequire('dotenv').config();\nconst cors = require('cors');\nconst superagent = require('superagent');\nconst methodOverride = require('method-override');\nconst pg = require('pg');\nconst PORT = process.env.PORT;\n\n//APP SETUP\nconst app = express();\napp.use(cors());\napp.use(express.urlencoded({ extended: true }));\napp.use(methodOverride('_method'));\napp.use(express.static('./public'));\napp.set('view engine', 'ejs');\nconst client = new pg.Client(process.env.DATABASE_URL);\n\n//HOME PAGE\napp.get('/', (req, res) => {\n let url = `https://api.covid19api.com/world/total`;\n superagent.get(url)\n .then(result => {\n res.render('HomePage', { totals: result.body })\n })\n})\n\n//SEARCH CONFIRMED CASES FOR CERTAIN COUNTRY\napp.get('/search', (req, res) => {\n const country = req.query.country;\n const from = req.query.from;\n const to = req.query.to;\n let url = `https://api.covid19api.com/country/${country}/status/confirmed?from=${from}&to=${to}`;\n superagent.get(url)\n .then(results => {\n console.log(results.body);\n res.render('getCountryResult', { resultsSearch: results.body })\n })\n\n})\n\n//RENDER ALL COUNTRIES WITH DETAILS\napp.get('/allCountries', (req, res) => {\n let url = `https://api.covid19api.com/summary`;\n superagent.get(url)\n .then(results => {\n let objArr = results.body.Countries.map(obj => {\n return new CountryObj(obj);\n })\n res.render('AllCountries', { countries: objArr });\n })\n})\n\n//ADD NEW COUNTRY TO MY DATABASE\napp.post('/addRecord', (req, res) => {\n let sql = 'INSERT INTO records (Country, TotalConfirmed, TotalDeaths, TotalRecovered, Date) VALUES ($1,$2,$3,$4,$5);';\n const { Country, TotalConfirmed, TotalDeaths, TotalRecovered, Date } = req.body;\n let safeValues = [Country, TotalConfirmed, TotalDeaths, TotalRecovered, Date];\n client.query(sql, safeValues)\n .then(() => {\n res.redirect('/MyRecords');\n })\n})\n\n//RENDER ADDED RECORDS\napp.get('/MyRecords', (req, res) => {\n let sql = 'SELECT * FROM records;';\n client.query(sql)\n .then(results => {\n // console.log(results);\n if (results.rowCount > 0) {\n\n res.render('MyRecords', { record: results.rows });\n }\n else {\n\n res.send('No Available Records');\n }\n })\n})\n\n//DISPLAY DETAILS FOR SELECTED COUNTRY\napp.get('/details/:id', (req, res) => {\n let sql = 'SELECT * FROM records WHERE id=$1;';\n let safeVal = [req.params.id];\n client.query(sql, safeVal)\n .then(result => {\n res.render('RecordDetails', { details: result.rows[0] });\n })\n})\n\n//UPDATE DETAILS\napp.put('/details/:id', (req, res) => {\n let sql = 'UPDATE records SET Country=$1, TotalConfirmed=$2, TotalDeaths=$3, TotalRecovered=$4, Date=$5 WHERE id=$6;';\n const { Country, TotalConfirmed, TotalDeaths, TotalRecovered, Date } = req.body;\n let safeValues = [Country, TotalConfirmed, TotalDeaths, TotalRecovered, Date, req.params.id];\n client.query(sql, safeValues)\n .then(() => {\n res.redirect(`/details/${req.params.id}`);\n })\n})\n\n//DELETE COUNTRY FROM DATABASE\napp.delete('/details/:id', (req, res) => {\n let sql = 'DELETE FROM records WHERE id =$1;';\n let safeVal = [req.params.id];\n client.query(sql, safeVal)\n .then(() => {\n res.redirect('/MyRecords');\n })\n})\n\n//CONSTRUCTOR TO INSTACIATE OBJECTS\nfunction CountryObj(obj) {\n this.Country = obj.Country + ', ' + obj.CountryCode;\n this.TotalConfirmed = obj.TotalConfirmed;\n this.TotalDeaths = obj.TotalDeaths;\n this.TotalRecovered = obj.TotalRecovered;\n this.Date = obj.Date;\n}\n\n//CONNECT SERVER TO DB\nclient.connect()\n .then(() => {\n app.listen(PORT, () => {\n console.log(`Listening on port: ${PORT}`);\n })\n })", "dangerousExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/dan', function (req, res) {\n5. const url = req.body.profile_url;\n6. try{\n7. res.redirect(url);\n8. }catch (e) {\n9. return res.status(500).send(\"ERROR\");\n10. }\n11. });\n12. \n13. module.exports = router;\nLine 7: A string variable URL of an unvalidated external input is used to connect.", "safeExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/safe', function (req, res) {\n5. const url = req.body.profile_url;\n6. const white_list = [\"https://www.safeurl.com\", \"https://www.verified.com\"];\n7. if (white_list.indexOf(url) < 0) {\n8. return res.status(500).send(\"url not allowed\");\n9. } else {\n10. try {\n11. res.redirect(url);\n12. } catch (e) {\n13. return res.status(500).send(\"ERROR\");\n14. }\n15. }\n16. });\n17. \n18. module.exports = router;\nLine 7-9: Validate external inputs through a filter function.", "contexts": [{"lineNo": 101, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "req"}}, {"lineNo": 101, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "redirect"}}]}} {"id": "dabd807b8e2abb8604831dc54517e97c663880cdf8f60fb1a18ec75393d6c8cc", "license": {"spdx": ["MIT"], "repo": "siddhantanal/postman-sample", "path": "api/controllers/PaymentController.js", "repo_head_hexsha": "044584e269a966e840234ba60d53b9297b7ec250", "stack_hexsha": "8c0726f27f062d6dece8c09dd5ffe6a1f99f01bd", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Redirection to untrusted site", "issueDescriptionEn": "The Redirection to untrusted site checker finds instances of redirecting to a URL generated with an unvalidated external input.\nAlthough connecting to a client-provided URL is often believed to be safe, an attacker can modify the request and redirect the user to a malicious site.\nMaintain a whitelist of external site URLs and domains allowed for redirection, which needs to be checked when a user input is passed as a redirect URL.", "issueLineNumber": 38, "entireCode": "/**\n * PaymentController\n *\n * @description :: Server-side logic for managing Payments\n * @help :: See http://sailsjs.org/#!/documentation/concepts/Controllers\n */\n\nconst keyPublishable = 'pk_test_EFauhL4VIeoeTDQUBdETeCmj';\nconst keySecret = 'sk_test_hTeniJlmahot2gL2vBTNmEox';\n\nconst stripe = require(\"stripe\")(keySecret);\n\nmodule.exports = {\n\tinititatePayment : function(req,res){\n console.log(req.body);\n \n Order.find().where({\n token : req.body.token\n }).exec(function(err,obj){\n if(!err && obj.length > 0 ){\n var amount = obj[0].total_amount;\n console.log(obj);\n if(obj[0].status === 'complete'){\n res.view('error',{\n msg: \"Order Already completed or rejected\"\n });\n }\n else{\n if(req.session.wallet > amount){\n var credits = parseInt(req.session.wallet) - parseInt(amount);\n //reduce credits\n User.update({ id : req.session.user_id }, { credits : credits }).exec(function(err,obj){\n if(!err){\n req.session.wallet = credits;\n req.session.save();\n Order.update({token:req.body.token},{status:'complete'}).exec(function(err,obj){\n if(!err){\n res.redirect('/generateRecipt/'+req.body.token);\n }\n else{\n res.view('error',{\n msg: \"Error Occured, transaction incomplete\"\n });\n }\n });\n }\n else{\n res.view('error',{\n msg: \"Error Occured, transaction incomplete\"\n });\n }\n });\n }\n else{\n var amount = parseInt(obj[0].total_amount)-parseInt(req.session.wallet);\n if(req.session.stripe_id == null){\n var promise = stripe.customers.create({\n email: req.body.stripeEmail,\n source: req.body.stripeToken\n }); \n promise.then(function(customer){\n User.update({ id : req.session.user_id }, { stripe_customer_id:customer.id }).exec(function(err,obj){\n if(!err){\n console.log('id : ');\n console.log(req.session.stripe_id);\n stripe.charges.create({\n amount,\n description: \"Sample Charge\",\n currency: \"usd\",\n customer: customer.id\n }).then(function(charge){ \n console.log(\"charge\");\n console.log(charge);\n User.update({ id : req.session.user_id }, { credits : 0 }).exec(function(err,obj){\n if(!err){\n req.session.wallet = 0;\n req.session.save();\n Order.update({token:req.body.token},{status:'complete'}).exec(function(err,obj){\n if(!err){\n res.redirect('/generateRecipt/'+req.body.token);\n }\n else{\n res.view('error',{\n msg: \"Error Occured, transaction incomplete\"\n });\n }\n });\n }\n else{\n res.view('error',{\n msg: \"Error Occured, transaction incomplete\"\n });\n }\n });\n });\n }\n else{\n res.view('error',{\n msg: \"Error Occured, Unable to update user details\"\n });\n }\n });\n });\n }\n else{\n var promise = stripe.charges.create({\n amount,\n description: \"Sample Charge\",\n currency: \"usd\",\n customer: req.session.stripe_id\n });\n promise.then(function(charge){\n User.update({ id : req.session.user_id }, { credits : 0 }).exec(function(err,obj){\n if(!err){\n req.session.wallet = 0;\n req.session.save();\n Order.update({token:req.body.token},{status:'complete'}).exec(function(err,obj){\n if(!err){\n res.redirect('/generateRecipt/'+req.body.token);\n }\n else{\n res.view('error',{\n msg: \"Error Occured, transaction incomplete\"\n });\n }\n });\n }\n else{\n res.view('error',{\n msg: \"Error Occured, transaction incomplete\"\n });\n }\n });\n });\n }\n }\n }\n }\n else{\n res.view('error',{\n msg: \"Token mismatch\"\n });\n }\n });\n },\n paymentToWallet : function(req,res){\n //add to wallet function\n var amount = req.body.credits;\n if(amount > 0)\n {\n if(req.session.stripe_id == null){\n var promise = stripe.customers.create({\n email: req.body.stripeEmail,\n source: req.body.stripeToken\n }); \n promise.then(function(customer){\n User.update({ id : req.session.user_id }, { stripe_customer_id:customer.id }).exec(function(err,obj){\n if(!err){\n stripe.charges.create({\n amount,\n description: \"Sample Charge\",\n currency: \"usd\",\n customer: customer.id\n }).then(function(charge){ \n var credits = parseInt(req.session.wallet) + parseInt(amount);\n User.update({id:req.session.user_id},{credits: credits}).exec(function(err,obj){\n if(!err){\n res.redirect('/profile');\n }\n else{\n res.view('error',{\n msg: \"Error Occured, transaction incomplete\"\n });\n }\n });\n });\n }\n else{\n res.view('error',{\n msg: \"Error Occured, no amount entered\"\n });\n }\n }); \n });\n }\n else{\n stripe.customers.create({\n email: req.body.stripeEmail,\n source: req.body.stripeToken\n })\n .then(customer =>\n stripe.charges.create({\n amount,\n description: \"Sample Charge\",\n currency: \"usd\",\n customer: customer.id\n }))\n .then(function(charge){ \n var credits = parseInt(req.session.wallet) + parseInt(amount);\n User.update({id:req.session.user_id},{credits: credits}).exec(function(err,obj){\n if(!err){\n res.redirect('/profile');\n }\n else{\n res.view('error',{\n msg: \"Error Occured, transaction incomplete\"\n });\n }\n });\n });\n }\n }\n else{\n res.view('error',{\n msg: \"Error Occured, no amount entered\"\n });\n }\n },\n getOrderSummary : function(req,res){\n var token = req.param('token');\n Order.query(\"SELECT `order`.`id`, `userproduct`.`product_name`, `userproduct`.`product_price`, `order`.`total_amount`, `order`.`status` FROM `order` LEFT JOIN `userproduct` ON `userproduct`.`order_id` = `order`.`id` WHERE `order`.`token` = ?\", [token], function(err, result){\n if(!err && result.length > 0)\n {\n console.log(result);\n if(result[0].status === 'complete'){\n res.view('error',{\n msg: \"Order Already completed or rejected\"\n });\n }\n else{\n var payFromWallet = false;\n var toBePayed = result[0].total_amount;\n var creditLeft = req.session.wallet;\n if(result[0].total_amount <= req.session.wallet){\n payFromWallet = true;\n toBePayed = 0;\n creditLeft = parseInt(req.session.wallet) - parseInt(result[0].total_amount);\n }\n else{\n toBePayed = parseInt(result[0].total_amount)-parseInt(req.session.wallet);\n creditLeft = 0;\n }\n res.view('payment',{\n cartList : result, \n total : result[0].total_amount,\n toBePayed : toBePayed,\n token:token, \n payFromWallet: payFromWallet,\n credits : req.session.wallet,\n creditLeft : creditLeft\n });\n }\n }\n else{\n res.view('error',{\n msg: \"Token mismatch\"\n });\n }\n });\n },\n generateOrderRecipt : function(req,res){\n var token = req.param('token');\n Order.query(\"SELECT `order`.`id`, `userproduct`.`product_name`, `userproduct`.`product_price`, `order`.`total_amount`, `order`.`status` FROM `order` LEFT JOIN `userproduct` ON `userproduct`.`order_id` = `order`.`id` WHERE `order`.`token` = ?\", [token], function(err, result){\n if(!err && result.length > 0)\n {\n res.view('recipt',{cartList : result, total : result[0].total_amount, status:result[0].status});\n }\n else{\n res.view('error',{\n msg: \"Token Mismatch\"\n });\n }\n });\n }\n};\n", "dangerousExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/dan', function (req, res) {\n5. const url = req.body.profile_url;\n6. try{\n7. res.redirect(url);\n8. }catch (e) {\n9. return res.status(500).send(\"ERROR\");\n10. }\n11. });\n12. \n13. module.exports = router;\nLine 7: A string variable URL of an unvalidated external input is used to connect.", "safeExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/safe', function (req, res) {\n5. const url = req.body.profile_url;\n6. const white_list = [\"https://www.safeurl.com\", \"https://www.verified.com\"];\n7. if (white_list.indexOf(url) < 0) {\n8. return res.status(500).send(\"url not allowed\");\n9. } else {\n10. try {\n11. res.redirect(url);\n12. } catch (e) {\n13. return res.status(500).send(\"ERROR\");\n14. }\n15. }\n16. });\n17. \n18. module.exports = router;\nLine 7-9: Validate external inputs through a filter function.", "contexts": [{"lineNo": 37, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "37"}}, {"lineNo": 38, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "req"}}, {"lineNo": 38, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "redirect"}}]}} {"id": "784b87a500a033e46adaa52b8d5d52f9fa891735d42f2908c926f78faf50534f", "license": {"spdx": ["MIT"], "repo": "JakinHuangWang/Blog", "path": "controllers/postAction.js", "repo_head_hexsha": "89b48962f8fb1f544e6c5193232f73eeaef572a6", "stack_hexsha": "c4ecfdaebb9fd1df0e30d9f31464a06c16bfee80", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Redirection to untrusted site", "issueDescriptionEn": "The Redirection to untrusted site checker finds instances of redirecting to a URL generated with an unvalidated external input.\nAlthough connecting to a client-provided URL is often believed to be safe, an attacker can modify the request and redirect the user to a malicious site.\nMaintain a whitelist of external site URLs and domains allowed for redirection, which needs to be checked when a user input is passed as a redirect URL.", "issueLineNumber": 40, "entireCode": "const BlogPost = require('../models/BlogPost');\nconst firebase = require('firebase/app')\nrequire('firebase/storage');\nconst { data } = require('jquery')\nglobal.XMLHttpRequest = require('xhr2');\n\nrequire('dotenv').config()\n\n\nconst firebaseConfig = {\n apiKey: process.env.API_KEY,\n authDomain: \"blog-10ed2.firebaseapp.com\",\n databaseURL: \"https://blog-10ed2.firebaseio.com\",\n projectId: \"blog-10ed2\",\n storageBucket: \"blog-10ed2.appspot.com\",\n messagingSenderId: \"462229385245\",\n appId: \"1:462229385245:web:cf2d1d79b2e0304570d6f4\",\n measurementId: \"G-PES0MWGV79\"\n};\nfirebase.initializeApp(firebaseConfig);\nconst storage = firebase.storage();\nconst storageRef = storage.ref();\nconst metadata = {\n contentType: 'image/jpeg',\n};\n\nexports.getPost = async (req, res) => {\n const blogpost = await BlogPost.findById(req.params.id);\n try{\n await storageRef.child(blogpost[\"image\"]).getDownloadURL().then( url => {\n res.render('post', {blogpost, url});\n });\n } catch(error) {\n res.redirect('/');\n }\n}\n\nexports.clickPost = async (req, res) => {\n const search = req.body['search'];\n res.redirect('/search/' + search);\n}\n\nexports.storePost = async (req, res) => {\n var data = {...req.body, date: new Date().toLocaleString()};\n if(req.files){\n let image = req.files.image;\n // var bytes = new Uint8Array(image.data);\n // image.mv(path.resolve(__dirname, 'public/img', image.name), async (error) => {\n // console.log(error);\n // });\n data['image'] = image.name;\n try{\n await storageRef.child(image.name).put(image.data, metadata);\n }catch(error){\n console.error(error);\n }\n }\n await BlogPost.create(data);\n res.redirect('/')\n}\n\nexports.createPost = async (req, res) => {\n res.render('create');\n}\n\nexports.searchPost = async (req, res) => {\n if(req.params.search === undefined){\n res.redirect('/');\n } else {\n const blogpost = await BlogPost.find({\n title: new RegExp(req.params.search)\n });\n res.render('search', {blogposts: blogpost})\n }\n}\n\n", "dangerousExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/dan', function (req, res) {\n5. const url = req.body.profile_url;\n6. try{\n7. res.redirect(url);\n8. }catch (e) {\n9. return res.status(500).send(\"ERROR\");\n10. }\n11. });\n12. \n13. module.exports = router;\nLine 7: A string variable URL of an unvalidated external input is used to connect.", "safeExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/safe', function (req, res) {\n5. const url = req.body.profile_url;\n6. const white_list = [\"https://www.safeurl.com\", \"https://www.verified.com\"];\n7. if (white_list.indexOf(url) < 0) {\n8. return res.status(500).send(\"url not allowed\");\n9. } else {\n10. try {\n11. res.redirect(url);\n12. } catch (e) {\n13. return res.status(500).send(\"ERROR\");\n14. }\n15. }\n16. });\n17. \n18. module.exports = router;\nLine 7-9: Validate external inputs through a filter function.", "contexts": [{"lineNo": 39, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "reqreq.body"}}, {"lineNo": 40, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "redirect"}}]}} {"id": "f71f4776e79795b9bfca186d2115c8a128b10bd0f91d2f08b2255bf9c2826e4c", "license": {"spdx": ["MIT"], "repo": "Ensemble3866/106NTUT_SE_PASS", "path": "routes/pass.js", "repo_head_hexsha": "968dda1622fcfbfd7afda13b3cefa3b0238331bc", "stack_hexsha": "994d1e4739e061a443bc9e0da07f9538552b3919", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Redirection to untrusted site", "issueDescriptionEn": "The Redirection to untrusted site checker finds instances of redirecting to a URL generated with an unvalidated external input.\nAlthough connecting to a client-provided URL is often believed to be safe, an attacker can modify the request and redirect the user to a malicious site.\nMaintain a whitelist of external site URLs and domains allowed for redirection, which needs to be checked when a user input is passed as a redirect URL.", "issueLineNumber": 230, "entireCode": "require('../lib/db');\nvar express = require('express');\nvar router = express.Router();\nvar mongoose = require('mongoose'); \nvar user = mongoose.model('user');\nvar course = mongoose.model('course');\nvar department = mongoose.model('department');\nvar assignment = mongoose.model('assignment');\nvar studentAssignment = mongoose.model('studentAssignment');\nvar path = require('path');\nvar fs = require('fs');\nvar util = require('util');\nvar formidable = require('formidable');\nvar archiver = require('archiver');\n\nrouter.use(function (req, res, next) {\n if(req.session.user == null){\n res.redirect('/');\n } else {\n next();\n }\n});\n\nrouter.get('/course', function(req, res, next) {\n res.render('course', { title: 'Express' });\n});\n\nrouter.get('/courseList', function(req, res, next) {\n user.findById(req.session.user._id)\n .populate({path: 'courses', populate: {path: 'classid'}})\n .populate({path: 'TACourse', populate: {path: 'classid'}})\n .populate('classid')\n .exec( function(err, _user) {\n res.render('courseList', { user : _user });\n })\n});\n\nrouter.get('/assignmentList/:courseId', function(req, res, next) {\n user.findById(req.session.user._id)\n .populate({path: 'courses', populate: {path: 'classid'}})\n .populate({path: 'TACourse', populate: {path: 'classid'}})\n .populate('classid')\n .exec( function(err, _user) {\n course.findById(req.params.courseId)\n .populate('assignment')\n .exec( function(err, _course) {\n req.session.curCourseId = req.params.courseId;\n res.render('assignmentList', { user : _user, course: _course });\n })\n })\n});\n\nrouter.get('/memberList/:courseId', function(req, res, next) {\n user.findById(req.session.user._id)\n .populate({path: 'courses', populate: {path: 'classid'}})\n .populate({path: 'TACourse', populate: {path: 'classid'}})\n .populate('classid')\n .exec( function(err, _user) {\n course.findById(req.params.courseId)\n .populate({path: 'TA', populate: {path: 'classid'}})\n .populate({path: 'studentAccount', populate: {path: 'classid'}})\n .exec( function(err, _course) {\n res.render('memberList', { user : _user, course: _course });\n })\n })\n});\n\nrouter.get('/correct/:assignmentId', function(req, res, next) {\n user.findById(req.session.user._id)\n .populate({path: 'courses', populate: {path: 'classid'}})\n .populate({path: 'TACourse', populate: {path: 'classid'}})\n .populate('classid')\n .exec( function(err, _user) {\n assignment.findById(req.params.assignmentId)\n .populate('courseid')\n .exec( function(err, _assignment) {\n studentAssignment.find()\n .where('assignmentId').equals(req.params.assignmentId)\n .populate({path: 'studentAccount'})\n .exec( function(err, _studentAssignment) {\n res.render('correct', { user : _user, studentAssignment: _studentAssignment, assignment: _assignment, courseId: req.session.curCourseId });\n })\n })\n })\n});\n\nrouter.get('/createAssignment/:courseId', function(req, res, next) {\n user.findById(req.session.user._id)\n .populate({path: 'courses', populate: {path: 'classid'}})\n .populate({path: 'TACourse', populate: {path: 'classid'}})\n .populate('classid')\n .exec( function(err, _user) {\n course.findById(req.params.courseId)\n .populate('assignment')\n .exec( function(err, _course) {\n req.session.curCourseId = req.params.courseId;\n res.render('createAssignment', { user : _user, course: _course });\n })\n })\n});\n\nrouter.get('/assignment/:assignmentId', function(req, res, next) {\n user.findById(req.session.user._id)\n .populate({path: 'courses', populate: {path: 'classid'}})\n .populate({path: 'TACourse', populate: {path: 'classid'}})\n .populate('classid')\n .exec( function(err, _user) {\n assignment.findById(req.params.assignmentId)\n .populate('courseid')\n .exec( function(err, _assignment) {\n req.session.curAssignmentId = req.params.assignmentId;\n req.session.curAssignmentName = _assignment.name;\n var filePath = path.join(__dirname, '../public/assignment/' + req.session.curAssignmentId + '/') + req.session.user.account + '_' + req.session.curAssignmentId + '.zip';\n fs.exists(filePath, function(ex){\n studentAssignment.findOne({studentAccount: req.session.user._id, assignmentId: req.session.curAssignmentId}, function(err, _studentAssignment) {\n var _score = null, _comment=\"\";\n \n if(_studentAssignment != null) {\n if(_studentAssignment.score == null)\n _score = \"-\";\n else{\n _score = _studentAssignment.score;\n if(_studentAssignment.comment == \"\")\n _comment = \" 分\" + _studentAssignment.comment;\n else\n _comment = \" 分,\" + _studentAssignment.comment;\n }\n }\n\n if(ex){\n res.render('assignment', { user : _user, assignment: _assignment, score: _score, comment: _comment, \n fileName: req.session.user.account + '_' + req.session.curAssignmentId + '.zip' });\n }\n else{\n res.render('assignment', { user : _user, assignment: _assignment, score: _score, comment: _comment, fileName: \"\" });\n }\n });\n });\n })\n })\n});\n\nrouter.get('/editAssignment/:assignmentId', function(req, res, next) {\n user.findById(req.session.user._id)\n .populate({path: 'courses', populate: {path: 'classid'}})\n .populate({path: 'TACourse', populate: {path: 'classid'}})\n .populate('classid')\n .exec( function(err, _user) {\n assignment.findById(req.params.assignmentId)\n .populate('courseid')\n .populate({path: 'courseid', populate: {path: 'studentAccount'}})\n .exec( function(err, _assignment) {\n res.render('editAssignment', { user : _user, assignment: _assignment });\n })\n })\n});\n\nrouter.get('/statistic/:courseId', function(req, res, next) {\n user.findById(req.session.user._id)\n .populate({path: 'courses', populate: {path: 'classid'}})\n .populate({path: 'TACourse', populate: {path: 'classid'}})\n .populate('classid')\n .exec( function(err, _user) {\n course.findById(req.params.courseId)\n .exec( function(err, _course) {\n req.session.curCourseId = req.params.courseId;\n res.render('statistic', { user : _user, course: _course });\n })\n })\n});\n\nrouter.post('/uploadAssignment', function(req, res, next){\n \n var form = new formidable.IncomingForm();\n form.maxFieldsSize = 5 * 1024 * 1024;\n form.keepExtensions = true;\n form.encoding = 'utf-8';\n\n form.parse(req, function (err, fields, file) {\n var filePath = '';\n if(file.selectFile) filePath = file.selectFile.path;\n \n var targetDir = path.join(__dirname, '../public/assignment/' + req.session.curAssignmentId);\n if (!fs.existsSync(targetDir)) {\n fs.mkdir(targetDir);\n }\n\n var fileExt = filePath.substring(filePath.lastIndexOf('.'));\n \n if (('.zip').indexOf(fileExt.toLowerCase()) === -1)\n {\n var err = new Error('上傳檔案非zip!');\n res.json({code:-1, message:'上傳檔案非zip!'});\n }\n else\n {\n var fileName = req.session.user.account + '_' + req.session.curAssignmentId + fileExt;\n var targetFile = path.join(targetDir, fileName);\n\n // 系統位於C:/時\n //fs.renameSync(filePath, targetFile);\n //系統位於C:/以外時\n var readStream = fs.createReadStream(filePath)\n var writeStream = fs.createWriteStream(targetFile);\n \n readStream.pipe(writeStream);\n readStream.on('end',function() {\n fs.unlinkSync(filePath);\n });\n studentAssignment.findOne()\n .where('assignmentId').equals(req.session.curAssignmentId)\n .where('studentAccount').equals(req.session.user.account).exec(function(err, _studentAssignment){\n if(err) next(err);\n else if(_studentAssignment == null) res.send(\"Database update fail.\");\n else{\n if(_studentAssignment.fileURL == null){\n assignment.findById(req.session.curAssignmentId, function(err, _assignment){\n _assignment.hanginCount += 1;\n _assignment.save(function(err){\n console.log(\"已上傳人數增加失敗!\");\n });\n });\n }\n _studentAssignment.fileURL = fileName;\n _studentAssignment.save(function(err){\n console.log(\"Student assignment save suceess.\");\n });\n }\n });\n res.redirect('/pass/assignmentList/' + req.session.curCourseId);\n }\n });\n});\n\nrouter.get('/assignment/download/:fileName', function(req, res, next) {\n var filePath = path.join(__dirname, '../public/assignment/'+ req.session.curAssignmentId + '/') + req.params.fileName;\n res.download(filePath, filePath, function(err){\n if (err) {\n next(err);\n } else {\n res.end();\n }\n });\n});\n\nrouter.get('/assignment/downloadAll/:assignmentId', function(req, res, next){\n var targetDir = path.join(__dirname, '../public/assignment/');\n var targetFile = targetDir + '/' + req.params.assignmentId + '.zip';\n var output = fs.createWriteStream(targetFile);\n var archive = archiver('zip');\n\n archive.on('error', function(err){\n throw err;\n });\n \n output.on('close', function() {\n console.log(archive.pointer() + ' total bytes');\n console.log('archiver has been finalized and the output file descriptor has closed.');\n res.download(targetFile , targetFile, function(err){\n if (err) next(err);\n else {\n fs.unlink(targetFile, function(err){\n if(err) next(err);\n res.end();\n });\n }\n });\n });\n\n archive.pipe(output);\n archive.directory(targetDir + '/' + req.session.curAssignmentId, false);\n archive.finalize();\n});\n\nrouter.post('/createAssignment', function(req, res, next) {\n assignment.findOne()\n .where('name').equals(req.body.name)\n .exec(function(err, _assignment){\n if(err) {\n next(err);\n }\n else if(_assignment != null){\n res.send(\"作業名稱重複!!\");\n }\n else {\n assignment.create(req.body, function(err, _assignment) {\n course.findOneAndUpdate({_id: _assignment.courseid}, {\"$push\": { assignment: _assignment._id }}, function(err, _course) {\n _course.studentAccount.forEach(function(student){\n var newStudentAssignment = new studentAssignment({\n assignmentId : _assignment._id,\n studentAccount : student\n });\n newStudentAssignment.save(function(err){\n if(err) next(err);\n });\n });\n });\n });\n res.send(\"success\");\n }\n });\n});\n\nrouter.patch('/editAssignment', function(req, res, next) {\n assignment.findOneAndUpdate({_id: req.body._id}, req.body, function(err, _assignment) {\n res.send(\"success\");\n });\n});\n\nrouter.delete('/deleteAssignment', function(req, res, next) {\n assignment.findOneAndRemove({_id: req.body.assignmentId}, function(error, doc, _assignment) {\n course.findByIdAndUpdate(req.body.courseId, { \"$pull\": { assignment: req.body.assignmentId }}, function (err, doc) {\n studentAssignment.remove({ assignmentId : req.body.assignmentId }, function(err){\n if(err) next(err);\n else res.send(\"success\");\n });\n });\n });\n});\n\nrouter.patch('/correctAssignment', function(req, res, next) {\n var jsonArray = JSON.parse(req.body.data);\n\n jsonArray.forEach(function(_studentAssignment) {\n studentAssignment.findOneAndUpdate({_id: _studentAssignment._id}, _studentAssignment, function(err, _assignment) {\n });\n });\n\n setTimeout(function() {\n res.send(\"success\");\n }, 2000);\n});\n\nrouter.get('/statistic/getAvgScores/:courseId', function(req, res, next) {\n var avgScores = [];\n\n course.findById(req.params.courseId)\n .populate('assignment')\n .exec(function(err, _course) {\n var findCount = 0;\n for (let j=0; j<_course.assignment.length; j++) {\n studentAssignment.find({assignmentId: _course.assignment[j]._id}, function(err, _studentAssignments){\n var totalScore = 0;\n for(var i in _studentAssignments){\n totalScore += _studentAssignments[i].score;\n }\n\n avgScores[j] = parseFloat((totalScore / _studentAssignments.length).toFixed(2));\n findCount ++;\n\n if (findCount == _course.assignment.length)\n res.send(avgScores);\n });\n }\n })\n});\n\nrouter.get('/statistic/getPersonalScores/:courseId/:studentId', function(req, res, next) {\n var personalScores = [];\n\n course.findById(req.params.courseId)\n .populate('assignment')\n .exec(function(err, _course) {\n var findCount = 0;\n for (let j=0; j<_course.assignment.length; j++) {\n studentAssignment.find({assignmentId: _course.assignment[j]._id, studentAccount: req.params.studentId}, function(err, _studentAssignments){\n if (_studentAssignments[0].score)\n personalScores[j] = _studentAssignments[0].score;\n else\n personalScores[j] = 0;\n findCount ++;\n\n if (findCount == _course.assignment.length)\n res.send(personalScores);\n });\n }\n })\n});\n\nrouter.get('/statistic/getHangin/:courseId', function(req, res, next) {\n var hanginCount = [];\n\n course.findById(req.params.courseId)\n .populate('assignment')\n .exec(function(err, _course) {\n var findCount = 0;\n for (let j=0; j<_course.assignment.length; j++) {\n assignment.findById(_course.assignment[j]._id, function(err, _assignment){\n\n hanginCount[j] = _assignment.hanginCount;\n findCount ++;\n\n if (findCount == _course.assignment.length)\n res.send(hanginCount);\n });\n }\n })\n});\n\n\nmodule.exports = router;\n", "dangerousExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/dan', function (req, res) {\n5. const url = req.body.profile_url;\n6. try{\n7. res.redirect(url);\n8. }catch (e) {\n9. return res.status(500).send(\"ERROR\");\n10. }\n11. });\n12. \n13. module.exports = router;\nLine 7: A string variable URL of an unvalidated external input is used to connect.", "safeExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/safe', function (req, res) {\n5. const url = req.body.profile_url;\n6. const white_list = [\"https://www.safeurl.com\", \"https://www.verified.com\"];\n7. if (white_list.indexOf(url) < 0) {\n8. return res.status(500).send(\"url not allowed\");\n9. } else {\n10. try {\n11. res.redirect(url);\n12. } catch (e) {\n13. return res.status(500).send(\"ERROR\");\n14. }\n15. }\n16. });\n17. \n18. module.exports = router;\nLine 7-9: Validate external inputs through a filter function.", "contexts": [{"lineNo": 230, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "req"}}, {"lineNo": 230, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "redirect"}}]}} {"id": "56774474525d382e19483e1b932dc37cefa62334789d487b7f8c8d5bd628d209", "license": {"spdx": ["Apache-2.0"], "repo": "russjohnson09/examples-oauth", "path": "oauth2-example-master/app.js", "repo_head_hexsha": "a1a1281bf876e32c978609eecd48c70884ce08aa", "stack_hexsha": "d12224144f6cdbe551b54decaa5d6b7799416dd6", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Redirection to untrusted site", "issueDescriptionEn": "The Redirection to untrusted site checker finds instances of redirecting to a URL generated with an unvalidated external input.\nAlthough connecting to a client-provided URL is often believed to be safe, an attacker can modify the request and redirect the user to a malicious site.\nMaintain a whitelist of external site URLs and domains allowed for redirection, which needs to be checked when a user input is passed as a redirect URL.", "issueLineNumber": 60, "entireCode": "var express = require('express');\nvar routes = require('./routes');\nvar config = require('./config');\nvar path = require('path');\nvar models = require('./models');\nvar middleware = require('./middleware');\nvar app = express();\nvar oauthserver = require('node-oauth2-server');\nvar User = models.User;\n\napp.set('env', process.env.NODE_ENV || 'development');\napp.set('port', process.env.PORT || 3000);\napp.set('views', path.join(__dirname, 'views'));\napp.set('view engine', 'jade');\napp.use(express.cookieParser('ncie0fnft6wjfmgtjz8i'));\napp.use(express.cookieSession());\n\napp.locals.title = 'OAuth Example';\napp.locals.pretty = true;\n\napp.configure('development', 'production', function() {\n app.use(express.logger('dev'));\n});\n\napp.use(express.bodyParser());\napp.use(express.methodOverride());\n\napp.oauth = oauthserver({\n model: models.oauth,\n grants: ['password', 'authorization_code', 'refresh_token'],\n debug: true\n});\n\napp.use(app.router);\napp.use(express.static(path.join(__dirname, 'public')));\n\napp.use(function(err, req, res, next) {\n if (process.env.NODE_ENV !== 'test')\n console.error('Error:', err);\n\n if (middleware.isValidationError(err)) {\n res.status(400);\n res.send(err.errors);\n } else {\n res.status(err.code || 500);\n res.send('Error');\n }\n});\n\nif ('development' === app.get('env')) {\n app.use(express.errorHandler());\n}\n\napp.get('/', middleware.loadUser, routes.index);\n\napp.all('/oauth/token', app.oauth.grant());\n\napp.get('/oauth/authorise', function(req, res, next) {\n if (!req.session.userId) {\n return res.redirect('/session?redirect=' + req.path + '&client_id=' +\n req.query.client_id + '&redirect_uri=' + req.query.redirect_uri);\n }\n\n res.render('authorise', {\n client_id: req.query.client_id,\n redirect_uri: req.query.redirect_uri\n });\n});\n\n// Handle authorise\napp.post('/oauth/authorise', function(req, res, next) {\n if (!req.session.userId) {\n return res.redirect('/session?redirect=' + req.path + 'client_id=' +\n req.query.client_id +'&redirect_uri=' + req.query.redirect_uri);\n }\n\n next();\n}, app.oauth.authCodeGrant(function(req, next) {\n // The first param should to indicate an error\n // The second param should a bool to indicate if the user did authorise the app\n // The third param should for the user/uid (only used for passing to saveAuthCode)\n next(null, req.body.allow === 'yes', req.session.userId, null);\n}));\n\napp.get('/secret', middleware.requiresUser, function(req, res) {\n res.send('Secret area');\n});\n\napp.use(app.oauth.errorHandler());\n\napp.post('/v1/users', routes.users.create);\napp.get('/account', middleware.requiresUser, routes.users.show);\napp.post('/session', routes.session.create);\napp.get('/session', routes.session.show);\n\nmodule.exports = app;", "dangerousExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/dan', function (req, res) {\n5. const url = req.body.profile_url;\n6. try{\n7. res.redirect(url);\n8. }catch (e) {\n9. return res.status(500).send(\"ERROR\");\n10. }\n11. });\n12. \n13. module.exports = router;\nLine 7: A string variable URL of an unvalidated external input is used to connect.", "safeExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/safe', function (req, res) {\n5. const url = req.body.profile_url;\n6. const white_list = [\"https://www.safeurl.com\", \"https://www.verified.com\"];\n7. if (white_list.indexOf(url) < 0) {\n8. return res.status(500).send(\"url not allowed\");\n9. } else {\n10. try {\n11. res.redirect(url);\n12. } catch (e) {\n13. return res.status(500).send(\"ERROR\");\n14. }\n15. }\n16. });\n17. \n18. module.exports = router;\nLine 7-9: Validate external inputs through a filter function.", "contexts": [{"lineNo": 59, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "59"}}, {"lineNo": 60, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "redirect"}}, {"lineNo": 61, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "req"}}]}} {"id": "75c6a17a50b059cd0d6efc57d4f7606f87bcb326a600d8d37080674ef79d9cce", "license": {"spdx": ["MIT"], "repo": "mehrdad-shokri/strider", "path": "apps/strider/lib/routes/index.js", "repo_head_hexsha": "371b0850ace2d6c55afe615e45fe3dba6b58382a", "stack_hexsha": "97bd84ec2657e8829f3dbdd357f3db3c66dcd3f3", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Redirection to untrusted site", "issueDescriptionEn": "The Redirection to untrusted site checker finds instances of redirecting to a URL generated with an unvalidated external input.\nAlthough connecting to a client-provided URL is often believed to be safe, an attacker can modify the request and redirect the user to a malicious site.\nMaintain a whitelist of external site URLs and domains allowed for redirection, which needs to be checked when a user input is passed as a redirect URL.", "issueLineNumber": 24, "entireCode": "const _ = require('lodash');\nconst common = require('../common');\nconst config = require('../config');\nconst debug = require('debug')('strider:routes');\nconst jobs = require('../jobs');\nconst models = require('../models');\nconst path = require('path');\nconst pjson = require('../../package.json');\nconst User = models.User;\nconst utils = require('../utils');\n\n/*\n * GET home page dashboard\n */\nexports.index = function (req, res) {\n // Work-around for Safari/Express etags bug on cookie logout.\n // Without it, Safari will cache the logged-in version despite logout!\n // See https://github.com/Strider-CD/strider/issues/284\n req.headers['if-none-match'] = 'no-match-for-this';\n\n if (req.session.return_to) {\n const return_to = req.session.return_to;\n req.session.return_to = null;\n return res.redirect(return_to);\n }\n\n let code = '';\n\n if (req.query.code !== undefined) {\n code = req.query.code;\n\n return res.render('register.html', {\n invite_code: code,\n version: pjson.version,\n });\n }\n\n if (!req.user) {\n return res.redirect('/login?ember=true');\n }\n\n jobs.latestJobs(req.user, true, function (err, jobs) {\n const availableProviders = Object.keys(common.userConfigs.provider).map(\n function (k) {\n return common.userConfigs.provider[k];\n }\n );\n\n res.render('index.html', {\n jobs: jobs,\n availableProviders: availableProviders,\n flash: req.flash(),\n version: pjson.version,\n });\n });\n};\n\nexports.emberIndex = function (req, res) {\n // Work-around for Safari/Express etags bug on cookie logout.\n // Without it, Safari will cache the logged-in version despite logout!\n // See https://github.com/Strider-CD/strider/issues/284\n req.headers['if-none-match'] = 'no-match-for-this';\n\n if (req.session.return_to) {\n const return_to = req.session.return_to;\n req.session.return_to = null;\n return res.redirect(return_to);\n }\n\n if (req.query.ember) {\n // TODO: only set if dev\n res.header('Cache-Control', 'private, no-cache, no-store, must-revalidate');\n res.render('ember/index.html');\n }\n};\n\nexports.setConfig = function (req, res) {\n const attrs = ['public'];\n\n applyAttrs(req.project, attrs, req.body);\n\n req.project.save(function (err) {\n if (err) return res.status(500).send('failed to save project');\n res.send('saved');\n });\n};\n\nexports.getRunnerConfig = function (req, res) {\n const branch = req.project.branch(req.query.branch);\n\n if (!branch) {\n return res.status(400).send('Invalid branch');\n }\n\n res.send(branch.runner);\n};\n\nexports.setRunnerConfig = function (req, res) {\n const branch = req.project.branch(req.query.branch);\n branch.runner.config = req.body;\n\n req.project.save(function (err, project) {\n if (err) {\n return res.status(500).send({\n error: 'Failed to save runner config',\n });\n }\n\n res.send(project.branch(req.query.branch).runner.config);\n });\n};\n\nexports.setRunnerId = function (req, res) {\n const branch = req.project.branch(req.query.branch);\n\n branch.runner.id = req.body.id;\n branch.runner.config = req.body.config;\n\n req.project.save(function (err, project) {\n if (err) {\n return res.status(500).send({\n error: 'Failed to save runner config',\n });\n }\n\n res.send(project.branch(req.query.branch).runner.id);\n });\n};\n\n// GET /:org/:repo/config/branch/:pluginname/?branch=:branch\n// Output: the config\nexports.getPluginConfig = function (req, res) {\n res.send(req.pluginConfig());\n};\n\n// POST /:org/:repo/config/branch/:plugin/?branch=:branch\n// Set the configuration for a plugin on a branch. Output: the new config.\nexports.setPluginConfig = function (req, res) {\n req.pluginConfig(req.body, function (err, config) {\n if (err) {\n return res.status(500).send({\n error: 'Failed to save plugin config',\n });\n }\n\n res.send(config);\n common.emitter.emit(\n 'branch.plugin_config',\n req.project,\n req.query.branch,\n req.params.plugin,\n req.body\n );\n });\n};\n\nexports.configureBranch = function (req, res) {\n const branch = req.project.branch(req.query.branch);\n\n if (!branch) {\n return res.status(400).send('Invalid branch');\n }\n\n if (req.body.plugin_order) {\n return setPluginOrder(req, res, branch);\n }\n\n // TODO: move this somewhere else?\n const attrs = [\n 'active',\n 'privkey',\n 'pubkey',\n 'envKeys',\n 'mirror_master',\n 'deploy_on_green',\n 'deploy_on_pull_request',\n 'runner',\n 'plugins',\n ];\n\n applyAttrs(branch, attrs, req.body);\n\n req.project.save(function (err) {\n if (err) {\n return res.status(500).send('failed to save project');\n }\n\n res.status(200).send('saved');\n });\n};\n\nfunction setPluginOrder(req, res, branch) {\n const plugins = req.body.plugin_order;\n const oldPlugins = branch.plugins || [];\n const map = {};\n\n oldPlugins.forEach(function (plugin) {\n map[plugin.id] = plugin;\n });\n\n plugins.forEach(function (plugin) {\n if (map[plugin.id]) {\n plugin.config = map[plugin.id].config;\n } else {\n plugin.config = {};\n }\n });\n\n branch.plugins = plugins;\n req.project.markModified('branches');\n\n req.project.save(function (err) {\n if (err) {\n return res.status(500).send('Failed to save plugin config');\n }\n\n res.send({ success: true });\n common.emitter.emit(\n 'branch.plugin_order',\n req.project,\n branch.name,\n plugins\n );\n });\n}\n\nexports.reloadConfig = function (req, res, next) {\n common.loader.initConfig(\n path.join(__dirname, 'public/javascripts/pages/config-plugins-compiled.js'),\n path.join(__dirname, 'public/stylesheets/css/config-plugins-compiled.css'),\n function (err, configs) {\n debug('loaded config pages');\n common.pluginConfigs = configs;\n\n common.loader.initUserConfig(\n path.join(\n __dirname,\n 'public/javascripts/pages/account-plugins-compiled.js'\n ),\n path.join(\n __dirname,\n 'public/stylesheets/css/account-plugins-compiled.css'\n ),\n function (err, configs) {\n debug('loaded account config pages');\n common.userConfigs = configs;\n next();\n }\n );\n }\n );\n};\n\n/*\n * GET /:org/:repo/config - project config page\n */\nexports.config = function (req, res) {\n User.collaborators(req.project.name, 0, function (err, users) {\n if (err) {\n throw err;\n }\n\n const data = {\n version: pjson.version,\n collaborators: [],\n serverName: config.server_name,\n project: req.project.toJSON(),\n statusBlocks: common.statusBlocks,\n userIsCreator: req.user.isProjectCreator,\n };\n\n if (req.user.isProjectCreator) {\n data.userConfigs = req.user.jobplugins;\n }\n\n delete data.project.creator;\n\n users.forEach(function (user) {\n const p = _.find(user.projects, function (p) {\n return p.name === req.project.name;\n });\n\n data.collaborators.push({\n email: user.email,\n access: p.access_level,\n gravatar: utils.gravatar(user.email),\n owner: user._id.toString() === req.project.creator._id.toString(),\n yourself: req.user._id.toString() === user._id.toString(),\n });\n });\n\n data.provider = common.pluginConfigs.provider[req.project.provider.id];\n data.runners = common.pluginConfigs.runner;\n data.plugins = common.pluginConfigs.job;\n\n data.collaborators.sort(function (a, b) {\n if (a.owner) return -1;\n if (b.owner) return 1;\n return 0;\n });\n\n const provider = common.extensions.provider[req.project.provider.id];\n const creator_creds = req.project.creator.account(req.project.provider)\n .config;\n\n if (!provider) {\n // TODO: alert the user through the UI\n debug('Provider plugin not installed!', req.project.provider.id);\n return respond(data);\n }\n\n if (\n typeof provider.getBranches === 'function' &&\n (!provider.hosted || creator_creds)\n ) {\n provider.getBranches(\n creator_creds,\n req.project.provider.config,\n req.project,\n function (err, branches) {\n data.allBranches = branches;\n respond(data);\n }\n );\n } else {\n respond(data);\n }\n });\n\n function respond(data) {\n res.format({\n html: function () {\n res.render('project_config.html', data);\n },\n json: function () {\n res.send(data);\n },\n });\n }\n};\n\n/*\n * /status endpoint\n * Executes a simple database query to verify that system is operational.\n * Assumes there is at least 1 user in the system.\n * Returns 200 on success.\n *\n * This is for use by Pingdom and similar monitoring systems.\n */\nexports.status = function (req, res) {\n function error(message) {\n res.statusCode = 500;\n\n const resp = {\n status: 'error',\n version: `StriderCD (http://stridercd.com) ${pjson.version}`,\n results: [],\n errors: [{ message: message }],\n };\n\n return res.jsonp(resp);\n }\n\n function ok() {\n res.statusCode = 200;\n\n const resp = {\n status: 'ok',\n version: `StriderCD (http://stridercd.com) ${pjson.version}`,\n results: [{ message: 'system operational' }],\n errors: [],\n };\n\n return res.jsonp(resp);\n }\n\n User.findOne(function (err, user) {\n if (err) {\n return error(`error retrieving user from DB: ${err}`);\n }\n\n if (!user) {\n return error('no users found in DB - mis-configured?');\n }\n\n return ok();\n });\n};\n\nfunction applyAttrs(obj, attrs, source) {\n attrs.forEach(function (attr) {\n if (typeof source[attr] !== 'undefined') {\n obj[attr] = source[attr];\n }\n });\n}", "dangerousExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/dan', function (req, res) {\n5. const url = req.body.profile_url;\n6. try{\n7. res.redirect(url);\n8. }catch (e) {\n9. return res.status(500).send(\"ERROR\");\n10. }\n11. });\n12. \n13. module.exports = router;\nLine 7: A string variable URL of an unvalidated external input is used to connect.", "safeExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/safe', function (req, res) {\n5. const url = req.body.profile_url;\n6. const white_list = [\"https://www.safeurl.com\", \"https://www.verified.com\"];\n7. if (white_list.indexOf(url) < 0) {\n8. return res.status(500).send(\"url not allowed\");\n9. } else {\n10. try {\n11. res.redirect(url);\n12. } catch (e) {\n13. return res.status(500).send(\"ERROR\");\n14. }\n15. }\n16. });\n17. \n18. module.exports = router;\nLine 7-9: Validate external inputs through a filter function.", "contexts": [{"lineNo": 21, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "21"}}, {"lineNo": 22, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "req"}}, {"lineNo": 22, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 24, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "redirect"}}]}} {"id": "6121b56fe365e52603e25e8680b7867e4ffdddcc429dd7ba631a4c378d3ad424", "license": {"spdx": ["MIT"], "repo": "imomarksasa/abayro-old-website", "path": "src/server.js", "repo_head_hexsha": "cea41a683fbff7362672504f3c2f05d1736deee0", "stack_hexsha": "068db8763e0ac258c9cb80b72c120ea1a17f8774", "match": "repo_path"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Redirection to untrusted site", "issueDescriptionEn": "The Redirection to untrusted site checker finds instances of redirecting to a URL generated with an unvalidated external input.\nAlthough connecting to a client-provided URL is often believed to be safe, an attacker can modify the request and redirect the user to a malicious site.\nMaintain a whitelist of external site URLs and domains allowed for redirection, which needs to be checked when a user input is passed as a redirect URL.", "issueLineNumber": 83, "entireCode": "const { tokens } = require('../bot/struct/bot');\nconst { resolve } = require('path');\nconst { Client, EvaluatedPermissions } = require('discord.js');\nconst express = require('express');\nconst passport = require('passport');\nconst session = require('express-session');\nconst MemoryStore = require('memorystore')(session);\nconst Strategy = require('passport-discord').Strategy;\nconst url = require('url');\nconst helmet = require('helmet');\nconst moment = require('moment');\nconst client = new Client();\nclient.login(tokens.discord);\n\n\nconst app = express();\napp.set('view engine', 'ejs');\napp.use(express.static(resolve(__dirname, 'public')));\napp.set('views', __dirname);\n\napp.get('/support', (req, res) => {\n\tres.redirect('https://discord.gg/yWyz5YE');\n});\npassport.serializeUser((user, done) => {\n\tdone(null, user);\n});\npassport.deserializeUser((obj, done) => {\n\tdone(null, obj);\n});\n\npassport.use(new Strategy({\n\tclientID: '484766518438133760',\n\tclientSecret: '',\n\tcallbackURL: 'https://beta.abayro.xyz/auth',\n\tscope: ['identify', 'guilds', 'guilds.join']\n},\n(accessToken, refreshToken, profile, done) => {\n\tprocess.nextTick(() => done(null, profile));\n}));\napp.use(session({\n\tstore: new MemoryStore({\n\t\tcheckPeriod: 86400000\n\t}),\n\tsecret: 'clientsessiosabayrosecret123123123',\n\tresave: false,\n\tsaveUninitialized: false\n}));\napp.use(passport.initialize());\napp.use(passport.session());\napp.use(helmet());\napp.locals.domain = 'beta.abayro.xyz';\nconst bodyParser = require('body-parser');\napp.use(bodyParser.json());\napp.use(bodyParser.urlencoded({\n\textended: true\n}));\n\nfunction checkAuth(req, res, next) {\n\tif (req.isAuthenticated()) return next();\n\treq.session.backURL = req.url;\n\tres.redirect('/login');\n}\napp.get('/login', (req, res, next) => {\n\tif (req.session.backURL) {\n\t\treq.session.backURL = 'https://beta.abayro.xyz/auth';\n\t} else if (req.headers.referer) {\n\t\tconst parsed = url.parse(req.headers.referer);\n\t\tif (parsed.hostname === app.locals.domain) {\n\t\t\treq.session.backURL = parsed.path;\n\t\t}\n\t} else {\n\t\treq.session.backURL = '/dashboard';\n\t}\n\tnext();\n},\npassport.authenticate('discord'));\napp.get('/auth', passport.authenticate('discord', {\n\tfailureRedirect: '/autherror'\n}), (req, res) => {\n\tif (req.session.backURL) {\n\t\tconst refurl = req.session.backURL;\n\t\treq.session.backURL = null;\n\t\tres.redirect(refurl);\n\t} else {\n\t\tres.redirect('/dashboard');\n\t}\n});\n\napp.get('/autherror', (req, res) => {\n\tres.render(res, req, 'views/pages/autherror.ejs');\n});\n\n\napp.get('/dashboard', checkAuth, (req, res) => {\n\tconst user = req.isAuthenticated() ? req.user : null;\n\tconst botStats = [{\n\t\tbotty: client,\n\t\tperms: EvaluatedPermissions,\n\t\tuser: req.isAuthenticated() ? req.user : null\n\t}];\n\tres.render('views/pages/dashboard', {\n\t\tbot: botStats, user, settings\n\t});\n});\n\napp.get('/guilds/:guildID', checkAuth, (req, res) => {\n\tres.redirect(`/guilds/${req.params.guildID}/manage`);\n});\n\napp.get('/user/:userID', checkAuth, (req, res) => {\n\tconst user = req.isAuthenticated() ? req.user : null;\n\tres.redirect(`/user/${user.id}/stats`);\n});\n\napp.get('/copyrighted-b601120a3e37bacb.html', (req, res) => {\n\tres.render('views/pages/copyrighted-b601120a3e37bacb.ejs');\n});\napp.get('/user/:userID/stats', checkAuth, (req, res) => {\n\tconst userStats = [{\n\t\tbotty: client,\n\t\tuser: req.isAuthenticated() ? req.user : null\n\t}];\n\tres.render('user/stats', {\n\t\tbot: userStats\n\t});\n});\n\napp.get('/user/:userID/pcard', checkAuth, (req, res) => {\n\tconst userStats = [{\n\t\tbotty: client,\n\t\tuser: req.isAuthenticated() ? req.user : null\n\t}];\n\tres.render('user/pcard', {\n\t\tbot: userStats\n\t});\n});\n\n\napp.get('/abayro-js/css/main.css', (req, res) => {\n\tres.redirect('/abayro/api/v3/stylesheets/css/scss/css/ABAYRO-STYLESHEET-NOURELDIEN[1].theme.css');\n});\n\napp.get('/store/profile', checkAuth, (req, res) => {\n\tconst userStats = [{\n\t\tbotty: client,\n\t\tuser: req.isAuthenticated() ? req.user : null\n\t}];\n\tres.render('shop', {\n\t\tbot: userStats\n\t});\n});\n\napp.get('/guilds/:guildID/manage', checkAuth, (req, res) => {\n\tconst guild = client.guilds.get(req.params.guildID);\n\tif (!guild) return res.status(404);\n\tconst isManaged = guild && Boolean(guild.member(req.user.id)) ? guild.member(req.user.id).permissions.has('MANAGE_GUILD') : false;\n\tif (!isManaged && !req.session.isAdmin) res.redirect('/');\n\tconst groles = app.get(`https://discordapp.com/api/v6/guilds/${req.params.guildID}/roles`);\n\tconst user = req.isAuthenticated() ? req.user : null;\n\tconst botStats = [{\n\t\tbot: client,\n\t\tperms: EvaluatedPermissions,\n\t\tmoment,\n\t\tguildroles: groles\n\t}];\n\tres.render('views/guild/manage.ejs', {\n\t\tguild,\n\t\tuser,\n\t\tsettings,\n\t\tbot: botStats\n\t});\n});\n\n\napp.get('/leaderboard/servers', (req, res) => {\n\tconst bot = client;\n\tconst user = req.isAuthenticated() ? req.user : null;\n\tres.render('views/pages/gleaders', {\n\t\tbot, user\n\t});\n});\n\napp.get('/leaderboard/servers/2', (req, res) => {\n\tconst bot = client;\n\tconst user = req.isAuthenticated() ? req.user : null;\n\tres.render('views/pages/gleaders2', {\n\t\tbot, user\n\t});\n});\n\napp.get('/leaderboard/servers/3', (req, res) => {\n\tconst bot = client;\n\tconst user = req.isAuthenticated() ? req.user : null;\n\tres.render('views/pages/gleaders3', {\n\t\tbot, user\n\t});\n});\n\napp.post('/guilds/:guildID/manage', checkAuth, (req, res) => {\n\tconst guild = client.guilds.get(req.params.guildID);\n\tif (!guild) return res.status(404);\n\tconst isManaged = guild && Boolean(guild.member(req.user.id)) ? guild.member(req.user.id).permissions.has('MANAGE_GUILD') : false;\n\tif (!isManaged && !req.session.isAdmin) res.redirect('/');\n\t// client.writeSettings(guild.id, req.body);\n\tres.redirect(`/guilds/${req.params.guildID}/manage`);\n});\n\napp.get('/api/', (req, res) => {\n\tres.render('views/pages/autherror');\n});\n\napp.get('/logout', (req, res) => {\n\treq.session.destroy(() => {\n\t\treq.logout();\n\t\tres.redirect('/');\n\t});\n});\n\napp.get('/', (req, res) => {\n\tconst guildCount = client.guilds.size;\n\tconst botStatus = client.user.presence.status;\n\tconst usersCount = client.users.size;\n\tconst bot = client;\n\tconst user = req.isAuthenticated() ? req.user : null;\n\tconst useradmin = req.session.isAdmin;\n\tres.render('views/pages/index', {\n\t\tguildCount, botStatus, usersCount, bot, user, useradmin\n\t});\n});\n\napp.get('/api/v4/abayro-js', (req, res) => {\n\tres.render('views/pages/autherror');\n});\n\napp.get('/about', (req, res) => {\n\tconst user = req.isAuthenticated() ? req.user : null;\n\tconst abdevs = client.guilds.get('470205496259772437').roles.get('470214128758423573').members\n\tconst abteam = client.guilds.get('470205496259772437').roles.get('471388844441468948').members.filter(member => !member.roles.has('470214128758423573'))\n\tconst contribs = client.guilds.get('470205496259772437').roles.get('541696997648891924').members.filter(member => !member.roles.has('470214128758423573'))\n\tres.render('views/pages/about', {\n\t\tuser, abdevs, abteam, contribs\n\t});\n});\n\napp.get('/premium', (req, res) => {\n\tconst botStats = [{\n\t\tbot: client,\n\t\tuser: req.isAuthenticated() ? req.user : null\n\t}];\n\tres.render('views/pages/premium', { bot: botStats });\n});\n\napp.get('/premium/subscribe', (req, res) => {\n\tconst botStats = [{\n\t\tbot: client,\n\t\tuser: req.isAuthenticated() ? req.user : null\n\t}];\n\tres.render('views/pages/subscribe', { bot: botStats });\n});\n\napp.get('/store', checkAuth, (req, res) => {\n\tres.render('views/pages/store');\n});\napp.get('/features', (req, res) => {\n\tconst user = req.isAuthenticated() ? req.user : null;\n\tres.render('views/pages/features', {\n\t\tclient, user\n\t});\n});\n\napp.get('/invite', (req, res) => {\n\tres.redirect(`https://discordapp.com/api/oauth2/authorize?client_id=484766518438133760&permissions=8&scope=bot`);\n});\napp.listen(3000);\n\napp.get('*', (req, res) => {\n\tif (res.status(404)) {\n\t\tconst bot = client;\n\t\tconst user = req.isAuthenticated() ? req.user : null;\n\t\tres.render('views/errors/notfound.ejs', {\n\t\t\tbot, user\n\t\t});\n\t}\n});", "dangerousExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/dan', function (req, res) {\n5. const url = req.body.profile_url;\n6. try{\n7. res.redirect(url);\n8. }catch (e) {\n9. return res.status(500).send(\"ERROR\");\n10. }\n11. });\n12. \n13. module.exports = router;\nLine 7: A string variable URL of an unvalidated external input is used to connect.", "safeExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/safe', function (req, res) {\n5. const url = req.body.profile_url;\n6. const white_list = [\"https://www.safeurl.com\", \"https://www.verified.com\"];\n7. if (white_list.indexOf(url) < 0) {\n8. return res.status(500).send(\"url not allowed\");\n9. } else {\n10. try {\n11. res.redirect(url);\n12. } catch (e) {\n13. return res.status(500).send(\"ERROR\");\n14. }\n15. }\n16. });\n17. \n18. module.exports = router;\nLine 7-9: Validate external inputs through a filter function.", "contexts": [{"lineNo": 80, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "80"}}, {"lineNo": 81, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "req"}}, {"lineNo": 81, "eventType": "source", "messageKey": "synz.COMMON.value.assigned", "params": {}}, {"lineNo": 83, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "redirect"}}]}} {"id": "73b7d0ee766a6968819523fa584a4195257f7ff09f1bc0f5e038ffc3aa3abbb8", "license": {"spdx": ["MIT"], "repo": "jkup/one-line", "path": "index.js", "repo_head_hexsha": "84df631d253629e8ad6867b9da9b0f00523ef7bc", "stack_hexsha": "ac1ad0edbca216bfaed51ca4d04238c70780dd6b", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Redirection to untrusted site", "issueDescriptionEn": "The Redirection to untrusted site checker finds instances of redirecting to a URL generated with an unvalidated external input.\nAlthough connecting to a client-provided URL is often believed to be safe, an attacker can modify the request and redirect the user to a malicious site.\nMaintain a whitelist of external site URLs and domains allowed for redirection, which needs to be checked when a user input is passed as a redirect URL.", "issueLineNumber": 34, "entireCode": "const cool = require('cool-ascii-faces')\nconst funky_intro = require('funny-words')\nconst express = require('express')\nconst emoji = require('emoji-cool');\n\nconst app = express();\napp.engine('html', require('ejs').renderFile); app.set('view engine', 'html');\n\napp.get('/', function(req, res) {\n res.send('Hello Mars!
    Days until next year:' + Math.round(( new Date().setFullYear(new Date().getFullYear() + 1, 0, 1) - new Date() )/(1000 * 60 * 60 * 24)));\n})\n\napp.get('/source', function(req, res){ res.redirect('https://github.com/jkup/one-line/');\n console.log(\"Here you can contribute to this project!\")})\napp.get('/hangUnlessSomeoneElseReturnsFromHere', function(req, res) {\n res.redirect('https://www.google.com/?tbm=isch&q=when+will+my+husband+return+from+war');\n}); // To make this route work, someone else needs to return a response\napp.get('/useless', function(req, res){ res.redirect('http://www.theuselessweb.com/'); })\napp.get('/findMoreHacktoberfestLabelledIssues', function(req, res){ res.redirect('http://issuehub.io/?label[]=hacktoberfest'); })\napp.get('/randNum/cake', function(req, res) { res.json({num: 44}); });\napp.get('/hello/:name', function(req, res) { res.json({\"hello\" : req.params.name}); })\napp.get('/goodbye/:name', function(req, res) { res.json({\"goodbye\" : req.params.name}); })\napp.get('/admin', function(req, res) { res.json(\"ACCESS DENIED\"); })\napp.get('/haveSomeFunCats', function(req, res) { res.redirect('http://www.catgifpage.com/'); });\napp.get('/leftpad/:val/:len', function(req, res) { res.json({ 'response': (+req.params.len > 0) ? (Array(+req.params.len-req.params.val.length).fill(0).join('') + req.params.val).slice(-req.params.res) : req.params.val })});\napp.get('/add/:x/:y', function(req, res) { res.json({x: req.params.x, y: req.params.y, sum: (Number(req.params.x) + Number(req.params.y))}); });\napp.get('/subtract/:x/:y', function(req, res) { res.json({x: req.params.x, y: req.params.y, difference: Number(req.params.x) - Number(req.params.y)}); });\napp.get('/fizzbuzz', function(req, res) { for(var i = 1, arr = []; i<51 ;i++) { arr.push(((i % 3 ? '' : 'fizz') + (i % 5 ? '' : 'buzz')) || i)}; res.json(arr); });\napp.get('/meaningOfLife', function(req, res) { res.json({ 1337: 42 }) });\napp.get('/hacktoberfest-countdown', function (req, res) {\n\tres.send('Hacktoberfest ends in ' + (new Date(2017, 9, 31).getTime() - Date.now())/1000/(24*60*60) + ' days.');\n\tconsole.log(\"Better get those PRs in soon, buddy!\");\n});\napp.get('/currency/:from/:to', function(req, res) { res.redirect('http://api.fixer.io/latest?base=' + req.params.from + '&symbols='+ req.params.to); });\napp.get('/duckduckgo/:search', function(req, res) { res.redirect('https://duckduckgo.com/?q=' + req.params.search)})\napp.get('/beAwesome', function(req, res){ res.redirect('https://github.com/sindresorhus/awesome'); })\napp.get('/motivateMe', function(req, res) {res.redirect('https://www.brainyquote.com/quotes/topics/topic_motivational.html')});\napp.get('/cloud2butt/:text', function(req, res) {res.send(req.params.text.toLowerCase().split('cloud').join('butt'));});\n//51 lines in and NOBODY has commented??? Shame. Well, hello everyone and happy Hacktoberfest. Have fun!\napp.get('/hacktoberfest-checker', function(req, res){ res.redirect('https://hacktoberfestchecker.herokuapp.com/'); })\napp.get('/findme', function(req,res){ res.redirect('https://github.com/mbj36');})\napp.get('/greet', function(req, res) { res.send('🖖'); });\napp.get('/nativescript-vue', function(req, res) { res.send('Want to build native apps with vue? Here you go: https://nativescript-vue.org/'); });\napp.get('/rollTheDice/:dice', function(req, res) {res.json({\"rollValue\" : Math.floor(Math.random() * req.params.dice) + 1 })});\n\napp.get('/ispalindrome/:word', (req, res) => res.send([req.params.word].map(w => w.toLowerCase()).map(w => w.replace(/[^a-zA-Z]+/g, \"\")).map(w => {console.log(w); return w}).reduce((acc, next) => acc ? acc : [...next].reverse().join('') === next, false)))\napp.use(function (req, res, next) { res.status(404); res.render('404'); });\n\nconsole.log(emoji)\nconsole.log(cool())\nconsole.log(funky_intro(\"Welcome to jkup, a Node.js app where you can only contribute one line at a time. Inspired by jkup himself.\"))\n\nvar server = app.listen(process.env.PORT || 3000, function () { // now we can close it if needed\n console.log(\"Server started\");\n});\napp.use(express.static('public'));\nconsole.log(\"I like this idea. :p\");", "dangerousExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/dan', function (req, res) {\n5. const url = req.body.profile_url;\n6. try{\n7. res.redirect(url);\n8. }catch (e) {\n9. return res.status(500).send(\"ERROR\");\n10. }\n11. });\n12. \n13. module.exports = router;\nLine 7: A string variable URL of an unvalidated external input is used to connect.", "safeExampleEn": "1. var express = require('express');\n2. var router = express.Router();\n3. \n4. router.post('/safe', function (req, res) {\n5. const url = req.body.profile_url;\n6. const white_list = [\"https://www.safeurl.com\", \"https://www.verified.com\"];\n7. if (white_list.indexOf(url) < 0) {\n8. return res.status(500).send(\"url not allowed\");\n9. } else {\n10. try {\n11. res.redirect(url);\n12. } catch (e) {\n13. return res.status(500).send(\"ERROR\");\n14. }\n15. }\n16. });\n17. \n18. module.exports = router;\nLine 7-9: Validate external inputs through a filter function.", "contexts": [{"lineNo": 34, "eventType": "source", "messageKey": "synz.COMMON.taint.source", "params": {"arg0": "req"}}, {"lineNo": 34, "eventType": "sink", "messageKey": "synz.COMMON.taint.sink", "params": {"arg0": "redirect"}}]}} {"id": "b3cdf0663f362344a52cd34338540a8f24838af37b94feadeda2bb31123712ad", "license": {"spdx": ["MIT"], "repo": "diecastro/newsfeed", "path": "server/src/app.js", "repo_head_hexsha": "096359a52f01b626cd3b602dacffb413667dc7d6", "stack_hexsha": "df587372c0b87277299751f52bc4567ac4c72bff", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Improper Cookie Flag Setting", "issueDescriptionEn": "Generally, web application uses cookies to send session information. However, the improper use of cookie flags may lead to vulnerabilities in session management such as MITM attacks or cookie stealing using XSS.\nIn Node.js, it is necessary to set security flags such as `secure` and `HttpOnly` to true for session management to enable cookie safety.", "issueLineNumber": 22, "entireCode": "'use strict';\n\nconst express = require('express'),\n session = require('express-session'),\n cookieParser = require('cookie-parser'),\n bodyParser = require('body-parser'),\n app = express(),\n helmet = require('helmet'),\n config = require('./config/app'),\n morgan = require('morgan'),\n compression = require('compression'),\n logger = require('./lib/logger');\n\nrequire('./db');\nrequire('./services/user');\n\nmodule.exports = function () {\n app.use(helmet());\n app.use(cookieParser());\n app.set('trust proxy', true);\n app.use(morgan('[:date[clf]] \":method :url HTTP/:http-version\" :status :res[content-length] \":referrer\" \":user-agent\"', {'stream': logger.stream}));\n app.use(session({resave: false, saveUninitialized: false, secret: config.server.secret}));\n app.set('views', __dirname + '/views');\n app.set('view engine', 'pug');\n app.use(compression());\n app.use(bodyParser.json({limit: config.server.payloadLimit}));\n app.use(bodyParser.urlencoded({limit: config.server.payloadLimit, extended: true}));\n app.use('/api', require('./apiRouter'));\n app.use('', require('./clientRouter'));\n\n return app;\n\n};", "dangerousExampleEn": "1. //--cookie-session\n2. let session = cookieSession({\n3. httpOnly: false,\n4. secure: false,\n5. });\n6. \n7. \n8. //--express-session\n9. const express = require('express');\n10. const session = require('express-session');\n11. let app = express();\n12. app.use(session({\n13. cookie:\n14. {\n15. secure: false,\n16. httpOnly: false\n17. }\n18. }));\n19. \n20. \n21. //--cookies\n22. let cookies = new Cookies(req, res, { keys: keys });\n23. cookies.set('LastVisit', new Date().toISOString(), {\n24. httpOnly: false,\n25. secure: false\n26. });\n27. \n28. //--csurf\n29. const cookieParser = require('cookie-parser');\n30. const csrf = require('csurf');\n31. const express = require('express');\n32. let csrfProtection = csrf({ cookie: { secure: false, httpOnly: false }});\nLine 3, 4, 15, 16, 24, 25, 32: This is insecure because the `secure` and `HttpOnly` flags are set to false.", "safeExampleEn": "1. //--cookie-session\n2. let session = cookieSession({\n3. httpOnly: true,\n4. secure: true,\n5. });\n6. \n7. \n8. //--express-session\n9. const express = require('express');\n10. const session = require('express-session');\n11. let app = express();\n12. app.use(session({\n13. cookie:\n14. {\n15. secure: true,\n16. httpOnly: true\n17. }\n18. }));\n19. \n20. \n21. //--cookies\n22. let cookies = new Cookies(req, res, { keys: keys });\n23. cookies.set('LastVisit', new Date().toISOString(), {\n24. httpOnly: true,\n25. secure: true\n26. });\n27. \n28. //--csurf\n29. const cookieParser = require('cookie-parser');\n30. const csrf = require('csurf');\n31. const express = require('express');\n32. let csrfProtection = csrf({ cookie: { secure: true, httpOnly: true }});\nLine 3, 4, 15, 16, 24, 25, 32: This is secure because the `secure` and `HttpOnly` flags are set to true.", "contexts": [{"lineNo": 22, "eventType": "sink", "messageKey": "jschk.SENSITIVE_COOKIE.FLAG.JS.defect.notset", "params": {}}]}} {"id": "cc551524d05b494248c9ea2332d2ae8080d9b3a76524a9f777b7bc20b273a852", "license": {"spdx": ["MIT"], "repo": "liuzhil/guaixiaogou", "path": "cw_server/app.js", "repo_head_hexsha": "0089ee4beacb6f4e789521237d13dd794ae145c5", "stack_hexsha": "49345ea946a713bcc79736ae7b489e3c98c049e5", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Improper Cookie Flag Setting", "issueDescriptionEn": "Generally, web application uses cookies to send session information. However, the improper use of cookie flags may lead to vulnerabilities in session management such as MITM attacks or cookie stealing using XSS.\nIn Node.js, it is necessary to set security flags such as `secure` and `HttpOnly` to true for session management to enable cookie safety.", "issueLineNumber": 14, "entireCode": "const express=require(\"express\");\nconst session=require(\"express-session\")\nconst bodyParser=require(\"body-parser\");\nconst index=require(\"./routes/index_router\");\nconst shop=require(\"./routes/shop_router\")\nconst details=require(\"./routes/details_router\");\nconst products=require(\"./routes/product_router\");\nconst login=require(\"./routes/login_router\");\nconst register=require(\"./routes/register_router\");\nconst cors=require(\"cors\");\nvar app=express();\napp.listen(3000);\n\napp.use(session({\n secret:\"128位随机字符串\",\n resave:false,\n saveUninitialized:true,\n cookie:{\n maxAge:1000*60*5\n }\n}))\napp.use(cors({\n origin:[\"http://127.0.0.1:3000\",\"http://127.0.0.1:5500\"],//允许列表\n credentials:true //是否验证\n }))\napp.use(bodyParser.urlencoded({extended:false}))\napp.use(express.static(\"public\"))\n\n\napp.use(\"/index\",index);\napp.use(\"/details\",details);\napp.use(\"/products\",products);\napp.use(\"/login\",login);\napp.use(\"/register\",register);\napp.use(\"/shop\",shop);\n\n\n\n\n\n\n\n\n\n\n", "dangerousExampleEn": "1. //--cookie-session\n2. let session = cookieSession({\n3. httpOnly: false,\n4. secure: false,\n5. });\n6. \n7. \n8. //--express-session\n9. const express = require('express');\n10. const session = require('express-session');\n11. let app = express();\n12. app.use(session({\n13. cookie:\n14. {\n15. secure: false,\n16. httpOnly: false\n17. }\n18. }));\n19. \n20. \n21. //--cookies\n22. let cookies = new Cookies(req, res, { keys: keys });\n23. cookies.set('LastVisit', new Date().toISOString(), {\n24. httpOnly: false,\n25. secure: false\n26. });\n27. \n28. //--csurf\n29. const cookieParser = require('cookie-parser');\n30. const csrf = require('csurf');\n31. const express = require('express');\n32. let csrfProtection = csrf({ cookie: { secure: false, httpOnly: false }});\nLine 3, 4, 15, 16, 24, 25, 32: This is insecure because the `secure` and `HttpOnly` flags are set to false.", "safeExampleEn": "1. //--cookie-session\n2. let session = cookieSession({\n3. httpOnly: true,\n4. secure: true,\n5. });\n6. \n7. \n8. //--express-session\n9. const express = require('express');\n10. const session = require('express-session');\n11. let app = express();\n12. app.use(session({\n13. cookie:\n14. {\n15. secure: true,\n16. httpOnly: true\n17. }\n18. }));\n19. \n20. \n21. //--cookies\n22. let cookies = new Cookies(req, res, { keys: keys });\n23. cookies.set('LastVisit', new Date().toISOString(), {\n24. httpOnly: true,\n25. secure: true\n26. });\n27. \n28. //--csurf\n29. const cookieParser = require('cookie-parser');\n30. const csrf = require('csurf');\n31. const express = require('express');\n32. let csrfProtection = csrf({ cookie: { secure: true, httpOnly: true }});\nLine 3, 4, 15, 16, 24, 25, 32: This is secure because the `secure` and `HttpOnly` flags are set to true.", "contexts": [{"lineNo": 14, "eventType": "sink", "messageKey": "jschk.SENSITIVE_COOKIE.FLAG.JS.defect.notset", "params": {}}]}} {"id": "35989a6ad9a89ac5e755310e2e888ad6b8b4029779d5d52655353ef1baaa6b2a", "license": {"spdx": ["Apache-2.0"], "repo": "xabier1/Proyecto-Quiz-I", "path": "app.js", "repo_head_hexsha": "b0494164d0d2632831e25844adfda82cafabaaca", "stack_hexsha": "fd1c7d16c9ecb15f62b81ec31159c9c5f884bea3", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Improper Cookie Flag Setting", "issueDescriptionEn": "Generally, web application uses cookies to send session information. However, the improper use of cookie flags may lead to vulnerabilities in session management such as MITM attacks or cookie stealing using XSS.\nIn Node.js, it is necessary to set security flags such as `secure` and `HttpOnly` to true for session management to enable cookie safety.", "issueLineNumber": 44, "entireCode": "//configuracion de la app\nvar express = require('express');\nvar path = require('path');\nvar favicon = require('serve-favicon');\nvar logger = require('morgan');\nvar cookieParser = require('cookie-parser');\nvar bodyParser = require('body-parser');\nvar partials = require ('express-partials');\nvar methodOverride = require('method-override');\nvar session = require('express-session');\n//capacidad para trabjar con el sistema de ficheros de node\nvar FileStreamRotator = require('file-stream-rotator')\nvar fs = require('fs');\n// create a write stream (in append mode)\n//var logss = fs.createWriteStream(__dirname + '/logs/accesos.log', {flags: 'a'})\nvar logCarpeta = __dirname + '/logs' ;\n// ensure log directory exists\nfs.existsSync(logCarpeta) || fs.mkdirSync(logDirectory);\n// create a rotating write stream\nvar logss = FileStreamRotator.getStream({\n filename: logCarpeta + '/access-%DATE%.log',\n frequency: 'daily',\n verbose: false\n})\n//variables para el enrutamiento\nvar rutas = require('./rutas/index');\n\n//se inicia la app\nvar app = express();\n\n\n// configuración de las plantillas\napp.set('views', path.join(__dirname, 'vistas'));\napp.set('view engine', 'ejs');\n//para poder usar plantillas parciales\napp.use(partials());\n\n//uso de favicon en la carpeta public\napp.use(favicon(__dirname + '/public/favicon.ico'));\napp.use(logger('combined', {stream: logss}));//config. de los logs\napp.use(bodyParser.json());\napp.use(bodyParser.urlencoded());\napp.use(cookieParser('dfsdffgasfdsaf546'));//se cifran las cookies con 'dfsdffgasfdsaf546'\napp.use(session());//instalamos sesiones\napp.use(express.static(path.join(__dirname, 'public')));\napp.use(methodOverride('_method'));\n\n// middleware para el autologout\napp.use(function (req, res, next) {\n\n //si no existe el tiempo de la sesion se crea uno\n var ahora = new Date().getTime();\n\n if (req.session.inicio === undefined) {\n req.session.inicio = ahora;\n }\n\n //se calcula la diferencia entre las 2 fechas\n var duracion = ahora - req.session.inicio;\n\n //si la duracion supera los dos minutos las sesion se elimina\n var tiempo = 2*60*1000; //el tiempo en milisegundos (2 minutos)\n if (duracion > tiempo) {\n //se elimina la variable inicio de la sesion\n delete req.session.inicio;\n // si existe este usuario ha iniciado session, se elimina su session de usuario\n if (req.session.user) {\n delete req.session.user;\n }\n } else {\n //se actualiza los datos\n req.session.inicio = ahora;\n }\n\n\n next();\n})\n\n// Helpers dinamicos: para el uso de las sesiones\napp.use(function(req, res, next) {\n\n // si no existe lo inicializa\n if (!req.session.redir) {\n req.session.redir = '/';\n }\n // guardar path en session.redir para despues de login\n if (!req.path.match(/\\/login|\\/logout|\\/user/)) {\n req.session.redir = req.path;\n }\n\n // Hacer visible req.session en las vistas\n res.locals.session = req.session;\n next();\n\n});\n\n//rutas\napp.use('/', rutas);\n\n// crea un error y lo pasa al siguiente middleware\napp.use(function(req, res, next) {\n var err = new Error('La página web que intentas visitar no existe.');\n err.status = 404;\n next(err);\n});\n\n// error handlers\n\n// Imprime error si estamos em modo desarrollo (mostrando datos del error)\nif (app.get('env') === 'development') {\n app.use(function(err, req, res, next) {\n res.status(err.status || 500);\n res.render('error', {\n message: err.message,\n error: err,\n errores:[]\n });\n });\n}\n\n// Imprime error si estamos em modo produción ( no mostrando datos del error)\napp.use(function(err, req, res, next) {\n res.status(err.status || 500);\n res.render('error', {\n message: err.message,\n error: {},\n errores:[]\n });\n});\n\n\nmodule.exports = app;", "dangerousExampleEn": "1. //--cookie-session\n2. let session = cookieSession({\n3. httpOnly: false,\n4. secure: false,\n5. });\n6. \n7. \n8. //--express-session\n9. const express = require('express');\n10. const session = require('express-session');\n11. let app = express();\n12. app.use(session({\n13. cookie:\n14. {\n15. secure: false,\n16. httpOnly: false\n17. }\n18. }));\n19. \n20. \n21. //--cookies\n22. let cookies = new Cookies(req, res, { keys: keys });\n23. cookies.set('LastVisit', new Date().toISOString(), {\n24. httpOnly: false,\n25. secure: false\n26. });\n27. \n28. //--csurf\n29. const cookieParser = require('cookie-parser');\n30. const csrf = require('csurf');\n31. const express = require('express');\n32. let csrfProtection = csrf({ cookie: { secure: false, httpOnly: false }});\nLine 3, 4, 15, 16, 24, 25, 32: This is insecure because the `secure` and `HttpOnly` flags are set to false.", "safeExampleEn": "1. //--cookie-session\n2. let session = cookieSession({\n3. httpOnly: true,\n4. secure: true,\n5. });\n6. \n7. \n8. //--express-session\n9. const express = require('express');\n10. const session = require('express-session');\n11. let app = express();\n12. app.use(session({\n13. cookie:\n14. {\n15. secure: true,\n16. httpOnly: true\n17. }\n18. }));\n19. \n20. \n21. //--cookies\n22. let cookies = new Cookies(req, res, { keys: keys });\n23. cookies.set('LastVisit', new Date().toISOString(), {\n24. httpOnly: true,\n25. secure: true\n26. });\n27. \n28. //--csurf\n29. const cookieParser = require('cookie-parser');\n30. const csrf = require('csurf');\n31. const express = require('express');\n32. let csrfProtection = csrf({ cookie: { secure: true, httpOnly: true }});\nLine 3, 4, 15, 16, 24, 25, 32: This is secure because the `secure` and `HttpOnly` flags are set to true.", "contexts": [{"lineNo": 44, "eventType": "sink", "messageKey": "jschk.SENSITIVE_COOKIE.FLAG.JS.defect.notset", "params": {}}]}} {"id": "a7024b4c871ac5c14a0bd337968cee878955f69c8276e39f5543914481ec9ba2", "license": {"spdx": ["MIT"], "repo": "hussainwali74/storyteller", "path": "app.js", "repo_head_hexsha": "81a7809fb46146aab53a59ed400de4756ed23102", "stack_hexsha": "88715a437ea5f637957ac52bf6cb93fc091a44c7", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Improper Cookie Flag Setting", "issueDescriptionEn": "Generally, web application uses cookies to send session information. However, the improper use of cookie flags may lead to vulnerabilities in session management such as MITM attacks or cookie stealing using XSS.\nIn Node.js, it is necessary to set security flags such as `secure` and `HttpOnly` to true for session management to enable cookie safety.", "issueLineNumber": 41, "entireCode": "const path = require('path')\nconst express = require('express')\nconst mongoose = require('mongoose')\nconst dotenv = require('dotenv')\nconst morgan = require('morgan')\nconst exphbs = require('express-handlebars')\nconst passport = require('passport')\nconst session = require('express-session')\nconst MongoStore = require('connect-mongo')(session)\n\nconst connectDB = require('./config/db')\nconst { Mongoose } = require('mongoose')\n\n//load config\ndotenv.config({ path: './config/config.env' })\n\n//passport config\nrequire('./config/passport')(passport)\n\nconnectDB()\n\nconst app = express()\n\n//Body Parser\napp.use(express.urlencoded({ extended: false }))\napp.use(express.json())\n//Logging\nif (process.env.NODE_ENV === 'development') {\n app.use(morgan('dev'))\n}\n\n//HANDLEBARS Helpers\nconst { formatDate } = require('./helpers/hbs');\n\n\n//handlebars\napp.engine('.hbs', exphbs({ helpers: { formatDate }, defaultLayout: 'main', extname: '.hbs' }));\napp.set('view engine', '.hbs');\n\n//session \napp.use(session({\n secret: 'planendar',\n resave: false,\n saveUninitialized: false,\n store: new MongoStore({ mongooseConnection: mongoose.connection })\n // cookie: { secure: true }\n}))\n\n//passport middleware\napp.use(passport.initialize())\napp.use(passport.session())\n\n//Static Folder\napp.use(express.static(path.join(__dirname, '/public')))\n\n//Routes\napp.use('/', require('./routes/index'));\napp.use('/auth', require('./routes/auth'));\napp.use('/stories', require('./routes/stories.routes'));\n\nconst PORT = process.env.PORT || 5000\n\napp.listen(PORT, console.log(`server is running in ${process.env.NODE_ENV} mode on PORT: ${PORT}`))", "dangerousExampleEn": "1. //--cookie-session\n2. let session = cookieSession({\n3. httpOnly: false,\n4. secure: false,\n5. });\n6. \n7. \n8. //--express-session\n9. const express = require('express');\n10. const session = require('express-session');\n11. let app = express();\n12. app.use(session({\n13. cookie:\n14. {\n15. secure: false,\n16. httpOnly: false\n17. }\n18. }));\n19. \n20. \n21. //--cookies\n22. let cookies = new Cookies(req, res, { keys: keys });\n23. cookies.set('LastVisit', new Date().toISOString(), {\n24. httpOnly: false,\n25. secure: false\n26. });\n27. \n28. //--csurf\n29. const cookieParser = require('cookie-parser');\n30. const csrf = require('csurf');\n31. const express = require('express');\n32. let csrfProtection = csrf({ cookie: { secure: false, httpOnly: false }});\nLine 3, 4, 15, 16, 24, 25, 32: This is insecure because the `secure` and `HttpOnly` flags are set to false.", "safeExampleEn": "1. //--cookie-session\n2. let session = cookieSession({\n3. httpOnly: true,\n4. secure: true,\n5. });\n6. \n7. \n8. //--express-session\n9. const express = require('express');\n10. const session = require('express-session');\n11. let app = express();\n12. app.use(session({\n13. cookie:\n14. {\n15. secure: true,\n16. httpOnly: true\n17. }\n18. }));\n19. \n20. \n21. //--cookies\n22. let cookies = new Cookies(req, res, { keys: keys });\n23. cookies.set('LastVisit', new Date().toISOString(), {\n24. httpOnly: true,\n25. secure: true\n26. });\n27. \n28. //--csurf\n29. const cookieParser = require('cookie-parser');\n30. const csrf = require('csurf');\n31. const express = require('express');\n32. let csrfProtection = csrf({ cookie: { secure: true, httpOnly: true }});\nLine 3, 4, 15, 16, 24, 25, 32: This is secure because the `secure` and `HttpOnly` flags are set to true.", "contexts": [{"lineNo": 41, "eventType": "sink", "messageKey": "jschk.SENSITIVE_COOKIE.FLAG.JS.defect.notset", "params": {}}]}} {"id": "0a2e85aa0a9905ad9831780db67cfcaa77fc7cf7c3b7cbbc7bda1ad30be5c968", "license": {"spdx": ["MIT"], "repo": "redhawkIT/hackathon-starter", "path": "server/src/setup/Express.js", "repo_head_hexsha": "744753fc099442e2f2f1d5b3226b74d5b23293dc", "stack_hexsha": "905003b5d484573d34d7f6253bed66561f3a7e55", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Improper Cookie Flag Setting", "issueDescriptionEn": "Generally, web application uses cookies to send session information. However, the improper use of cookie flags may lead to vulnerabilities in session management such as MITM attacks or cookie stealing using XSS.\nIn Node.js, it is necessary to set security flags such as `secure` and `HttpOnly` to true for session management to enable cookie safety.", "issueLineNumber": 35, "entireCode": "const compression = require('compression')\nconst session = require('express-session')\n// const cors = require('cors')\nconst bodyParser = require('body-parser')\nconst methodOverride = require('method-override')\nconst logger = require('morgan')\nconst helmet = require('helmet')\n\nconst { NODE_ENV } = process.env\nconst COOKIE_SECRET = 'foobar' // TODO\n\n/**\nSets up express\n*/\nmodule.exports = (server) => {\n // Helmet helps you secure your Express servers by setting various HTTP headers\n // https://github.com/helmetjs/helmet\n server.use(helmet())\n\n // Enable CORS with various options\n // https://github.com/expressjs/cors\n // server.use(cors())\n\n // GZIP files\n server.use(compression())\n // Basic logger(dev)\n if (NODE_ENV !== 'production') server.use(logger('dev'))\n\n // Parse incoming request bodies\n // https://github.com/expressjs/body-parser\n server.use(bodyParser.json())\n server.use(bodyParser.urlencoded({ extended: true }))\n\n // Sessions (consider using a DB to manage sessions in prod)\n server.use(session({\n secret: COOKIE_SECRET,\n resave: false,\n saveUninitialized: false,\n cookie: { maxAge: 60000 }\n }))\n\n // Lets you use HTTP verbs such as PUT or DELETE\n // https://github.com/expressjs/method-override\n server.use(methodOverride())\n}", "dangerousExampleEn": "1. //--cookie-session\n2. let session = cookieSession({\n3. httpOnly: false,\n4. secure: false,\n5. });\n6. \n7. \n8. //--express-session\n9. const express = require('express');\n10. const session = require('express-session');\n11. let app = express();\n12. app.use(session({\n13. cookie:\n14. {\n15. secure: false,\n16. httpOnly: false\n17. }\n18. }));\n19. \n20. \n21. //--cookies\n22. let cookies = new Cookies(req, res, { keys: keys });\n23. cookies.set('LastVisit', new Date().toISOString(), {\n24. httpOnly: false,\n25. secure: false\n26. });\n27. \n28. //--csurf\n29. const cookieParser = require('cookie-parser');\n30. const csrf = require('csurf');\n31. const express = require('express');\n32. let csrfProtection = csrf({ cookie: { secure: false, httpOnly: false }});\nLine 3, 4, 15, 16, 24, 25, 32: This is insecure because the `secure` and `HttpOnly` flags are set to false.", "safeExampleEn": "1. //--cookie-session\n2. let session = cookieSession({\n3. httpOnly: true,\n4. secure: true,\n5. });\n6. \n7. \n8. //--express-session\n9. const express = require('express');\n10. const session = require('express-session');\n11. let app = express();\n12. app.use(session({\n13. cookie:\n14. {\n15. secure: true,\n16. httpOnly: true\n17. }\n18. }));\n19. \n20. \n21. //--cookies\n22. let cookies = new Cookies(req, res, { keys: keys });\n23. cookies.set('LastVisit', new Date().toISOString(), {\n24. httpOnly: true,\n25. secure: true\n26. });\n27. \n28. //--csurf\n29. const cookieParser = require('cookie-parser');\n30. const csrf = require('csurf');\n31. const express = require('express');\n32. let csrfProtection = csrf({ cookie: { secure: true, httpOnly: true }});\nLine 3, 4, 15, 16, 24, 25, 32: This is secure because the `secure` and `HttpOnly` flags are set to true.", "contexts": [{"lineNo": 35, "eventType": "sink", "messageKey": "jschk.SENSITIVE_COOKIE.FLAG.JS.defect.notset", "params": {}}]}} {"id": "b63352e0a5892483a8a0a3f0d40b13312467ca2272493f688fa5fd827c87acad", "license": {"spdx": ["Apache-2.0"], "repo": "akankshamahajan99/identity-demo", "path": "LFS171x/indy-material/nodejs/app.js", "repo_head_hexsha": "a84bbc8607b85798fa25c32f84f0c87ee4341846", "stack_hexsha": "a9a8928b3a8e8f82c221b7e83b5f73e144890284", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Improper Cookie Flag Setting", "issueDescriptionEn": "Generally, web application uses cookies to send session information. However, the improper use of cookie flags may lead to vulnerabilities in session management such as MITM attacks or cookie stealing using XSS.\nIn Node.js, it is necessary to set security flags such as `secure` and `HttpOnly` to true for session management to enable cookie safety.", "issueLineNumber": 22, "entireCode": "const createError = require('http-errors');\nconst express = require('express');\nconst session = require('express-session');\nconst path = require('path');\nconst cookieParser = require('cookie-parser');\nconst logger = require('morgan');\nconst config = require('./config');\n\nconst indexRouter = require('./ui/routes/index');\nconst apiRouter = require('./ui/routes/api');\nconst indyHandler = require('./indy/src/handler')({ defaultHandlers: true, eventHandlers: [] }); // () executes the function so that we can potentially have multiple indy handlers;\n// const uiMessageHandlers = require('./ui/uiMessageHandlers');\n// uiMessageHandlers.enableDefaultHandlers(indyHandler);\n\nconst app = express();\n\n// view engine setup\napp.set('views', path.join(__dirname, 'ui/views'));\napp.set('view engine', 'ejs');\n\nconst FileStore = require('session-file-store')(session);\napp.use(session({\n name: `server-session-cookie-id-for-${config.walletName}`,\n secret: config.sessionSecret,\n saveUninitialized: true,\n resave: true,\n rolling: true,\n store: new FileStore()\n}));\n\napp.use(logger('dev'));\napp.use(express.json());\napp.use(express.urlencoded({ extended: false }));\napp.use(cookieParser());\napp.use(express.static(path.join(__dirname, 'ui/public')));\n\napp.use('/', indexRouter);\napp.use('/api', apiRouter);\napp.post('/indy', indyHandler.middleware);\n\n// catch 404 and forward to error handler\napp.use(function(req, res, next) {\n next(createError(404));\n});\n\n// error handler\napp.use(function(err, req, res, next) {\n // set locals, only providing error in development\n res.locals.message = err.message;\n res.locals.error = req.app.get('env') === 'development' ? err : {};\n\n // render the error page\n res.status(err.status || 500);\n res.render('error');\n});\n\nmodule.exports = app;", "dangerousExampleEn": "1. //--cookie-session\n2. let session = cookieSession({\n3. httpOnly: false,\n4. secure: false,\n5. });\n6. \n7. \n8. //--express-session\n9. const express = require('express');\n10. const session = require('express-session');\n11. let app = express();\n12. app.use(session({\n13. cookie:\n14. {\n15. secure: false,\n16. httpOnly: false\n17. }\n18. }));\n19. \n20. \n21. //--cookies\n22. let cookies = new Cookies(req, res, { keys: keys });\n23. cookies.set('LastVisit', new Date().toISOString(), {\n24. httpOnly: false,\n25. secure: false\n26. });\n27. \n28. //--csurf\n29. const cookieParser = require('cookie-parser');\n30. const csrf = require('csurf');\n31. const express = require('express');\n32. let csrfProtection = csrf({ cookie: { secure: false, httpOnly: false }});\nLine 3, 4, 15, 16, 24, 25, 32: This is insecure because the `secure` and `HttpOnly` flags are set to false.", "safeExampleEn": "1. //--cookie-session\n2. let session = cookieSession({\n3. httpOnly: true,\n4. secure: true,\n5. });\n6. \n7. \n8. //--express-session\n9. const express = require('express');\n10. const session = require('express-session');\n11. let app = express();\n12. app.use(session({\n13. cookie:\n14. {\n15. secure: true,\n16. httpOnly: true\n17. }\n18. }));\n19. \n20. \n21. //--cookies\n22. let cookies = new Cookies(req, res, { keys: keys });\n23. cookies.set('LastVisit', new Date().toISOString(), {\n24. httpOnly: true,\n25. secure: true\n26. });\n27. \n28. //--csurf\n29. const cookieParser = require('cookie-parser');\n30. const csrf = require('csurf');\n31. const express = require('express');\n32. let csrfProtection = csrf({ cookie: { secure: true, httpOnly: true }});\nLine 3, 4, 15, 16, 24, 25, 32: This is secure because the `secure` and `HttpOnly` flags are set to true.", "contexts": [{"lineNo": 22, "eventType": "sink", "messageKey": "jschk.SENSITIVE_COOKIE.FLAG.JS.defect.notset", "params": {}}]}} {"id": "12bb4f78892521d9988631955e093bdd7fc1825e3f2837eeca09c5124d0e8ded", "license": {"spdx": ["MIT"], "repo": "Philip-Mann/final-capstone", "path": "server.js", "repo_head_hexsha": "a2d7f9bad1a3697463322b4deb86aaeed2dbbc68", "stack_hexsha": "d393cea449751a83b7063be7cc604953e4ba80f0", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Improper Cookie Flag Setting", "issueDescriptionEn": "Generally, web application uses cookies to send session information. However, the improper use of cookie flags may lead to vulnerabilities in session management such as MITM attacks or cookie stealing using XSS.\nIn Node.js, it is necessary to set security flags such as `secure` and `HttpOnly` to true for session management to enable cookie safety.", "issueLineNumber": 34, "entireCode": "require('dotenv').config();\nconst express = require('express');\nconst path = require('path');\nconst session = require('express-session');\nconst passport = require('passport');\n// const FacebookStrategy = require('passport-facebook').Strategy;\nconst { Cases, Users } = require('./models')\nconst { PORT } = process.env;\nconst news = require('./articles/articles');\nconst cors = require('cors');\nconst corsOptions = { \n origin:'*',\n optionSuccessStatus:200, \n\n}\n\nconsole.log(\"COMING FROM USERS!!!\", Users)\n\n\n// changed from app to server\nconst server = express();\nserver.use(cors(corsOptions));\nprocess.env.HTTPS = true\n\n// session middleware\nconst sess = {\n secret: 'keyboard cat',\n cookie: {\n maxAge: 24 * 60 * 60 * 1000\n },\n resave: false,\n saveUninitialized: false\n}\nserver.use(session(sess));\nserver.use(passport.initialize());\nserver.use(passport.session());\n\n\n// Serving up the static build file for React\nserver.use(express.static(path.resolve(__dirname + '/react-ui/build')));\nserver.use(express.json());\n\n// to see if server is running\nserver.get('/heartbeat', (req, res) => {\n res.json({\n \"is\": \"working\"\n });\n});\n\n// const userId = req.user\n\nserver.get(`/api/profile/:id`, async (req, res) => {\n const profileInfo = await Users.findOne({\n where: {\n loginStrategyId: req.params.id\n }\n })\n res.json(profileInfo);\n});\n\n// getting Cases table from DB\nserver.get('/api/cases', async (req, res) => {\n const cases = await Cases.findAll();\n res.json(cases);\n});\n\n// getting cases from Cases table from DB by id\nserver.get('/api/cases/:id', async (req, res) => {\n const caseId = req.params.id;\n const caseDataById = await Cases.findAll({\n where: {\n id: caseId\n }\n });\n res.json(caseDataById);\n});\n\n// posting cases to Cases table in DB\nserver.post('/api/cases', async (req, res) => {\n console.log(req.body) //empty object\n const { name, race, sex, age, height, location,\n year, images, body_condition,\n description, characteristics, agencies, cod } = req.body;\n console.log(\"name:\", name);\n const newCase = await Cases.create({\n name, \n race,\n sex,\n age,\n height,\n location,\n year,\n images,\n body_condition,\n description,\n characteristics,\n agencies,\n cod\n });\n console.log('new case entered successfuly', req.body);\n res.send({\n \"message\": \"new case created successfully\",\n \"id\": newCase.id\n });\n});\n\nserver.get('/api/news', (req, res) => {\n res.send(news);\n});\n\nconst auth = require('./routes/auth');\nserver.use('/auth', auth);\n\nserver.get('*', function (req, res) {\n res.sendFile(__dirname + '/react-ui/build/index.html');\n});\n\nserver.listen(PORT, () => {\n console.log(`Server listening on ${PORT}`);\n});", "dangerousExampleEn": "1. //--cookie-session\n2. let session = cookieSession({\n3. httpOnly: false,\n4. secure: false,\n5. });\n6. \n7. \n8. //--express-session\n9. const express = require('express');\n10. const session = require('express-session');\n11. let app = express();\n12. app.use(session({\n13. cookie:\n14. {\n15. secure: false,\n16. httpOnly: false\n17. }\n18. }));\n19. \n20. \n21. //--cookies\n22. let cookies = new Cookies(req, res, { keys: keys });\n23. cookies.set('LastVisit', new Date().toISOString(), {\n24. httpOnly: false,\n25. secure: false\n26. });\n27. \n28. //--csurf\n29. const cookieParser = require('cookie-parser');\n30. const csrf = require('csurf');\n31. const express = require('express');\n32. let csrfProtection = csrf({ cookie: { secure: false, httpOnly: false }});\nLine 3, 4, 15, 16, 24, 25, 32: This is insecure because the `secure` and `HttpOnly` flags are set to false.", "safeExampleEn": "1. //--cookie-session\n2. let session = cookieSession({\n3. httpOnly: true,\n4. secure: true,\n5. });\n6. \n7. \n8. //--express-session\n9. const express = require('express');\n10. const session = require('express-session');\n11. let app = express();\n12. app.use(session({\n13. cookie:\n14. {\n15. secure: true,\n16. httpOnly: true\n17. }\n18. }));\n19. \n20. \n21. //--cookies\n22. let cookies = new Cookies(req, res, { keys: keys });\n23. cookies.set('LastVisit', new Date().toISOString(), {\n24. httpOnly: true,\n25. secure: true\n26. });\n27. \n28. //--csurf\n29. const cookieParser = require('cookie-parser');\n30. const csrf = require('csurf');\n31. const express = require('express');\n32. let csrfProtection = csrf({ cookie: { secure: true, httpOnly: true }});\nLine 3, 4, 15, 16, 24, 25, 32: This is secure because the `secure` and `HttpOnly` flags are set to true.", "contexts": [{"lineNo": 34, "eventType": "sink", "messageKey": "jschk.SENSITIVE_COOKIE.FLAG.JS.defect.notset", "params": {}}]}} {"id": "42e3cfc72e3c6bbb542064260a4280590f798907984a7fd497558a5c42560ad7", "license": {"spdx": ["MIT"], "repo": "rd825/authmini", "path": "sessions.js", "repo_head_hexsha": "234b0cd5186eeb12eda457a937832d7c5e236de2", "stack_hexsha": "d792866c73f27973033cac64fd3c8caad9f06fbf", "match": "repo_path"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Improper Cookie Flag Setting", "issueDescriptionEn": "Generally, web application uses cookies to send session information. However, the improper use of cookie flags may lead to vulnerabilities in session management such as MITM attacks or cookie stealing using XSS.\nIn Node.js, it is necessary to set security flags such as `secure` and `HttpOnly` to true for session management to enable cookie safety.", "issueLineNumber": 30, "entireCode": "const express = require('express');\nconst cors = require('cors');\nconst session = require('express-session');\nconst KnexSessionStore = require('connect-session-knex')(session);\nconst bcrypt = require('bcryptjs'); // *************************** added package and required it here\n\nconst db = require('./database/dbConfig.js');\n\nconst server = express();\n\nconst sessionConfig = {\n name: 'monkey',\n secret: 'asfjaofuwruq04r3oj;ljg049fjq30j4jlajg40j40tjojasl;kjg',\n cookie: {\n maxAge: 1000 * 60 * 10,\n secure: false, // only set it over https; in production you want this true.\n },\n httpOnly: true, // no js can touch this cookie\n resave: false,\n saveUninitialized: false,\n store: new KnexSessionStore({\n tablename: 'sessions',\n sidfieldname: 'sid',\n knex: db,\n createtable: true,\n clearInterval: 1000 * 60 * 60,\n }),\n};\n\nserver.use(session(sessionConfig)); // wires up session management\nserver.use(express.json());\nserver.use(cors());\n\nserver.post('/api/login', (req, res) => {\n // grab username and password from body\n const creds = req.body;\n\n db('users')\n .where({ username: creds.username })\n .first()\n .then(user => {\n if (user && bcrypt.compareSync(creds.password, user.password)) {\n // passwords match and user exists by that username\n req.session.user = user.id;\n res.status(200).json({ message: 'welcome!' });\n } else {\n // either username is invalid or password is wrong\n res.status(401).json({ message: 'you shall not pass!!' });\n }\n })\n .catch(err => res.json(err));\n});\n\nfunction protected(req, res, next) {\n if (req.session && req.session.user) {\n // they're logged in, go ahead and provide access\n next();\n } else {\n // bounce them\n res.status(401).json({ you: 'shall not pass!!' });\n }\n}\n\n// protect this route, only authenticated users should see it\nserver.get('/api/me', protected, (req, res) => {\n db('users')\n .select('id', 'username', 'password') // ***************************** added password to the select\n .where({ id: req.session.user })\n .first()\n .then(users => {\n res.json(users);\n })\n .catch(err => res.send(err));\n});\n\nserver.get('/api/users', protected, (req, res) => {\n db('users')\n .select('id', 'username', 'password') // ***************************** added password to the select\n .then(users => {\n res.json(users);\n })\n .catch(err => res.send(err));\n});\n\nserver.get('/api/logout', (req, res) => {\n if (req.session) {\n req.session.destroy(err => {\n if (err) {\n res.send('you can never leave');\n } else {\n res.send('bye');\n }\n });\n } else {\n res.end();\n }\n});\n\nserver.post('/api/register', (req, res) => {\n // grab username and password from body\n const creds = req.body;\n\n // generate the hash from the user's password\n const hash = bcrypt.hashSync(creds.password, 4); // rounds is 2^X\n\n // override the user.password with the hash\n creds.password = ;\n\n // save the user to the database\n db('users')\n .insert(creds)\n .then(ids => {\n res.status(201).json(ids);\n })\n .catch(err => json(err));\n});\n\nserver.get('/', (req, res) => {\n res.send('Its Alive!');\n});\n\nserver.listen(3300, () => console.log('\\nrunning on port 3300\\n'));", "dangerousExampleEn": "1. //--cookie-session\n2. let session = cookieSession({\n3. httpOnly: false,\n4. secure: false,\n5. });\n6. \n7. \n8. //--express-session\n9. const express = require('express');\n10. const session = require('express-session');\n11. let app = express();\n12. app.use(session({\n13. cookie:\n14. {\n15. secure: false,\n16. httpOnly: false\n17. }\n18. }));\n19. \n20. \n21. //--cookies\n22. let cookies = new Cookies(req, res, { keys: keys });\n23. cookies.set('LastVisit', new Date().toISOString(), {\n24. httpOnly: false,\n25. secure: false\n26. });\n27. \n28. //--csurf\n29. const cookieParser = require('cookie-parser');\n30. const csrf = require('csurf');\n31. const express = require('express');\n32. let csrfProtection = csrf({ cookie: { secure: false, httpOnly: false }});\nLine 3, 4, 15, 16, 24, 25, 32: This is insecure because the `secure` and `HttpOnly` flags are set to false.", "safeExampleEn": "1. //--cookie-session\n2. let session = cookieSession({\n3. httpOnly: true,\n4. secure: true,\n5. });\n6. \n7. \n8. //--express-session\n9. const express = require('express');\n10. const session = require('express-session');\n11. let app = express();\n12. app.use(session({\n13. cookie:\n14. {\n15. secure: true,\n16. httpOnly: true\n17. }\n18. }));\n19. \n20. \n21. //--cookies\n22. let cookies = new Cookies(req, res, { keys: keys });\n23. cookies.set('LastVisit', new Date().toISOString(), {\n24. httpOnly: true,\n25. secure: true\n26. });\n27. \n28. //--csurf\n29. const cookieParser = require('cookie-parser');\n30. const csrf = require('csurf');\n31. const express = require('express');\n32. let csrfProtection = csrf({ cookie: { secure: true, httpOnly: true }});\nLine 3, 4, 15, 16, 24, 25, 32: This is secure because the `secure` and `HttpOnly` flags are set to true.", "contexts": [{"lineNo": 30, "eventType": "sink", "messageKey": "jschk.SENSITIVE_COOKIE.FLAG.JS.defect.notset", "params": {}}]}} {"id": "2aa9ede4b48519bc84ae9b6f82b5d5282d8cb6dbc5f541fb04323c0bfed5b1c9", "license": {"spdx": ["MIT"], "repo": "exozet/oauth-accesstoken-refresher", "path": "index.js", "repo_head_hexsha": "6e5c44ff76ffeb3912064513773ffa734e6630bf", "stack_hexsha": "0e9b54a89a83646968686b3c2176b485b75ff7df", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Improper Cookie Flag Setting", "issueDescriptionEn": "Generally, web application uses cookies to send session information. However, the improper use of cookie flags may lead to vulnerabilities in session management such as MITM attacks or cookie stealing using XSS.\nIn Node.js, it is necessary to set security flags such as `secure` and `HttpOnly` to true for session management to enable cookie safety.", "issueLineNumber": 30, "entireCode": "require('dotenv').config()\n\nvar express = require('express');\nvar session = require('express-session');\nvar request = require('request');\nvar basicAuth = require('express-basic-auth');\nvar uuidV4 = require('uuid/v4');\nvar debug = require('debug')('oauth-accesstoken-refresher');\n\nvar Grant = require('grant-express');\nvar grant = new Grant({\n \"now\": {\n \"key\": process.env.OAUTH_CLIENT_ID,\n \"secret\": process.env.OAUTH_CLIENT_SECRET,\n \"callback\": \"/handle/now/callback\",\n \"oauth\": 2,\n \"state\": true,\n \"redirect_uri\": process.env.OAUTH_REDIRECT_URI,\n \"authorize_url\": process.env.OAUTH_AUTHORIZED_URL,\n \"access_url\": process.env.OAUTH_ACCESS_URL,\n \"scope\": process.env.OAUTH_SCOPE.split(\" \").join(\" \")\n }\n }\n);\n\nvar latestData = {};\nvar latestDataDate = null;\n\nvar app = express();\napp.use(session({secret: uuidV4()}));\nvar basicAuthUsers = {};\nbasicAuthUsers[process.env.BASIC_AUTH_USERNAME] = process.env.BASIC_AUTH_PASSWORD;\n\napp.use(basicAuth({users: basicAuthUsers, challenge: true}));\napp.use(grant);\n\napp.get('/handle/now/callback', function (req, res) {\n var body = req.query;\n if (body.access_token && body.raw.expires_in && body.refresh_token) {\n latestData = body.raw;\n latestDataDate = new Date();\n res.redirect('/');\n } else {\n debug('The raw access_token information does not contain access_token, expires_in AND refresh_token.');\n latestData = null;\n latestDataDate = null;\n res.status(400);\n res.end('Either access_token, expires_in or refresh_token was not set when refreshing the token. Please login again at /connect/oauth once!');\n }\n});\n\napp.get('/', function(req, res) {\n var now = new Date();\n\n if (!latestDataDate) {\n debug('We don\\'t have a access_token, yet');\n res.status(400);\n res.setHeader(\"Content-Type\", \"text/html\");\n res.end('No token stored, yet. Please login at /connect/now once!');\n return;\n }\n\n if (!latestData.expires_in) {\n debug(\"We don't know when it will expire: thus we don't refresh it!\");\n latestData.cached = true;\n res.end(JSON.stringify(latestData, null, 4));\n return;\n }\n\n if (latestData.expires_in * 1000 + latestDataDate.getTime() >= now.getTime()) { /* expires date? */\n debug(\"We know when it expires and serve it as long as it's not expired!\");\n latestData.cached = true;\n res.end(JSON.stringify(latestData, null, 4));\n return;\n }\n\n if (process.env.OAUTH_REFRESH_URL) {\n debug(\"We know how to refresh it and it's already expired!\");\n request({\n \"url\": process.env.OAUTH_REFRESH_URL,\n \"method\": \"POST\",\n \"qs\": {\n \"client_id\": process.env.OAUTH_CLIENT_ID,\n \"client_secret\": process.env.OAUTH_CLIENT_SECRET,\n \"refresh_token\": latestData.refresh_token\n }\n }, function (error, response, body) {\n if (!error && response.statusCode == 200) {\n body = JSON.parse(body);\n debug(\"we got data from refresh token\", body);\n if (body.access_token && body.expires_in && body.refresh_token) {\n latestData = body;\n latestDataDate = new Date();\n res.end(JSON.stringify(latestData, null, 4));\n } else {\n latestData = null;\n latestDataDate = null;\n res.status(400);\n res.end('Either access_token, expires_in or refresh_token was not set when refreshing the token. Please login again at /connect/oauth once!');\n }\n } else {\n latestData = null;\n latestDataDate = null;\n res.status(400);\n res.setHeader(\"Content-Type\", \"text/html\");\n res.end('Refreshing token did not work. Please login again at /connect/now once!');\n }\n });\n return ;\n }\n\n debug(\"We don't know how to refresh it and it's already expired\");\n res.status(400);\n res.setHeader(\"Content-Type\", \"text/html\");\n res.end('Token data expired. Please login again at /connect/now once!');\n});\n\nvar serverPort = parseInt(process.env.PORT || \"3000\", 10);\n\napp.listen(serverPort, function() {\n debug('listening on port %d', serverPort)\n});", "dangerousExampleEn": "1. //--cookie-session\n2. let session = cookieSession({\n3. httpOnly: false,\n4. secure: false,\n5. });\n6. \n7. \n8. //--express-session\n9. const express = require('express');\n10. const session = require('express-session');\n11. let app = express();\n12. app.use(session({\n13. cookie:\n14. {\n15. secure: false,\n16. httpOnly: false\n17. }\n18. }));\n19. \n20. \n21. //--cookies\n22. let cookies = new Cookies(req, res, { keys: keys });\n23. cookies.set('LastVisit', new Date().toISOString(), {\n24. httpOnly: false,\n25. secure: false\n26. });\n27. \n28. //--csurf\n29. const cookieParser = require('cookie-parser');\n30. const csrf = require('csurf');\n31. const express = require('express');\n32. let csrfProtection = csrf({ cookie: { secure: false, httpOnly: false }});\nLine 3, 4, 15, 16, 24, 25, 32: This is insecure because the `secure` and `HttpOnly` flags are set to false.", "safeExampleEn": "1. //--cookie-session\n2. let session = cookieSession({\n3. httpOnly: true,\n4. secure: true,\n5. });\n6. \n7. \n8. //--express-session\n9. const express = require('express');\n10. const session = require('express-session');\n11. let app = express();\n12. app.use(session({\n13. cookie:\n14. {\n15. secure: true,\n16. httpOnly: true\n17. }\n18. }));\n19. \n20. \n21. //--cookies\n22. let cookies = new Cookies(req, res, { keys: keys });\n23. cookies.set('LastVisit', new Date().toISOString(), {\n24. httpOnly: true,\n25. secure: true\n26. });\n27. \n28. //--csurf\n29. const cookieParser = require('cookie-parser');\n30. const csrf = require('csurf');\n31. const express = require('express');\n32. let csrfProtection = csrf({ cookie: { secure: true, httpOnly: true }});\nLine 3, 4, 15, 16, 24, 25, 32: This is secure because the `secure` and `HttpOnly` flags are set to true.", "contexts": [{"lineNo": 30, "eventType": "sink", "messageKey": "jschk.SENSITIVE_COOKIE.FLAG.JS.defect.notset", "params": {}}]}} {"id": "170df680285e758895e9868b519045ffd4d8ade607d2c5ee52e95055e08bf117", "license": {"spdx": ["BSD-2-Clause"], "repo": "sossw1/project-purple-planet", "path": "app.js", "repo_head_hexsha": "3c132e515b28ed9137ab4f068f7a49bdd679c4f8", "stack_hexsha": "d663151c649b7299db55fc7dc04eb85e803c573e", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Improper Cookie Flag Setting", "issueDescriptionEn": "Generally, web application uses cookies to send session information. However, the improper use of cookie flags may lead to vulnerabilities in session management such as MITM attacks or cookie stealing using XSS.\nIn Node.js, it is necessary to set security flags such as `secure` and `HttpOnly` to true for session management to enable cookie safety.", "issueLineNumber": 19, "entireCode": "require('dotenv').config();\nconst express = require('express');\nconst session = require('express-session');\nconst exphbs = require('express-handlebars');\nconst passport = require('./config/passport');\nconst helmet = require('helmet');\nconst path = require('path');\nconst secret = process.env.Session_Secret;\nconst db = require('./models');\nconst PORT = process.env.PORT || 3000;\n\nconst app = express();\napp.use(helmet());\napp.use(express.urlencoded({\n extended: false\n}));\napp.use(express.json());\napp.use(express.static(path.join(__dirname, 'public')));\napp.use(session({\n secret,\n resave: true,\n saveUninitialized: true\n}));\napp.use(passport.initialize());\napp.use(passport.session());\n\napp.engine('handlebars', exphbs({\n defaultLayout: 'main'\n}));\napp.set('view engine', 'handlebars');\n\n// Requiring our routes\nrequire('./routes/html-routes.js')(app);\nrequire('./routes/api-routes.js')(app);\nrequire('./routes/board-api-routes.js')(app);\nrequire('./routes/task-api-routes.js')(app);\n\n// Syncing our database and logging a message to the user upon success\ndb.sequelize.sync().then(function () {\n app.listen(PORT, function () {\n console.log('==> 🌎 Listening on port %s. Visit http://localhost:%s/ in your browser.', PORT, PORT);\n });\n});", "dangerousExampleEn": "1. //--cookie-session\n2. let session = cookieSession({\n3. httpOnly: false,\n4. secure: false,\n5. });\n6. \n7. \n8. //--express-session\n9. const express = require('express');\n10. const session = require('express-session');\n11. let app = express();\n12. app.use(session({\n13. cookie:\n14. {\n15. secure: false,\n16. httpOnly: false\n17. }\n18. }));\n19. \n20. \n21. //--cookies\n22. let cookies = new Cookies(req, res, { keys: keys });\n23. cookies.set('LastVisit', new Date().toISOString(), {\n24. httpOnly: false,\n25. secure: false\n26. });\n27. \n28. //--csurf\n29. const cookieParser = require('cookie-parser');\n30. const csrf = require('csurf');\n31. const express = require('express');\n32. let csrfProtection = csrf({ cookie: { secure: false, httpOnly: false }});\nLine 3, 4, 15, 16, 24, 25, 32: This is insecure because the `secure` and `HttpOnly` flags are set to false.", "safeExampleEn": "1. //--cookie-session\n2. let session = cookieSession({\n3. httpOnly: true,\n4. secure: true,\n5. });\n6. \n7. \n8. //--express-session\n9. const express = require('express');\n10. const session = require('express-session');\n11. let app = express();\n12. app.use(session({\n13. cookie:\n14. {\n15. secure: true,\n16. httpOnly: true\n17. }\n18. }));\n19. \n20. \n21. //--cookies\n22. let cookies = new Cookies(req, res, { keys: keys });\n23. cookies.set('LastVisit', new Date().toISOString(), {\n24. httpOnly: true,\n25. secure: true\n26. });\n27. \n28. //--csurf\n29. const cookieParser = require('cookie-parser');\n30. const csrf = require('csurf');\n31. const express = require('express');\n32. let csrfProtection = csrf({ cookie: { secure: true, httpOnly: true }});\nLine 3, 4, 15, 16, 24, 25, 32: This is secure because the `secure` and `HttpOnly` flags are set to true.", "contexts": [{"lineNo": 19, "eventType": "sink", "messageKey": "jschk.SENSITIVE_COOKIE.FLAG.JS.defect.notset", "params": {}}]}} {"id": "5a0b27aa770cc70d1de23ed62058b416e0126312f84ecdd9cb1d35be078f4cc1", "license": {"spdx": ["MIT"], "repo": "lolmc00/Planner-WEB", "path": "server/server.js", "repo_head_hexsha": "8ddd21028dfb534227c1e660467dee532d9daf7b", "stack_hexsha": "04c9e169b51f3267a6200db3f9784f52401076dc", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Improper Cookie Flag Setting", "issueDescriptionEn": "Generally, web application uses cookies to send session information. However, the improper use of cookie flags may lead to vulnerabilities in session management such as MITM attacks or cookie stealing using XSS.\nIn Node.js, it is necessary to set security flags such as `secure` and `HttpOnly` to true for session management to enable cookie safety.", "issueLineNumber": 30, "entireCode": "const express = require('express');\nconst bodyParser = require('body-parser');\nconst session = require('express-session');\nconst mysqlStore = require('express-mysql-session')(session);\nconst fs = require('fs');\nconst app = express();\nconst api = require('./routes');\nconst sequelize = require('./models').sequelize;\n\napp.use(bodyParser.json());\napp.use(bodyParser.urlencoded({extended: true}));\n\nsequelize.sync();\n\nconst port = 5000;\n\nconst conf = fs.readFileSync('./config/config.json');\nconst options = (JSON.parse(conf)).options;\nvar sessionStore = new mysqlStore(options);\nconst sessionData = fs.readFileSync('./config/session.json');\nconst sessionSecret = JSON.parse(sessionData);\n\napp.use(session({\n key: 'connect.sid',\n secret: sessionSecret.secret,\n resave: false,\n store: sessionStore,\n saveUninitialized: true,\n httpOnly: true,\n secure: false\n}));\n\n\napp.get('/', (req, res) =>{\n});\n\napp.use('/api', api);\n\napp.listen(port, () => console.log(`Listening on port ${port}`));", "dangerousExampleEn": "1. //--cookie-session\n2. let session = cookieSession({\n3. httpOnly: false,\n4. secure: false,\n5. });\n6. \n7. \n8. //--express-session\n9. const express = require('express');\n10. const session = require('express-session');\n11. let app = express();\n12. app.use(session({\n13. cookie:\n14. {\n15. secure: false,\n16. httpOnly: false\n17. }\n18. }));\n19. \n20. \n21. //--cookies\n22. let cookies = new Cookies(req, res, { keys: keys });\n23. cookies.set('LastVisit', new Date().toISOString(), {\n24. httpOnly: false,\n25. secure: false\n26. });\n27. \n28. //--csurf\n29. const cookieParser = require('cookie-parser');\n30. const csrf = require('csurf');\n31. const express = require('express');\n32. let csrfProtection = csrf({ cookie: { secure: false, httpOnly: false }});\nLine 3, 4, 15, 16, 24, 25, 32: This is insecure because the `secure` and `HttpOnly` flags are set to false.", "safeExampleEn": "1. //--cookie-session\n2. let session = cookieSession({\n3. httpOnly: true,\n4. secure: true,\n5. });\n6. \n7. \n8. //--express-session\n9. const express = require('express');\n10. const session = require('express-session');\n11. let app = express();\n12. app.use(session({\n13. cookie:\n14. {\n15. secure: true,\n16. httpOnly: true\n17. }\n18. }));\n19. \n20. \n21. //--cookies\n22. let cookies = new Cookies(req, res, { keys: keys });\n23. cookies.set('LastVisit', new Date().toISOString(), {\n24. httpOnly: true,\n25. secure: true\n26. });\n27. \n28. //--csurf\n29. const cookieParser = require('cookie-parser');\n30. const csrf = require('csurf');\n31. const express = require('express');\n32. let csrfProtection = csrf({ cookie: { secure: true, httpOnly: true }});\nLine 3, 4, 15, 16, 24, 25, 32: This is secure because the `secure` and `HttpOnly` flags are set to true.", "contexts": [{"lineNo": 30, "eventType": "sink", "messageKey": "jschk.SENSITIVE_COOKIE.FLAG.JS.defect.false", "params": {}}]}} {"id": "8e2077507a44d002d255b64a527d27c3b31a15745800d2cc5b39dbab83525fcc", "license": {"spdx": ["MIT"], "repo": "exiled212/callDiary", "path": "app.js", "repo_head_hexsha": "02c8c3ff4f90b36dfc090da3758b38f48db6abc4", "stack_hexsha": "c3c143ab06a01602bb5edf2410bc265925cdc9ad", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Improper Cookie Flag Setting", "issueDescriptionEn": "Generally, web application uses cookies to send session information. However, the improper use of cookie flags may lead to vulnerabilities in session management such as MITM attacks or cookie stealing using XSS.\nIn Node.js, it is necessary to set security flags such as `secure` and `HttpOnly` to true for session management to enable cookie safety.", "issueLineNumber": 22, "entireCode": "(()=>{\n\n\trequire('rootpath')()\n\n\tconst \texpress \t\t= \trequire('express')\n\t,\t\tbodyParser\t\t=\trequire('body-parser')\n\t,\t\tmethodOverride\t=\trequire('method-override')\n\t,\t\tsession \t\t= \trequire(\"express-session\")\n\t, \t\tcookieParser \t= \trequire(\"cookie-parser\")\n\t, \t\tcons \t\t\t= \trequire(\"consolidate\")\n\t, \t\tfavicon \t\t= \trequire(\"serve-favicon\")\n\t, \t\tpath \t\t\t= \trequire(\"path\")\n\t, \t\tpassport \t\t= \trequire(\"passport\")\n\t, \t\tfastCsv \t\t= \trequire(\"fast-csv\")\n\n\n\tlet \tapp\t= express()\n\n\t//Configuracion de Sessiones\n\tapp\t\t\t\n\t\t.use(cookieParser())\n\t\t.use(session({\n\t\t\tsecret:\t\t\t\t'test'\t,\n\t\t\tresave:\t\t\t\tfalse\t,\n\t\t\tmaxAge:\t\t\t\t1200000\t,\n\t\t\tsaveUninitialized:\tfalse\n\t\t}))\n\t//Configuracion de Express\n\t\t.use(express.static('./public'))\n\t\t.use(favicon(path.join('public', 'img', 'favicon.ico')))\n\t\t.use(bodyParser.urlencoded({ extended: true }))\n\t\t.use(bodyParser.json())\n\t\t.use(methodOverride())\n\t\t.use(passport.initialize())\n\t\t.use(passport.session())\n\n\t\t.engine('html', cons.swig)\n\n\t\t.set('views', `./public/views`)\n\t\t.set('view engine', 'ejs')\n\n\tpassport.serializeUser((user, done)=>{\n\t\tdone(null, user)\n\t})\n\tpassport.deserializeUser((user,done)=>{\n\t\tdone(null, user)\n\t})\n\n\trequire('./routes.js')(app);\n\t\t\n\t\t\n\tmodule.exports = app\n})();", "dangerousExampleEn": "1. //--cookie-session\n2. let session = cookieSession({\n3. httpOnly: false,\n4. secure: false,\n5. });\n6. \n7. \n8. //--express-session\n9. const express = require('express');\n10. const session = require('express-session');\n11. let app = express();\n12. app.use(session({\n13. cookie:\n14. {\n15. secure: false,\n16. httpOnly: false\n17. }\n18. }));\n19. \n20. \n21. //--cookies\n22. let cookies = new Cookies(req, res, { keys: keys });\n23. cookies.set('LastVisit', new Date().toISOString(), {\n24. httpOnly: false,\n25. secure: false\n26. });\n27. \n28. //--csurf\n29. const cookieParser = require('cookie-parser');\n30. const csrf = require('csurf');\n31. const express = require('express');\n32. let csrfProtection = csrf({ cookie: { secure: false, httpOnly: false }});\nLine 3, 4, 15, 16, 24, 25, 32: This is insecure because the `secure` and `HttpOnly` flags are set to false.", "safeExampleEn": "1. //--cookie-session\n2. let session = cookieSession({\n3. httpOnly: true,\n4. secure: true,\n5. });\n6. \n7. \n8. //--express-session\n9. const express = require('express');\n10. const session = require('express-session');\n11. let app = express();\n12. app.use(session({\n13. cookie:\n14. {\n15. secure: true,\n16. httpOnly: true\n17. }\n18. }));\n19. \n20. \n21. //--cookies\n22. let cookies = new Cookies(req, res, { keys: keys });\n23. cookies.set('LastVisit', new Date().toISOString(), {\n24. httpOnly: true,\n25. secure: true\n26. });\n27. \n28. //--csurf\n29. const cookieParser = require('cookie-parser');\n30. const csrf = require('csurf');\n31. const express = require('express');\n32. let csrfProtection = csrf({ cookie: { secure: true, httpOnly: true }});\nLine 3, 4, 15, 16, 24, 25, 32: This is secure because the `secure` and `HttpOnly` flags are set to true.", "contexts": [{"lineNo": 22, "eventType": "sink", "messageKey": "jschk.SENSITIVE_COOKIE.FLAG.JS.defect.notset", "params": {}}]}} {"id": "bfcd425a58d97d5853fd6b1e8f96a90265b58e77634d2e3049f5e9effe2ab017", "license": {"spdx": ["MIT"], "repo": "srhoulam/ocmud", "path": "app.js", "repo_head_hexsha": "0e7e3f102f06cfde40c70491126e7d5241defcfc", "stack_hexsha": "d1234fecd5fdc9a713c45e287e90bee124c05ac6", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Improper Cookie Flag Setting", "issueDescriptionEn": "Generally, web application uses cookies to send session information. However, the improper use of cookie flags may lead to vulnerabilities in session management such as MITM attacks or cookie stealing using XSS.\nIn Node.js, it is necessary to set security flags such as `secure` and `HttpOnly` to true for session management to enable cookie safety.", "issueLineNumber": 40, "entireCode": "'use strict';\n\nlet express = require('express');\n//let path = require('path');\nlet bodyParser = require('body-parser');\n\nlet session = require('express-session');\nlet sessionStore = require('./lib/sessionStore');\nlet uuid = require('uuid');\nlet passport = require('./lib/passport');\nlet cors = require('cors');\n\nlet app = express();\nlet appEnvironment = app.get('env');\n\n// will be using a reverse proxy in production\nif(appEnvironment !== 'development') {\n app.enable(\"trust proxy\");\n}\n\n/** DOC\n *\n * The purpose of the express portion of this application\n * is for the authentication request. The rest will be\n * handled via socket.io\n *\n */\n\n// ensure environment variables are loaded\nprocess.env.SESSION_SECRET || require('dotenv').load();\n\n// apply middleware to express instance\napp.use(cors({\n origin : 'https://pfbe.saad.rhoulam.com',\n credentials : true\n}));\napp.use(bodyParser.json());\n// app.use(bodyParser.urlencoded({ extended: true }));\n\napp.use(session({\n name : \"ocmud.sid\",\n secret : process.env.SESSION_SECRET,\n secure : appEnvironment !== 'development',\n store : sessionStore,\n saveUninitialized : false,\n resave : false,\n genid : function() {\n return uuid.v4({\n rng : uuid.nodeRNG\n });\n },\n cookie : {\n maxAge : 60 * 60 * 1000\n }\n}));\n\n// auth middleware\napp.use(passport.initialize());\napp.use(passport.session());\n\n// routers\napp.use('/auth', require('./routes/auth'));\napp.use('/bug', require('./routes/bug'));\n\n// serve front-end from same origin\n// socket.io won't send the session cookie otherwise\n//\n// remove this for production and use a reverse proxy\n// to serve the files from the same origin as the app\nif(appEnvironment === 'development') {\n app.use('/pub', express.static(__dirname + \"/../ocmud-fe\"));\n}\n\n// catch 404 and forward to error handler\napp.use(function(req, res, next) {\n let err = new Error('Not Found');\n err.status = 404;\n next(err);\n});\n\n// error handlers\n\n// development error handler\n// will print stacktrace\nif (appEnvironment === 'development') {\n app.use(function(err, req, res, next) {\n res.status(err.status || 500);\n res.json({\n message: err.message,\n error: err.stack\n });\n });\n}\n\n// production error handler\n// no stacktraces leaked to user\napp.use(function(err, req, res, next) {\n res.status(err.status || 500);\n res.json({\n message: err.message,\n error: {}\n });\n});\n\n\nmodule.exports = app;", "dangerousExampleEn": "1. //--cookie-session\n2. let session = cookieSession({\n3. httpOnly: false,\n4. secure: false,\n5. });\n6. \n7. \n8. //--express-session\n9. const express = require('express');\n10. const session = require('express-session');\n11. let app = express();\n12. app.use(session({\n13. cookie:\n14. {\n15. secure: false,\n16. httpOnly: false\n17. }\n18. }));\n19. \n20. \n21. //--cookies\n22. let cookies = new Cookies(req, res, { keys: keys });\n23. cookies.set('LastVisit', new Date().toISOString(), {\n24. httpOnly: false,\n25. secure: false\n26. });\n27. \n28. //--csurf\n29. const cookieParser = require('cookie-parser');\n30. const csrf = require('csurf');\n31. const express = require('express');\n32. let csrfProtection = csrf({ cookie: { secure: false, httpOnly: false }});\nLine 3, 4, 15, 16, 24, 25, 32: This is insecure because the `secure` and `HttpOnly` flags are set to false.", "safeExampleEn": "1. //--cookie-session\n2. let session = cookieSession({\n3. httpOnly: true,\n4. secure: true,\n5. });\n6. \n7. \n8. //--express-session\n9. const express = require('express');\n10. const session = require('express-session');\n11. let app = express();\n12. app.use(session({\n13. cookie:\n14. {\n15. secure: true,\n16. httpOnly: true\n17. }\n18. }));\n19. \n20. \n21. //--cookies\n22. let cookies = new Cookies(req, res, { keys: keys });\n23. cookies.set('LastVisit', new Date().toISOString(), {\n24. httpOnly: true,\n25. secure: true\n26. });\n27. \n28. //--csurf\n29. const cookieParser = require('cookie-parser');\n30. const csrf = require('csurf');\n31. const express = require('express');\n32. let csrfProtection = csrf({ cookie: { secure: true, httpOnly: true }});\nLine 3, 4, 15, 16, 24, 25, 32: This is secure because the `secure` and `HttpOnly` flags are set to true.", "contexts": [{"lineNo": 40, "eventType": "sink", "messageKey": "jschk.SENSITIVE_COOKIE.FLAG.JS.defect.notset", "params": {}}]}} {"id": "aaa95a1210d048ec3321f27083fa9b13c4bc1119fae60a48b6699141210f07cd", "license": {"spdx": ["BSD-3-Clause"], "repo": "epochml/link-shortner", "path": "index.js", "repo_head_hexsha": "146b376aacab2778e0ffed5b976419a7e0fbb97f", "stack_hexsha": "8888ce290425eda4c1908ae88722cecd307a3f93", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Improper Cookie Flag Setting", "issueDescriptionEn": "Generally, web application uses cookies to send session information. However, the improper use of cookie flags may lead to vulnerabilities in session management such as MITM attacks or cookie stealing using XSS.\nIn Node.js, it is necessary to set security flags such as `secure` and `HttpOnly` to true for session management to enable cookie safety.", "issueLineNumber": 59, "entireCode": "const hogan = require('hogan-express');\nconst express = require('express');\nconst session = require('express-session');\nconst SQLiteStore = require('connect-sqlite3')(session);\nconst baseURL = process.env.baseURL || 'goepoch.ml';\nconst favicon = require('serve-favicon');\nconst sqlite3 = require('sqlite3')\nconst dbVendor = process.env.DB_VENDOR;\nconst config = require('./config');\nconst passport = require('passport')\nvar OIDCStrategy = require('passport-azure-ad').OIDCStrategy;\nvar cookieParser = require('cookie-parser');\n\nif (dbVendor === \"postgresql\") {\n console.error(\"SQL support not yet implemented\")\n process.exit(2)\n} else {\n var db = new sqlite3.Database(process.env.DB_FILE, sqlite3.OPEN_READWRITE, (err) => {\n if (err) {\n console.error(err.message);\n process.exit(1);\n }\n })\n var store = new SQLiteStore({'dir': process.env.SESSION_DB_FILE_LOC, 'db': process.env.SESSION_DB_FILE_NAME});\n}\nvar app = express();\nvar server = app.listen(9215, function () {\n var host = server.address().address;\n var port = server.address().port;\n console.log('Listening on port %s', port);\n});\napp.set('view engine', 'html');\napp.set('views', require('path').join(__dirname, '/view'));\napp.engine('html', hogan);\n\n// Create a session-store to be used by both the express-session\n// middleware and the keycloak middleware.\nfunction makeSecret() {\n const length = 64;\n let result = '';\n const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+-=[]\\;\\',./<>?:\"{}|';\n const charactersLength = characters.length;\n for ( var i = 0; i < length; i++ ) {\n result += characters.charAt(Math.floor(Math.random() * charactersLength));\n }\n return result;\n}\nfunction getRandomURL() {\n const length = 6;\n let result = '';\n const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';\n const charactersLength = characters.length;\n for ( var i = 0; i < length; i++ ) {\n result += characters.charAt(Math.floor(Math.random() * charactersLength));\n }\n return result;\n}\nconst secret = process.env.NODE_ENV === \"development\" ? \"secret\" : makeSecret()\napp.use(session({\n secret: secret,\n resave: false,\n saveUninitialized: true,\n store: process.env.NODE_ENV === \"development\" ? undefined : store\n}));\n\n//-----------------------------------------------------------------------------\n// To support persistent login sessions, Passport needs to be able to\n// serialize users into and deserialize users out of the session. Typically,\n// this will be as simple as storing the user ID when serializing, and finding\n// the user by ID when deserializing.\n//-----------------------------------------------------------------------------\npassport.serializeUser(function(user, done) {\n done(null, user.oid);\n});\n\npassport.deserializeUser(function(oid, done) {\n findByOid(oid, function (err, user) {\n done(err, user);\n });\n});\n\n// array to hold logged in users\nvar users = [];\n\nvar findByOid = function(oid, fn) {\n for (var i = 0, len = users.length; i < len; i++) {\n var user = users[i];\n if (user.oid === oid) {\n return fn(null, user);\n }\n }\n return fn(null, null);\n};\n\npassport.use(new OIDCStrategy({\n identityMetadata: config.creds.identityMetadata,\n clientID: config.creds.clientID,\n responseType: config.creds.responseType,\n responseMode: config.creds.responseMode,\n redirectUrl: config.creds.redirectUrl,\n allowHttpForRedirectUrl: config.creds.allowHttpForRedirectUrl,\n clientSecret: config.creds.CLIENT_SECRET,\n validateIssuer: config.creds.validateIssuer,\n isB2C: config.creds.isB2C,\n issuer: config.creds.issuer,\n passReqToCallback: config.creds.passReqToCallback,\n scope: config.creds.scope,\n loggingLevel: config.creds.loggingLevel,\n nonceLifetime: config.creds.nonceLifetime,\n nonceMaxAmount: config.creds.nonceMaxAmount,\n useCookieInsteadOfSession: config.creds.useCookieInsteadOfSession,\n cookieEncryptionKeys: config.creds.cookieEncryptionKeys,\n clockSkew: config.creds.clockSkew,\n},\nfunction(iss, sub, profile, accessToken, refreshToken, done) {\n if (!profile.oid) {\n return done(new Error(\"No oid found\"), null);\n }\n // asynchronous verification, for effect...\n process.nextTick(function () {\n findByOid(profile.oid, function(err, user) {\n if (err) {\n return done(err);\n }\n if (!user) {\n // \"Auto-registration\"\n users.push(profile);\n return done(null, profile);\n }\n return done(null, user);\n });\n });\n}\n));\napp.use(cookieParser());\napp.use(express.urlencoded({ extended : true }));\napp.use(express.json())\napp.use(passport.initialize());\napp.use(passport.session());\napp.use(favicon(__dirname + '/public/img/favicon.ico'));\napp.use('/static', express.static('public'))\nfunction ensureAuthenticated(req, res, next) {\n if (req.isAuthenticated()) { return next(); }\n res.redirect('/login');\n};\n\nasync function addURLToDB(name, url, email, groups) {\n return new Promise(function(resolve, reject) {\n db.serialize(function() {\n const stmt = db.prepare(\"INSERT INTO urlData (name, url, email, groups) VALUES (?, ?, ?, ?)\");\n stmt.run([name, url, email, groups], function(err) {\n if (err) {\n reject(err)\n } else {\n resolve({name, url, email})\n }\n })\n })\n })\n}\nasync function getDataForEmail(email) {\n return new Promise(function(resolve, reject) {\n db.serialize(function() {\n const stmt = db.prepare(\"SELECT * FROM urlData WHERE email=?\");\n stmt.all([email], function(err, data) {\n if (err) {\n reject(err)\n } else {\n resolve(data)\n }\n })\n })\n })\n}\n\nasync function getDelegatedLinks(userGroups) {\n return new Promise(function(resolve, reject) {\n db.serialize(function() {\n const stmt = db.prepare(\"SELECT * FROM urlData;\");\n stmt.all([], function(err, allData) {\n if (err) {\n reject(err)\n } else {\n allData = allData.map(item => {\n if (item.groups === null) {\n return item; \n }\n item.groups = item.groups.split(','); \n return item;\n })\n const data = allData.filter(item => {\n let compareGroups = []\n if (item.groups !== null) {\n compareGroups = item.groups\n }\n const mergedArray = userGroups.filter(value => compareGroups.includes(value));\n return mergedArray.length > 0 \n })\n resolve(data)\n }\n })\n })\n })\n}\n\nasync function removeURLfromDB(name) {\n return new Promise(function(resolve, reject) {\n db.serialize(function() {\n const stmt = db.prepare(\"DELETE FROM urlData WHERE name=?\");\n stmt.run([name], function(err) {\n if (err) {\n reject(err)\n } else {\n resolve(name)\n }\n })\n })\n })\n}\nasync function getRedirectURL(name) {\n return new Promise(function(resolve, reject) {\n db.serialize(function() {\n const stmt = db.prepare(\"SELECT url FROM urlData WHERE name=?\");\n stmt.all([name], function(err, data) {\n if (err) {\n reject(err)\n } else {\n resolve(data)\n }\n })\n })\n })\n}\nasync function updateRecord(name, url) {\n return new Promise(function(resolve, reject) {\n db.serialize(function() {\n const stmt = db.prepare(\"UPDATE urlData SET url=?, name=? WHERE name=?\");\n stmt.run([url, name, name], function(err) {\n if (err) {\n reject(err)\n } else {\n resolve({name, url})\n }\n })\n })\n })\n}\n\napp.get('/login',\n function(req, res, next) {\n passport.authenticate('azuread-openidconnect', \n { \n response: res, // required\n resourceURL: config.resourceURL, // optional. Provide a value if you want to specify the resource.\n customState: 'my_state', // optional. Provide a value if you want to provide custom state value.\n failureRedirect: '/error',\n useCookieInsteadOfSession: true,\n domain_hint: 'epochml.org'\n }\n )(req, res, next);\n },\n function(req, res) {\n res.redirect('/');\n});\napp.get('/error', (req, res) => {\n res.status(500).send(\"An error occurred.\")\n}\n\n);\n// 'GET returnURL'\n// `passport.authenticate` will try to authenticate the content returned in\n// query (such as authorization code). If authentication fails, user will be\n// redirected to '/' (home page); otherwise, it passes to the next middleware.\napp.get('/auth/openid/return',\n function(req, res, next) {\n passport.authenticate('azuread-openidconnect', \n { \n response: res, // required\n failureRedirect: '/' \n }\n )(req, res, next);\n },\n function(req, res) {\n res.redirect('/');\n });\n\n// 'POST returnURL'\n// `passport.authenticate` will try to authenticate the content returned in\n// body (such as authorization code). If authentication fails, user will be\n// redirected to '/' (home page); otherwise, it passes to the next middleware.\napp.post('/auth/openid/return',\n function(req, res, next) {\n passport.authenticate('azuread-openidconnect', \n { \n response: res, // required\n failureRedirect: '/' \n }\n )(req, res, next);\n },\n function(req, res) {\n res.redirect('/');\n });\n\n// 'logout' route, logout from passport, and destroy the session with AAD.\napp.get('/logout', function(req, res){\n req.session.destroy(function(err) {\n req.logOut();\n res.redirect(config.destroySessionUrl);\n });\n});\n\n// begin business logic\n\napp.get('/', ensureAuthenticated, async function (req, res) {\n res.render('index.html', { email: req.user._json.preferred_username, name: req.user.displayName, baseURL, userGroups: req.user._json.groups.map((item) => {return {group: item}}) })\n return\n})\n\napp.post('/addURL', ensureAuthenticated, async function (req, res) {\n const email = req.user._json.preferred_username;\n const url = req.query.url;\n const name = req.query.name;\n const groups = req.body.groups\n if (url.indexOf(baseURL) > -1 ) {\n res.json({\n message: `The origin URL cannot be a path of ${baseURL}`\n })\n return\n }\n if (url === undefined || name === undefined) {\n res.status(400).json({\n message: \"Either url or name was not provided.\"\n })\n return\n }\n addURLToDB(name, url, email, groups).then((obj) => {\n res.json({\n url: obj.url,\n shortURL: `https://goepoch.ml/${obj.name}`,\n email: obj.email,\n groups: groups\n });\n }).catch((err) => {\n if (err.errno == 19) {\n res.status(409).json({\n message: \"This short URL has already been taken. Please try another.\"\n })\n } else {\n res.status(500).json({\n message: \"The short URL could not be added. Please try again.\"\n })\n }\n\n })\n return\n\n});\n\napp.get('/mylinks', ensureAuthenticated, async function (req, res) {\n const email = req.user._json.preferred_username;\n const name = req.user.displayName;\n const userGroups = req.user._json.groups;\n const data = await getDataForEmail(email).catch(() => {res.status(500).render('500'); return});\n const delegatedLinks = await getDelegatedLinks(userGroups).catch(() => {res.status(500).render('500'); return});\n res.render('mylinks', {\n data,\n name,\n email,\n baseURL,\n delegatedLinks\n })\n})\n\napp.delete('/deleteLink', ensureAuthenticated, async function (req, res) {\n const name = req.query.name;\n removeURLfromDB(name).then(() => {\n res.json({\n name, deleted: true\n })\n return\n }).catch(() => {\n res.status(500).json({\n message: \"Could not delete the link. Please try again.\"\n })\n return\n })\n})\napp.put('/updateLink', ensureAuthenticated, async function (req, res) {\n const name = req.query.name;\n const url = req.query.url;\n if (url.indexOf(baseURL) > -1 ) {\n res.json({\n message: `The origin URL cannot be a path of ${baseURL}`\n })\n return\n }\n updateRecord(name, url).then((data) => {\n res.json(data);\n return;\n }).catch(() => {\n res.status(500).json({\n message: \"Could not update the link. Please try again.\"\n })\n return\n })\n})\napp.get('/getRandomURL', ensureAuthenticated, async function (req, res) {\n let exists = true;\n let generatedURL = '';\n let i = 0;\n while(exists) {\n try {\n generatedURL = getRandomURL();\n const url = await getRedirectURL(generatedURL);\n exists = url[0] !== undefined;\n if (i > 10) {\n throw new Error(\"In a generation loop, must exit.\")\n }\n } catch {\n res.status(500).json({success: false})\n return\n }\n }\n try {\n if (generatedURL !== '') {\n res.json({success: true, generatedURL})\n return\n }\n throw new Error(\"Did not actually generate a new URL.\")\n } catch {\n res.status(500).json({success: false})\n return\n }\n})\napp.get('/:id', async function (req, res) {\n const name = req.params.id;\n const ts = Date.now();\n try {\n const url = await getRedirectURL(name)\n if (url[0] !== undefined) {\n res.redirect(url[0].url)\n return\n } else {\n res.status(404).render('404')\n return\n }\n } catch {\n res.status(500).render('500')\n return\n }\n\n})", "dangerousExampleEn": "1. //--cookie-session\n2. let session = cookieSession({\n3. httpOnly: false,\n4. secure: false,\n5. });\n6. \n7. \n8. //--express-session\n9. const express = require('express');\n10. const session = require('express-session');\n11. let app = express();\n12. app.use(session({\n13. cookie:\n14. {\n15. secure: false,\n16. httpOnly: false\n17. }\n18. }));\n19. \n20. \n21. //--cookies\n22. let cookies = new Cookies(req, res, { keys: keys });\n23. cookies.set('LastVisit', new Date().toISOString(), {\n24. httpOnly: false,\n25. secure: false\n26. });\n27. \n28. //--csurf\n29. const cookieParser = require('cookie-parser');\n30. const csrf = require('csurf');\n31. const express = require('express');\n32. let csrfProtection = csrf({ cookie: { secure: false, httpOnly: false }});\nLine 3, 4, 15, 16, 24, 25, 32: This is insecure because the `secure` and `HttpOnly` flags are set to false.", "safeExampleEn": "1. //--cookie-session\n2. let session = cookieSession({\n3. httpOnly: true,\n4. secure: true,\n5. });\n6. \n7. \n8. //--express-session\n9. const express = require('express');\n10. const session = require('express-session');\n11. let app = express();\n12. app.use(session({\n13. cookie:\n14. {\n15. secure: true,\n16. httpOnly: true\n17. }\n18. }));\n19. \n20. \n21. //--cookies\n22. let cookies = new Cookies(req, res, { keys: keys });\n23. cookies.set('LastVisit', new Date().toISOString(), {\n24. httpOnly: true,\n25. secure: true\n26. });\n27. \n28. //--csurf\n29. const cookieParser = require('cookie-parser');\n30. const csrf = require('csurf');\n31. const express = require('express');\n32. let csrfProtection = csrf({ cookie: { secure: true, httpOnly: true }});\nLine 3, 4, 15, 16, 24, 25, 32: This is secure because the `secure` and `HttpOnly` flags are set to true.", "contexts": [{"lineNo": 59, "eventType": "sink", "messageKey": "jschk.SENSITIVE_COOKIE.FLAG.JS.defect.notset", "params": {}}]}} {"id": "5b38eeea2f59baad171b1161366149bde6bcb9754eefb4382a29f84491828ae5", "license": {"spdx": ["MIT"], "repo": "Mineru98/ExpressExam", "path": "src/index.js", "repo_head_hexsha": "940cba28a978c1eae826aafd11188dec973c75d7", "stack_hexsha": "dd107e076a1eaab0ada56f5b26c6f2b596b28f9e", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Improper Cookie Flag Setting", "issueDescriptionEn": "Generally, web application uses cookies to send session information. However, the improper use of cookie flags may lead to vulnerabilities in session management such as MITM attacks or cookie stealing using XSS.\nIn Node.js, it is necessary to set security flags such as `secure` and `HttpOnly` to true for session management to enable cookie safety.", "issueLineNumber": 11, "entireCode": "const express = require(\"express\");\nconst session = require(\"express-session\");\nconst bodyParser = require(\"body-parser\");\nconst { v4: uuidv4 } = require('uuid');\nconst app = express();\n\napp.set('trust proxy', 1);\napp.use(bodyParser.urlencoded({ extended: false }));\napp.use(bodyParser.json({ limit: \"50mb\" }));\napp.use(\n\tsession({\n\t\tsecret: \"password\",\n\t\tresave: true,\n\t\trolling: true,\n\t\tsaveUninitialized: true,\n\t\tcookie: {\n\t\t\tmaxAge: 60 * 60 * 1000,\n\t\t},\n\t\tgenid: uuidv4,\n\t}),\n);\n\napp.get('/', (req, res) => {\n\tconst sess = req.session;\n\tconsole.log(sess);\n\tres.status(200).json();\n});\n\napp.post('/login', (req, res) => {\n\tconst { username } = req.body;\n\tconst sess = req.session;\n\tsess.username = username;\n\tres.status(200).json();\n});\n\napp.get('/home', (req, res) => {\n\tconst sess = req.session;\n\tconsole.log(sess.username);\n\tres.status(200).json();\n});\n\n\napp.get('/logout', (req, res) => {\n\tconst sess = req.session;\n\treq.session.destroy((err) => {\n\t\treturn res.status(500).json();\n\t});\n\tres.status(200).json();\n});\n\napp.listen(3000, () => {\n\tconsole.log(\"Server running on Port 3000\");\n});\n", "dangerousExampleEn": "1. //--cookie-session\n2. let session = cookieSession({\n3. httpOnly: false,\n4. secure: false,\n5. });\n6. \n7. \n8. //--express-session\n9. const express = require('express');\n10. const session = require('express-session');\n11. let app = express();\n12. app.use(session({\n13. cookie:\n14. {\n15. secure: false,\n16. httpOnly: false\n17. }\n18. }));\n19. \n20. \n21. //--cookies\n22. let cookies = new Cookies(req, res, { keys: keys });\n23. cookies.set('LastVisit', new Date().toISOString(), {\n24. httpOnly: false,\n25. secure: false\n26. });\n27. \n28. //--csurf\n29. const cookieParser = require('cookie-parser');\n30. const csrf = require('csurf');\n31. const express = require('express');\n32. let csrfProtection = csrf({ cookie: { secure: false, httpOnly: false }});\nLine 3, 4, 15, 16, 24, 25, 32: This is insecure because the `secure` and `HttpOnly` flags are set to false.", "safeExampleEn": "1. //--cookie-session\n2. let session = cookieSession({\n3. httpOnly: true,\n4. secure: true,\n5. });\n6. \n7. \n8. //--express-session\n9. const express = require('express');\n10. const session = require('express-session');\n11. let app = express();\n12. app.use(session({\n13. cookie:\n14. {\n15. secure: true,\n16. httpOnly: true\n17. }\n18. }));\n19. \n20. \n21. //--cookies\n22. let cookies = new Cookies(req, res, { keys: keys });\n23. cookies.set('LastVisit', new Date().toISOString(), {\n24. httpOnly: true,\n25. secure: true\n26. });\n27. \n28. //--csurf\n29. const cookieParser = require('cookie-parser');\n30. const csrf = require('csurf');\n31. const express = require('express');\n32. let csrfProtection = csrf({ cookie: { secure: true, httpOnly: true }});\nLine 3, 4, 15, 16, 24, 25, 32: This is secure because the `secure` and `HttpOnly` flags are set to true.", "contexts": [{"lineNo": 11, "eventType": "sink", "messageKey": "jschk.SENSITIVE_COOKIE.FLAG.JS.defect.notset", "params": {}}]}} {"id": "3dd7b032bf6aa071fe12bf57cacd2312718fdd562556c6f3334913e45cd3f67d", "license": {"spdx": ["MIT"], "repo": "EncodedBunny/Dataview", "path": "app.js", "repo_head_hexsha": "a8ec76383696440d26be3d32519986f0c17b461b", "stack_hexsha": "cd9516039990e13a555bc4359f2da0238054c4b9", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Improper Cookie Flag Setting", "issueDescriptionEn": "Generally, web application uses cookies to send session information. However, the improper use of cookie flags may lead to vulnerabilities in session management such as MITM attacks or cookie stealing using XSS.\nIn Node.js, it is necessary to set security flags such as `secure` and `HttpOnly` to true for session management to enable cookie safety.", "issueLineNumber": 110, "entireCode": "module.exports = function(port){\n\tconst createError = require('http-errors');\n\tconst express = require('express');\n\tconst path = require('path');\n\tconst logger = require('morgan');\n\tconst sassMiddleware = require('node-sass-middleware');\n\tconst fileUpload = require('express-fileupload');\n\tconst http = require('http');\n\tconst url = require(\"url\");\n\tconst favicon = require('serve-favicon');\n\tconst session = require(\"express-session\");\n\tconst crypto = require(\"crypto\");\n\t\n\tArray.prototype.remove = function(x) {\n\t\tlet i = this.indexOf(+x);\n\t\tif(i > -1)\n\t\t\tthis.splice(i, 1);\n\t\treturn this;\n\t};\n\t\n\tconst users = require(\"./users\");\n\t\n\tconst driverManager = require('./driverManager');\n\tconst deviceManager = require('./deviceManager')(driverManager);\n\tconst fileManager = require(\"./fileManager\")();\n\tconst experimentManager = require('./experimentManager')(deviceManager, driverManager, fileManager);\n\n\tconst indexRouter = require('./routes/index');\n\tconst usersRouter = require('./routes/users');\n\tconst devicesRouter = require('./routes/devices')(driverManager, deviceManager);\n\tconst experimentsRouter = require('./routes/experiments')(deviceManager, experimentManager, fileManager);\n\tconst settingsRouter = require('./routes/settings');\n\tconst driversRouter = require('./routes/drivers')(driverManager, fileManager);\n\t\n\tconst settings = require(\"./settings\");\n\t\n\tconst cp = require(\"child_process\");\n\t\n\tlet child = cp.spawn(path.join(__dirname, \"node_modules\", \"electron\", \"dist\", \"electron.exe\"), [path.join(__dirname, \"interface.js\")], {\n\t\tstdio: [ \"ignore\", \"ignore\", \"ignore\" ]\n\t});\n\t\n\tlet app = express();\n\t\n\tapp.use(logger('dev'));\n\tapp.use(express.json());\n\tapp.use(express.urlencoded({ extended: false }));\n\t\n\tapp.set(\"views\", path.join(__dirname, \"views\"));\n\tapp.set(\"view engine\", \"twig\");\n\tapp.disable(\"x-powered-by\");\n\t\n\tlet sessionSecret = settings.getSetting(\"sessionSecret\");\n\tif(sessionSecret === undefined || sessionSecret.length <= 0){\n\t\tsessionSecret = crypto.randomBytes(32).toString(\"hex\");\n\t\tsettings.setSetting(\"sessionSecret\", sessionSecret);\n\t}\n\t\n\tlet sessionConfig = {\n\t\tsecret: sessionSecret,\n\t\tname: \"dv_sid\",\n\t\tresave: false,\n\t\tsaveUninitialized: true,\n\t\tcookie: {\n\t\t\tmaxAge: 1000*60*30,\n\t\t\thttpOnly: true\n\t\t}\n\t};\n\t\n\tif(app.get(\"env\") === \"production\") {\n\t\tapp.set(\"trust proxy\", 1);\n\t\tsessionConfig.cookie.secure = true;\n\t}\n\t\n\tapp.use((req, res, next) => {\n\t\tres.setHeader(\"X-Frame-Options\", \"DENY\");\n\t\tres.setHeader(\"X-XSS-Protection\", \"1; mode=block\");\n\t\tres.setHeader(\"X-Content-Type-Options\", \"nosniff\");\n\t\tnext();\n\t});\n\tapp.use(fileUpload({\n\t\tlimits: {\n\t\t\tfileSize: 10 * 1024 * 1024\n\t\t},\n\t\tuseTempFiles: true,\n\t\ttempFileDir: fileManager.tmpDir\n\t}));\n\t\n\tapp.use(sassMiddleware({\n\t\tsrc: path.join(__dirname, \"public\"),\n\t\tdest: path.join(__dirname, \"public\"),\n\t\tindentedSyntax: true,\n\t\tsourceMap: true,\n\t\tincludePaths: path.join(__dirname, \"node_modules\")\n\t}));\n\t/*app.use(\"stylesheets/\", postCssMiddleware({\n\t\tplugins: [autoprefixer()],\n\t\toptions: {\n\t\t\tmap: {\n\t\t\t\tinline: true\n\t\t\t}\n\t\t},\n\t\tsrc: req => {\n\t\t\treturn path.join(__dirname, \"public\", req.path);\n\t\t}\n\t}));*/\n\tapp.use(express.static(path.join(__dirname, \"public\")));\n\tapp.use(favicon(path.join(__dirname, \"public\", \"images\", \"favicon.ico\")));\n\t\n\tapp.use(session(sessionConfig));\n\t\n\tapp.use(\"/\", indexRouter);\n\tapp.use((req, res, next) => {\n\t\tif(!req.session.user && req.session.cookie)\n\t\t\tres.clearCookie(\"dv_sid\");\n\t\tnext();\n\t});\n\tapp.use((req, res, next) => {\n\t\tif(!req.session.user)\n\t\t\tres.redirect(\"/\");\n\t\telse\n\t\t\tnext();\n\t});\n\tapp.use(\"/users\", usersRouter);\n\tapp.use(\"/devices\", devicesRouter);\n\tapp.use(\"/experiments\", experimentsRouter);\n\tapp.use(\"/settings\", settingsRouter);\n\tapp.use(\"/drivers\", driversRouter);\n\t\n\tapp.use(function(req, res, next) {\n\t\tnext(createError(404));\n\t});\n\t\n\tapp.use(function(err, req, res, next) {\n\t\tres.locals.message = err.message;\n\t\tres.locals.error = req.app.get('env') === 'development' ? err : {};\n\t\t\n\t\tres.status(err.status || 500);\n\t\tres.render('error');\n\t});\n\t\n\tapp.server = http.createServer(app);\n\tapp.server.listen(port);\n\n\tconst io = require(\"socket.io\")(app.server);\n\tio.on('connection', function(socket){\n\t\tlet linkFunction = function(name, fun, keys, values) {\n\t\t\tsocket.on(name, (data, res) => {\n\t\t\t\tlet args = [];\n\t\t\t\tif(keys !== undefined)\n\t\t\t\t\tif(keys.length > 0)\n\t\t\t\t\t\tfor(const key of keys)\n\t\t\t\t\t\t\targs.push((values !== undefined ? values[key] : undefined) || data[key]);\n\t\t\t\t\telse\n\t\t\t\t\t\targs.push(data);\n\t\t\t\tlet result = fun.apply(undefined, args);\n\t\t\t\tlet respond = () => {\n\t\t\t\t\tif (res && typeof res === \"function\") res(result);\n\t\t\t\t\telse socket.emit(name, result);\n\t\t\t\t};\n\t\t\t\tif(typeof result === \"object\" && typeof result.then === \"function\"){\n\t\t\t\t\tresult.then(res => {\n\t\t\t\t\t\tresult = res;\n\t\t\t\t\t\trespond();\n\t\t\t\t\t}).catch(err => {\n\t\t\t\t\t\tresult = err;\n\t\t\t\t\t\trespond();\n\t\t\t\t\t});\n\t\t\t\t} else{\n\t\t\t\t\trespond();\n\t\t\t\t}\n\t\t\t});\n\t\t};\n\t\tlet checkAndGetFromUrl = function(parent){\n\t\t\tlet path = new url.URL(socket.request.headers.referer || \"\").pathname;\n\t\t\tif(path.length > 0)\n\t\t\t\tpath = path.substring(1);\n\t\t\tpath = path.split(\"/\");\n\t\t\tif(path.length >= 2 && path[0] === parent)\n\t\t\t\treturn path[1];\n\t\t\treturn \"\";\n\t\t};\n\t\tlinkFunction(\"addDevice\", deviceManager.addDevice,[\"name\", \"type\", \"extraData\", \"model\"]);\n\t\tlinkFunction(\"getDevice\", deviceManager.getDevice,[\"id\"]);\n\t\tlinkFunction(\"getDevices\", deviceManager.getDevices);\n\t\t\n\t\tsocket.on(\"listenDevice\", deviceID => {\n\t\t\tlet dev = deviceManager.getDevice(deviceID || checkAndGetFromUrl(\"devices\"));\n\t\t\tif(dev)\n\t\t\t\tdev.addListener(socket.id, (updates) => { // TODO: Add this listener to default device listener function\n\t\t\t\t\tlet ups = {};\n\t\t\t\t\tfor(const senID of Object.keys(dev.sensors))\n\t\t\t\t\t\tif (Object.keys(updates).includes(dev.sensors[senID].id + \"\"))\n\t\t\t\t\t\t\tups[senID] = updates[dev.sensors[senID].id];\n\t\t\t\t\tsocket.emit(\"sensorData\", ups);\n\t\t\t\t});\n\t\t});\n\t\t\n\t\tlinkFunction(\"addSensor\", deviceManager.addSensor,[\"deviceID\", \"name\", \"location\", \"extraData\"]);\n\t\tlinkFunction(\"addActuator\", deviceManager.addActuator,[\"deviceID\", \"name\", \"location\", \"extraData\"]);\n\t\tlinkFunction(\"addPeripheral\", deviceManager.addPeripheral,[\"deviceID\", \"name\", \"model\", \"extraData\"]);\n\t\tlinkFunction(\"getPeripheralForm\", deviceManager.getPeripheralForm,[\"deviceID\", \"model\"]);\n\t\tlinkFunction(\"configureSensor\", deviceManager.configureSensor,[\"deviceID\", \"sensorID\", \"location\", \"extraData\"]);\n\t\tlinkFunction(\"configureActuator\", deviceManager.configureActuator,[\"deviceID\", \"sensorID\", \"location\", \"extraData\"]);\n\t\tlinkFunction(\"removeSensor\", deviceManager.removeSensor,[\"deviceID\", \"sensorID\"],{deviceID: checkAndGetFromUrl(\"devices\")});\n\t\tlinkFunction(\"setDeviceI2C\", deviceManager.setI2C,[\"deviceID\", \"enabled\"]);\n\t\t\n\t\tlinkFunction(\"addExperiment\", experimentManager.addExperiment,[\"name\"]);\n\t\tlinkFunction(\"getExperiment\", experimentManager.getExperiment,[\"id\"]);\n\t\tlinkFunction(\"getExperiments\", experimentManager.getExperiments);\n\t\tlinkFunction(\"setExperimentMeasurement\", experimentManager.setExperimentMeasurement,[\"id\", \"condition\", \"frequency\", \"measurementData\"]);\n\t\tlinkFunction(\"updateExperimentDataflow\", experimentManager.updateExperimentDataflow,[\"id\", \"dataflowStructure\"]);\n\t\tlinkFunction(\"beginExperiment\", experimentManager.beginExperiment, [\"id\"]);\n\t\tlinkFunction(\"stopExperiment\", experimentManager.stopExperiment, [\"id\"]);\n\t\tlinkFunction(\"addGraphToExperiment\", experimentManager.addGraphToExperiment,[\"experimentID\", \"title\", \"xLbl\", \"yLbl\", \"saveType\"]);\n\t\tlinkFunction(\"listenToExperiment\", experimentManager.listenToExperiment,[\"id\", \"listenerID\", \"listener\"],{\n\t\t\tlistenerID: socket.id,\n\t\t\tlistener: {\n\t\t\t\tonGraphData: (title, point) => {\n\t\t\t\t\tsocket.emit(\"graphData\", {title: title, point: point});\n\t\t\t\t},\n\t\t\t\tonEnd: () => {\n\t\t\t\t\tsocket.emit(\"experimentEnd\");\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\t\n\t\t// TODO: Temporary fix, final fix will be to create a single manager that uses UUID namespaces\n\t\tsocket.on(\"getDevicesAndExperiments\", (res) => {\n\t\t\tlet obj = {\n\t\t\t\tdevices: deviceManager.getDevices(),\n\t\t\t\texperiments: experimentManager.getExperimentList().map(experiment => {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tname: experiment.name,\n\t\t\t\t\t\tid: experiment.id\n\t\t\t\t\t};\n\t\t\t\t})\n\t\t\t};\n\t\t\tif(res && typeof res === \"function\") res(obj);\n\t\t\telse socket.emit(\"getDevicesAndExperiments\", obj);\n\t\t});\n\t\t\n\t\tsocket.on('disconnect', function() {\n\t\t\tfor(const experiment of experimentManager.getExperimentList())\n\t\t\t\texperiment.removeListener(socket.id);\n\t\t});\n\t});\n\n\treturn app;\n};", "dangerousExampleEn": "1. //--cookie-session\n2. let session = cookieSession({\n3. httpOnly: false,\n4. secure: false,\n5. });\n6. \n7. \n8. //--express-session\n9. const express = require('express');\n10. const session = require('express-session');\n11. let app = express();\n12. app.use(session({\n13. cookie:\n14. {\n15. secure: false,\n16. httpOnly: false\n17. }\n18. }));\n19. \n20. \n21. //--cookies\n22. let cookies = new Cookies(req, res, { keys: keys });\n23. cookies.set('LastVisit', new Date().toISOString(), {\n24. httpOnly: false,\n25. secure: false\n26. });\n27. \n28. //--csurf\n29. const cookieParser = require('cookie-parser');\n30. const csrf = require('csurf');\n31. const express = require('express');\n32. let csrfProtection = csrf({ cookie: { secure: false, httpOnly: false }});\nLine 3, 4, 15, 16, 24, 25, 32: This is insecure because the `secure` and `HttpOnly` flags are set to false.", "safeExampleEn": "1. //--cookie-session\n2. let session = cookieSession({\n3. httpOnly: true,\n4. secure: true,\n5. });\n6. \n7. \n8. //--express-session\n9. const express = require('express');\n10. const session = require('express-session');\n11. let app = express();\n12. app.use(session({\n13. cookie:\n14. {\n15. secure: true,\n16. httpOnly: true\n17. }\n18. }));\n19. \n20. \n21. //--cookies\n22. let cookies = new Cookies(req, res, { keys: keys });\n23. cookies.set('LastVisit', new Date().toISOString(), {\n24. httpOnly: true,\n25. secure: true\n26. });\n27. \n28. //--csurf\n29. const cookieParser = require('cookie-parser');\n30. const csrf = require('csurf');\n31. const express = require('express');\n32. let csrfProtection = csrf({ cookie: { secure: true, httpOnly: true }});\nLine 3, 4, 15, 16, 24, 25, 32: This is secure because the `secure` and `HttpOnly` flags are set to true.", "contexts": [{"lineNo": 110, "eventType": "sink", "messageKey": "jschk.SENSITIVE_COOKIE.FLAG.JS.defect.notset", "params": {}}]}} {"id": "bffb5411661266da6dd7f8950b67493d5c0fb76d081383293e791e9f949f5980", "license": {"spdx": ["Apache-2.0"], "repo": "AndresIturria/Cat-Attack", "path": "src/index.js", "repo_head_hexsha": "19ce61174a4b59edc27352327adf2e8153b64550", "stack_hexsha": "4181f2a7d4c025005b5edf5dca22c090568f1ecf", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Improper Cookie Flag Setting", "issueDescriptionEn": "Generally, web application uses cookies to send session information. However, the improper use of cookie flags may lead to vulnerabilities in session management such as MITM attacks or cookie stealing using XSS.\nIn Node.js, it is necessary to set security flags such as `secure` and `HttpOnly` to true for session management to enable cookie safety.", "issueLineNumber": 32, "entireCode": "const express = require('express');\nconst nunjucks = require('nunjucks');\nconst path = require('path');\nconst morgan = require('morgan');\nconst passport = require('passport');\nconst session = require('express-session');\nconst flash = require('connect-flash');\nconst createError = require(\"http-errors\");\nconst fileUpload = require('express-fileupload');\n\n//Initializations\nrequire('./database');\nrequire('./passport/local-auth');\n\nconst app = express();\n\n//settings\napp.engine( 'html', nunjucks.render) ;\napp.set( 'view engine', 'html');\n\nnunjucks.configure(path.join(__dirname, '/views'), {\n autoescape: true,\n express: app\n});\n\n//middlewares\napp.use(express.static(path.join(__dirname, 'public')));\napp.use(express.json()); // to support JSON-encoded bodies\napp.use(express.urlencoded( { extended: true } )); // to support URL-encoded bodies\nmorgan.token('body', (req, res) => JSON.stringify(req.body));\napp.use(morgan(':method :url :status :response-time ms :body '));\napp.use(session({\n secret: 'pruebasecreto',\n resave: false,\n saveUninitialized: false\n}));\napp.use(flash());\napp.use(fileUpload());\napp.use(passport.initialize());\napp.use(passport.session());\napp.use((req, res, next) => { //Esto es un Middleware propio para poder acceder al mensaje de signup en la vista de registrarse.\n app.locals.signinMessage = req.flash('signinMessage');\n app.locals.signupMessage = req.flash('signupMessage');\n app.locals.user = req.user;\n next(); // Sin este next se va a quedar estancado aqui\n});\n\n\n//Routes\napp.use('/', require('./routes/index'));\napp.use('/registrarse', require('./routes/registrarse'));\napp.use('/logout', isAuthenticated, require('./routes/logout'));\napp.use('/dashboard', isAuthenticated, require('./routes/dashboard'));\napp.use('/adopcion', isAuthenticated, require('./routes/adopcion'));\napp.use('/consejos', isAuthenticated, require('./routes/consejos'));\napp.use('/miperfil', isAuthenticated, require('./routes/miperfil'));\napp.use('/adopt_form', isAuthenticated, require('./routes/adopt_form'));\napp.use('/catsitting', isAuthenticated, require('./routes/catsitting'));\napp.use('/catsitting_form', isAuthenticated, require('./routes/catsitting_form'));\napp.use('/consejo_form', isAuthenticated, require('./routes/consejo_form'));\napp.use('/incidencias', isAuthenticated, require('./routes/incidencias'));\napp.use('/enviar_incidencia', isAuthenticated, require('./routes/enviar_incidencia'));\napp.use('/chat', isAuthenticated, require('./routes/chat'));\napp.use('/perfil_form_foto', isAuthenticated, require('./routes/perfil_form_foto'));\napp.use('/perfil_form_password', isAuthenticated, require('./routes/perfil_form_password'));\n\n// catch 404 and forward to error handler\napp.use(function(req, res, next) {\n next(createError(404));\n});\n\n// error handler\napp.use(function(err, req, res, next) {\n // set locals, only providing error in development\n res.locals.message = err.message;\n res.locals.error = req.app.get('env') === 'development' ? err : {};\n\n // render the error page\n res.status(err.status || 500);\n res.render('error.njk');\n});\n\n// Authentication\n\nfunction isAuthenticated(req, res, next) {\n if(req.isAuthenticated()) { // req.isAuthenticated is a function provided by passport.\n return next();\n }\n res.redirect('/')\n}\n\nmodule.exports = app;", "dangerousExampleEn": "1. //--cookie-session\n2. let session = cookieSession({\n3. httpOnly: false,\n4. secure: false,\n5. });\n6. \n7. \n8. //--express-session\n9. const express = require('express');\n10. const session = require('express-session');\n11. let app = express();\n12. app.use(session({\n13. cookie:\n14. {\n15. secure: false,\n16. httpOnly: false\n17. }\n18. }));\n19. \n20. \n21. //--cookies\n22. let cookies = new Cookies(req, res, { keys: keys });\n23. cookies.set('LastVisit', new Date().toISOString(), {\n24. httpOnly: false,\n25. secure: false\n26. });\n27. \n28. //--csurf\n29. const cookieParser = require('cookie-parser');\n30. const csrf = require('csurf');\n31. const express = require('express');\n32. let csrfProtection = csrf({ cookie: { secure: false, httpOnly: false }});\nLine 3, 4, 15, 16, 24, 25, 32: This is insecure because the `secure` and `HttpOnly` flags are set to false.", "safeExampleEn": "1. //--cookie-session\n2. let session = cookieSession({\n3. httpOnly: true,\n4. secure: true,\n5. });\n6. \n7. \n8. //--express-session\n9. const express = require('express');\n10. const session = require('express-session');\n11. let app = express();\n12. app.use(session({\n13. cookie:\n14. {\n15. secure: true,\n16. httpOnly: true\n17. }\n18. }));\n19. \n20. \n21. //--cookies\n22. let cookies = new Cookies(req, res, { keys: keys });\n23. cookies.set('LastVisit', new Date().toISOString(), {\n24. httpOnly: true,\n25. secure: true\n26. });\n27. \n28. //--csurf\n29. const cookieParser = require('cookie-parser');\n30. const csrf = require('csurf');\n31. const express = require('express');\n32. let csrfProtection = csrf({ cookie: { secure: true, httpOnly: true }});\nLine 3, 4, 15, 16, 24, 25, 32: This is secure because the `secure` and `HttpOnly` flags are set to true.", "contexts": [{"lineNo": 32, "eventType": "sink", "messageKey": "jschk.SENSITIVE_COOKIE.FLAG.JS.defect.notset", "params": {}}]}} {"id": "3d7caeb8a3baa41b02248fe90bd67911534e9db32cca10709098858e256f625e", "license": {"spdx": ["MIT"], "repo": "beyondnetPeru/BeyondNet.Sample.Typescript", "path": "react-sample/backend/app.js", "repo_head_hexsha": "0cce64b1f3d504fa2f1a5ced8b0dcd48b4ec8d5a", "stack_hexsha": "7b3ecdd6173efda32512551de5788c6f5d6d8988", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Improper Cookie Flag Setting", "issueDescriptionEn": "Generally, web application uses cookies to send session information. However, the improper use of cookie flags may lead to vulnerabilities in session management such as MITM attacks or cookie stealing using XSS.\nIn Node.js, it is necessary to set security flags such as `secure` and `HttpOnly` to true for session management to enable cookie safety.", "issueLineNumber": 47, "entireCode": "require('dotenv').config();\nconst express = require('express');\nconst session = require('express-session');\nconst passport = require('passport');\nconst SequelizeStore = require('connect-session-sequelize')(session.Store);\nconst passportConfig = require('./config/passport');\nconst sequelize = require('./utils/sequelize-singleton');\nconst logger = require('morgan');\nconst bodyParser = require('body-parser');\nconst cookieParser = require('cookie-parser');\nconst cors = require('cors');\nconst helmet = require('helmet');\nconst RateLimit = require('express-rate-limit');\nconst compression = require('compression');\nconst auth = require('./middlewares/auth');\n\nrequire('./models/User');\nrequire('./models/Session');\n\nconst app = express();\n// security filter\napp.use(helmet());\n\n// Compress all routes\napp.use(compression());\napp.use(logger('dev'));\n\nconst limiter = new RateLimit({\n windowMs: 15 * 60 * 1000, // 15 minutes\n max: 1000, // limit each IP to 100 requests per windowMs\n delayMs: 0, // disable delaying - full speed until the max limit is reached\n});\n// apply to all requests\napp.use(limiter);\n\napp.use(\n bodyParser.urlencoded({\n extended: true,\n }),\n);\napp.use(bodyParser.json());\napp.use(cookieParser());\n\nconst origin = process.env.FRONTEND_URL;\napp.use(cors({ origin, credentials: true }));\n\nconst sessionMiddleware = session({\n secret: process.env.SESSION_SECRET,\n resave: false,\n saveUninitialized: false,\n cookie: {\n maxAge: 30 * 24 * 60 * 60 * 1000, // 1 month\n secure: process.env.NODE_ENV === 'production',\n },\n store: new SequelizeStore({\n db: sequelize,\n table: 'Session',\n }),\n});\n\npassportConfig(passport);\napp.use(sessionMiddleware);\napp.use(passport.initialize());\napp.use(passport.session());\n\napp.post('/user/login', require('./routes/login'));\napp.post('/user/register', require('./routes/sign-up'));\napp.get('/user/authenticated', require('./routes/authenticated'));\napp.get('/user/logout', require('./routes/logout'));\napp.get('/user/all/:username?', auth, require('./routes/users'));\napp.get('/user/:userId', auth, require('./routes/userById'));\napp.put('/user/:userId', auth, require('./routes/userEdit'));\n\napp.use((err, req, res) => {\n if (!err.statusCode) err.statusCode = 500;\n\n res.status(err.statusCode).json({\n errors: [{\n message: err.message,\n }],\n type: 'error',\n statusCode: err.statusCode,\n });\n});\n\nmodule.exports = {\n app,\n sessionMiddleware,\n};", "dangerousExampleEn": "1. //--cookie-session\n2. let session = cookieSession({\n3. httpOnly: false,\n4. secure: false,\n5. });\n6. \n7. \n8. //--express-session\n9. const express = require('express');\n10. const session = require('express-session');\n11. let app = express();\n12. app.use(session({\n13. cookie:\n14. {\n15. secure: false,\n16. httpOnly: false\n17. }\n18. }));\n19. \n20. \n21. //--cookies\n22. let cookies = new Cookies(req, res, { keys: keys });\n23. cookies.set('LastVisit', new Date().toISOString(), {\n24. httpOnly: false,\n25. secure: false\n26. });\n27. \n28. //--csurf\n29. const cookieParser = require('cookie-parser');\n30. const csrf = require('csurf');\n31. const express = require('express');\n32. let csrfProtection = csrf({ cookie: { secure: false, httpOnly: false }});\nLine 3, 4, 15, 16, 24, 25, 32: This is insecure because the `secure` and `HttpOnly` flags are set to false.", "safeExampleEn": "1. //--cookie-session\n2. let session = cookieSession({\n3. httpOnly: true,\n4. secure: true,\n5. });\n6. \n7. \n8. //--express-session\n9. const express = require('express');\n10. const session = require('express-session');\n11. let app = express();\n12. app.use(session({\n13. cookie:\n14. {\n15. secure: true,\n16. httpOnly: true\n17. }\n18. }));\n19. \n20. \n21. //--cookies\n22. let cookies = new Cookies(req, res, { keys: keys });\n23. cookies.set('LastVisit', new Date().toISOString(), {\n24. httpOnly: true,\n25. secure: true\n26. });\n27. \n28. //--csurf\n29. const cookieParser = require('cookie-parser');\n30. const csrf = require('csurf');\n31. const express = require('express');\n32. let csrfProtection = csrf({ cookie: { secure: true, httpOnly: true }});\nLine 3, 4, 15, 16, 24, 25, 32: This is secure because the `secure` and `HttpOnly` flags are set to true.", "contexts": [{"lineNo": 47, "eventType": "sink", "messageKey": "jschk.SENSITIVE_COOKIE.FLAG.JS.defect.notset", "params": {}}]}} {"id": "ebdf074f4feaab61bfdc5df6c1d010ec2b1293eee0fd53f88ae66a781ea789cf", "license": {"spdx": ["MIT"], "repo": "chintance99/staging-deploy", "path": "src/session.js", "repo_head_hexsha": "805375b1652b4f54902609dc6d85a91cde0b7b91", "stack_hexsha": "252bdca9d5c84312f30f7efc9b69b6f681800b2f", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Improper Cookie Flag Setting", "issueDescriptionEn": "Generally, web application uses cookies to send session information. However, the improper use of cookie flags may lead to vulnerabilities in session management such as MITM attacks or cookie stealing using XSS.\nIn Node.js, it is necessary to set security flags such as `secure` and `HttpOnly` to true for session management to enable cookie safety.", "issueLineNumber": 10, "entireCode": "const session = require('express-session');\nconst MongoStore = require('connect-mongo');\n\n\nmodule.exports = function sessionInit(app) {\n const connectionString = app.get('databaseUrl');\n if (!connectionString) throw new Error('Database connection string is not set in config \\'databaseUrl\\'');\n const tlsEnabled = app.get('tlsEnabled');\n\n const sess = session({\n cookie: {\n secure: tlsEnabled,\n },\n\n // True if we do SSL external to Node\n proxy: tlsEnabled,\n\n // session-sequelize supports the touch method so per the\n // express-session docs this should be set to false\n resave: false,\n\n saveUninitialized: true,\n secret: app.get('sessionSecret'),\n store: MongoStore.create({\n mongoUrl: connectionString,\n }),\n });\n\n app.set('expressSession', sess);\n app.use(sess);\n};", "dangerousExampleEn": "1. //--cookie-session\n2. let session = cookieSession({\n3. httpOnly: false,\n4. secure: false,\n5. });\n6. \n7. \n8. //--express-session\n9. const express = require('express');\n10. const session = require('express-session');\n11. let app = express();\n12. app.use(session({\n13. cookie:\n14. {\n15. secure: false,\n16. httpOnly: false\n17. }\n18. }));\n19. \n20. \n21. //--cookies\n22. let cookies = new Cookies(req, res, { keys: keys });\n23. cookies.set('LastVisit', new Date().toISOString(), {\n24. httpOnly: false,\n25. secure: false\n26. });\n27. \n28. //--csurf\n29. const cookieParser = require('cookie-parser');\n30. const csrf = require('csurf');\n31. const express = require('express');\n32. let csrfProtection = csrf({ cookie: { secure: false, httpOnly: false }});\nLine 3, 4, 15, 16, 24, 25, 32: This is insecure because the `secure` and `HttpOnly` flags are set to false.", "safeExampleEn": "1. //--cookie-session\n2. let session = cookieSession({\n3. httpOnly: true,\n4. secure: true,\n5. });\n6. \n7. \n8. //--express-session\n9. const express = require('express');\n10. const session = require('express-session');\n11. let app = express();\n12. app.use(session({\n13. cookie:\n14. {\n15. secure: true,\n16. httpOnly: true\n17. }\n18. }));\n19. \n20. \n21. //--cookies\n22. let cookies = new Cookies(req, res, { keys: keys });\n23. cookies.set('LastVisit', new Date().toISOString(), {\n24. httpOnly: true,\n25. secure: true\n26. });\n27. \n28. //--csurf\n29. const cookieParser = require('cookie-parser');\n30. const csrf = require('csurf');\n31. const express = require('express');\n32. let csrfProtection = csrf({ cookie: { secure: true, httpOnly: true }});\nLine 3, 4, 15, 16, 24, 25, 32: This is secure because the `secure` and `HttpOnly` flags are set to true.", "contexts": [{"lineNo": 10, "eventType": "sink", "messageKey": "jschk.SENSITIVE_COOKIE.FLAG.JS.defect.notset", "params": {}}]}} {"id": "bd6347868594d8d1aeea467bfa71100b54b0a90d6de0ec10801ca806e10dc6db", "license": {"spdx": ["MIT"], "repo": "CrumrineCoder/VotingApp", "path": "server.js", "repo_head_hexsha": "2cb2b67d9310bde20853d2dd59fd7ca334a0b192", "stack_hexsha": "c91f802ea0a347b3c5e8e81da60d05f44d3a1123", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Improper Cookie Flag Setting", "issueDescriptionEn": "Generally, web application uses cookies to send session information. However, the improper use of cookie flags may lead to vulnerabilities in session management such as MITM attacks or cookie stealing using XSS.\nIn Node.js, it is necessary to set security flags such as `secure` and `HttpOnly` to true for session management to enable cookie safety.", "issueLineNumber": 53, "entireCode": "\n'use strict';\n/* Authentication: */\n/*\n This file handles connecting the user to the server and the controllers to the database. \n*/\nvar path = require('path');\nvar cookieParser = require('cookie-parser');\nvar bodyParser = require('body-parser');\nvar exphbs = require('express-handlebars');\nvar expressValidator = require('express-validator');\nvar flash = require('connect-flash');\nvar session = require('express-session');\nvar passport = require('passport');\nvar LocalStrategy = require('passport-local').Strategy;\n\n// Connecte to the database with Mongoose\nvar mongoose = require('mongoose');\nmongoose.connect('mongodb://' + process.env.HOST + '/' + process.env.NAME, {\n useMongoClient: true\n});\nvar db = mongoose.connection;\n// Get the other routes\nvar polls = require('./app/routes/polls.js');\nvar users = require('./app/routes/users.js');\nvar express = require('express'),\n routes = require('./app/routes/index.js'),\n mongodb = require('mongodb');\nvar MongoClient = mongodb.MongoClient;\nvar mLab = 'mongodb://' + process.env.HOST + '/' + process.env.NAME;\nvar app = express();\n\n// Set up the view engine, handlebars\napp.set('views', path.join(__dirname, 'views'));\napp.engine('handlebars', exphbs({\n defaultLayout: 'layout'\n}));\napp.set('view engine', 'handlebars');\n\n// Parsers for cookies and body\napp.use(bodyParser.json());\napp.use(bodyParser.urlencoded({\n extended: false\n}));\napp.use(cookieParser());\n\n// Shortcut the other directories\napp.use('/public', express.static(process.cwd() + '/public'));\napp.use('/controllers', express.static(process.cwd() + '/app/controllers'));\napp.use('/views', express.static(process.cwd() + '/views'));\n\n// Passport session\napp.use(session({\n secret: process.env.PASSKEY,\n saveUninitialized: true,\n resave: true\n}));\napp.use(passport.initialize());\napp.use(passport.session());\napp.use(passport.authenticate('remember-me'));\n\n// Bodyparser validation\napp.use(expressValidator({\n errorFormatter: function(param, msg, value) {\n var namespace = param.split('.'),\n root = namespace.shift(),\n formParam = root;\n\n while (namespace.length) {\n formParam += '[' + namespace.shift() + ']';\n }\n return {\n param: formParam,\n msg: msg,\n value: value\n };\n }\n}));\n// Error message formatting\napp.use(flash());\n\napp.use(function(req, res, next) {\n res.locals.success_msg = req.flash('success_msg');\n res.locals.error_msg = req.flash('error_msg');\n res.locals.error = req.flash('error');\n res.locals.user = req.user || null;\n next();\n});\n\n// Routing\napp.use('/users', users);\napp.use('/polls', polls);\n// Connect to the database with MongoDB\nMongoClient.connect(mLab, function(err, db) {\n \n if (err) {\n throw new Error('Database failed to connect!');\n } else {\n // console.log('MongoDB successfully connected on port 27017.');\n }\n \n //Exports the routes to app and db\n routes(app, db);\n app.listen(3000, function() {\n // console.log('Listening on port 3000...');\n });\n});", "dangerousExampleEn": "1. //--cookie-session\n2. let session = cookieSession({\n3. httpOnly: false,\n4. secure: false,\n5. });\n6. \n7. \n8. //--express-session\n9. const express = require('express');\n10. const session = require('express-session');\n11. let app = express();\n12. app.use(session({\n13. cookie:\n14. {\n15. secure: false,\n16. httpOnly: false\n17. }\n18. }));\n19. \n20. \n21. //--cookies\n22. let cookies = new Cookies(req, res, { keys: keys });\n23. cookies.set('LastVisit', new Date().toISOString(), {\n24. httpOnly: false,\n25. secure: false\n26. });\n27. \n28. //--csurf\n29. const cookieParser = require('cookie-parser');\n30. const csrf = require('csurf');\n31. const express = require('express');\n32. let csrfProtection = csrf({ cookie: { secure: false, httpOnly: false }});\nLine 3, 4, 15, 16, 24, 25, 32: This is insecure because the `secure` and `HttpOnly` flags are set to false.", "safeExampleEn": "1. //--cookie-session\n2. let session = cookieSession({\n3. httpOnly: true,\n4. secure: true,\n5. });\n6. \n7. \n8. //--express-session\n9. const express = require('express');\n10. const session = require('express-session');\n11. let app = express();\n12. app.use(session({\n13. cookie:\n14. {\n15. secure: true,\n16. httpOnly: true\n17. }\n18. }));\n19. \n20. \n21. //--cookies\n22. let cookies = new Cookies(req, res, { keys: keys });\n23. cookies.set('LastVisit', new Date().toISOString(), {\n24. httpOnly: true,\n25. secure: true\n26. });\n27. \n28. //--csurf\n29. const cookieParser = require('cookie-parser');\n30. const csrf = require('csurf');\n31. const express = require('express');\n32. let csrfProtection = csrf({ cookie: { secure: true, httpOnly: true }});\nLine 3, 4, 15, 16, 24, 25, 32: This is secure because the `secure` and `HttpOnly` flags are set to true.", "contexts": [{"lineNo": 53, "eventType": "sink", "messageKey": "jschk.SENSITIVE_COOKIE.FLAG.JS.defect.notset", "params": {}}]}} {"id": "23453b86ed31f63b41f788c4e15e4a4443764939287deed95e976eb3d252c3f8", "license": {"spdx": ["MIT"], "repo": "weirdindiankid/urban-refuge", "path": "server/index.js", "repo_head_hexsha": "526b61c7332ed2260e741c60b24fc27550db36e2", "stack_hexsha": "c62d0b7a221e0c4e3116a7bb000a415027ccbc6f", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Improper Cookie Flag Setting", "issueDescriptionEn": "Generally, web application uses cookies to send session information. However, the improper use of cookie flags may lead to vulnerabilities in session management such as MITM attacks or cookie stealing using XSS.\nIn Node.js, it is necessary to set security flags such as `secure` and `HttpOnly` to true for session management to enable cookie safety.", "issueLineNumber": 21, "entireCode": "var express = require('express');\nvar app = express();\nvar passport = require('passport');\nvar WindowsLiveStrategy = require('passport-windowslive');\nvar hbs = require('hbs');\nvar session = require('express-session');\nvar bodyParser = require('body-parser');\nvar cookieParser = require('cookie-parser');\nvar config = require('./config/config');\n\n/* routes */\nvar index = require('./routes/index');\nvar resources = require('./routes/resources');\nvar users = require('./routes/users');\nvar api = require('./routes/api');\n\n/* initialize express */\napp.use(bodyParser.json());\napp.use(bodyParser.urlencoded({ extended: true }));\napp.set('trust proxy', 1) // trust first proxy\napp.use(session({\n secret: 'shhhhhhhhh',\n resave: true,\n saveUninitialized: true\n}));\napp.use(cookieParser());\n\n/* Add headers */\napp.use(function (req, res, next) {\n // Website you wish to allow to connect\n res.setHeader('Access-Control-Allow-Origin', '*');\n // Request methods you wish to allow\n res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');\n // Request headers you wish to allow\n res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');\n // Set to true if you need the website to include cookies in the requests sent\n // to the API (e.g. in case you use sessions)\n res.setHeader('Access-Control-Allow-Credentials', true);\n // Pass to next layer of middleware\n next();\n});\n\n// Configure Passport to use Auth0\nvar strategy = new WindowsLiveStrategy({\n clientID: config.clientID,\n clientSecret: config.clientSecret,\n callbackURL: config.callbackURL\n }, function(accessToken, refreshToken, profile, done) {\n // accessToken is the token to call Auth0 API (not needed in the most cases)\n // extraParams.id_token has the JSON Web Token\n // profile has all the information from the user\n return done(null, profile);\n });\n\npassport.use(strategy);\n\n// This can be used to keep a smaller payload\npassport.serializeUser(function(user, done) {\n done(null, user);\n});\n\npassport.deserializeUser(function(user, done) {\n done(null, user);\n});\n\napp.use(passport.initialize());\napp.use(passport.session());\n\n\n/* initialize handlebars */\napp.set('view engine', 'hbs');\napp.set('views', __dirname+'/views');\nhbs.registerPartials(__dirname + '/views/partials');\nhbs.registerHelper('neq', function(lvalue, rvalue, options) {\n if (arguments.length < 3)\n throw new Error(\"Handlebars Helper equal needs 2 parameters\");\n if(lvalue==rvalue) {\n return options.inverse(this);\n } else {\n return options.fn(this);\n }\n});\n\n/* routes */\napp.use('/', index);\napp.use('/resources', resources);\napp.use('/users', users);\napp.use('/api', api);\n\napp.listen(config.port, function () {\n console.log('Urban Refuge is listening on port',config.port);\n});", "dangerousExampleEn": "1. //--cookie-session\n2. let session = cookieSession({\n3. httpOnly: false,\n4. secure: false,\n5. });\n6. \n7. \n8. //--express-session\n9. const express = require('express');\n10. const session = require('express-session');\n11. let app = express();\n12. app.use(session({\n13. cookie:\n14. {\n15. secure: false,\n16. httpOnly: false\n17. }\n18. }));\n19. \n20. \n21. //--cookies\n22. let cookies = new Cookies(req, res, { keys: keys });\n23. cookies.set('LastVisit', new Date().toISOString(), {\n24. httpOnly: false,\n25. secure: false\n26. });\n27. \n28. //--csurf\n29. const cookieParser = require('cookie-parser');\n30. const csrf = require('csurf');\n31. const express = require('express');\n32. let csrfProtection = csrf({ cookie: { secure: false, httpOnly: false }});\nLine 3, 4, 15, 16, 24, 25, 32: This is insecure because the `secure` and `HttpOnly` flags are set to false.", "safeExampleEn": "1. //--cookie-session\n2. let session = cookieSession({\n3. httpOnly: true,\n4. secure: true,\n5. });\n6. \n7. \n8. //--express-session\n9. const express = require('express');\n10. const session = require('express-session');\n11. let app = express();\n12. app.use(session({\n13. cookie:\n14. {\n15. secure: true,\n16. httpOnly: true\n17. }\n18. }));\n19. \n20. \n21. //--cookies\n22. let cookies = new Cookies(req, res, { keys: keys });\n23. cookies.set('LastVisit', new Date().toISOString(), {\n24. httpOnly: true,\n25. secure: true\n26. });\n27. \n28. //--csurf\n29. const cookieParser = require('cookie-parser');\n30. const csrf = require('csurf');\n31. const express = require('express');\n32. let csrfProtection = csrf({ cookie: { secure: true, httpOnly: true }});\nLine 3, 4, 15, 16, 24, 25, 32: This is secure because the `secure` and `HttpOnly` flags are set to true.", "contexts": [{"lineNo": 21, "eventType": "sink", "messageKey": "jschk.SENSITIVE_COOKIE.FLAG.JS.defect.notset", "params": {}}]}} {"id": "b0847c2193e2c473707570d6c852d36862956a0d213a4dd645a10ec52fc1890c", "license": {"spdx": ["MIT"], "repo": "jmthompson2015/xwing-miniatures-game", "path": "src/model/ShipFledAction.js", "repo_head_hexsha": "86174203c9d6c99617b8ceaebdc651a61c4f65a4", "stack_hexsha": "1193cf99dba9ba52dc93e9937b9395bf0e938273", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Leftover debug code", "issueDescriptionEn": "The Leftover debug code checker finds debug code that remains not removed.\nDebug code may contain parts that output sensitive information or allow control over the system. If the program is deployed with debug code remaining, attackers may bypass an authentication process or access restricted information.\nRemove all debug code before deploying the application.", "issueLineNumber": 29, "entireCode": "import InputValidator from \"../utility/InputValidator.js\";\n\nimport Action from \"./Action.js\";\nimport TargetLock from \"./TargetLock.js\";\n\nfunction ShipFledAction(environment, token, fromPosition)\n{\n InputValidator.validateNotNull(\"environment\", environment);\n InputValidator.validateNotNull(\"token\", token);\n InputValidator.validateNotNull(\"fromPosition\", fromPosition);\n\n this.environment = function()\n {\n return environment;\n };\n\n this.token = function()\n {\n return token;\n };\n\n this.fromPosition = function()\n {\n return fromPosition;\n };\n\n this.doIt = function()\n {\n LOGGER.trace(\"ShipFledAction.doIt() start\");\n\n const tokens = [];\n\n if (token.isParent())\n {\n tokens.push(token.tokenFore());\n tokens.push(token.tokenAft());\n }\n else\n {\n tokens.push(token);\n }\n\n tokens.forEach(function(token)\n {\n const store = environment.store();\n TargetLock.removeAllTargetLocks(store, token);\n\n // Return the damage cards.\n if (token.isParent())\n {\n environment.discardAllDamage(token.tokenFore().damages());\n environment.discardAllDamage(token.tokenFore().criticalDamages());\n environment.discardAllDamage(token.tokenAft().damages());\n environment.discardAllDamage(token.tokenAft().criticalDamages());\n }\n else\n {\n environment.discardAllDamage(token.damages());\n environment.discardAllDamage(token.criticalDamages());\n }\n\n if (token)\n {\n environment.removeTouching(token);\n environment.removeToken(token);\n }\n store.dispatch(Action.setUserMessage(\"Ship fled the battlefield: \" + token));\n });\n\n LOGGER.trace(\"ShipFledAction.doIt() end\");\n };\n}\n\nexport default ShipFledAction;", "dangerousExampleEn": "1. \nLine 3: A debug code is remaining.", "safeExampleEn": "1. \nLine 3: Remove the code used for debugging.", "contexts": [{"lineNo": 29, "eventType": "sink", "messageKey": "jschk.LEFTOVER_DEBUG_CODE.TOBE.JS.defect", "params": {}}]}} {"id": "c24db117c65bc0a9b3409ee93a80c6ec3b2301b4725a4fcff0d0d02d70dd7b5e", "license": {"spdx": ["0BSD"], "repo": "colohr/bxy", "path": "web/function/function.import.package.js", "repo_head_hexsha": "f072e5306f2ed7e0e9fe5df1568f5b10ff8f4b1e", "stack_hexsha": "fa51d5b3f81528e2391ff1de001fb348b6aa5aa3", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Leftover debug code", "issueDescriptionEn": "The Leftover debug code checker finds debug code that remains not removed.\nDebug code may contain parts that output sensitive information or allow control over the system. If the program is deployed with debug code remaining, attackers may bypass an authentication process or access restricted information.\nRemove all debug code before deploying the application.", "issueLineNumber": 29, "entireCode": "(function define(...x){const _=this.modules?this.modules:module,__=(m,...a)=>_.define?_.define('function.import.export',{value:m(...a)}):_.exports=m(...a);return _.has&&_.has('function.import.export')?_.get('function.import.export'):(([m],y,...z)=>__(m,...(y.concat(z))))(x.splice(0,1),(x=x.map(i=>Array.isArray(i)?i.map(f=>f()):i).reduce((l,i)=>(Array.isArray(i)?l[0].push(...i):l.push(i),l),[[]]))[0],...x.slice(1, x.length));})\n(function definition() {\n\tconst {dot,http,wait} = window.modules\n\t//exports\n\treturn import_package\n\n\t//scope actions\n\tfunction define_module(item){\n\t\tconst define = dot.get(item, 'mode.define')\n\t\tif(define && 'node_modules' in item) window.modules.set(item.name, Object.defineProperties(window.modules.get(item.name)||{}, item.node_modules.reduce(reduce, {})))\n\t\tif(item.defined !== true) item.defined = define === false || window.modules.has(item.name)\n\t\treturn item = null\n\t}\n\n\tfunction define_module_alias(item, dependency){ Object.defineProperties(window.modules, [{notation: item.name, variable: dependency.variable}].reduce(reduce, {})) }\n\n\tasync function import_package(...x){\n\t\tconst name = x.filter(window.modules.is.text)[0]\n\t\tlet item = get_module(name)\n\t\tif(item === null) item = await load_module(name)\n\t\tif(item === null) item = get_module(name)\n\t\treturn item !== null ? item:await http.assets(http.locator.unpack(name, ...x))\n\t}\n\n\tfunction get_module(name){ return window.modules.has(name) ? window.modules.get(name):null }\n\n\tasync function load_dependency(dependency){\n\t\ttry{ return await http.assets(dependency.locator).then(on_load).then(on_module) }\n\t\tcatch(error){ console.trace(error)}\n\t\treturn null\n\t\t//scope actions\n\t\tfunction on_load(){ return dependency.wait ? wait(...dependency.wait):true }\n\t\tfunction on_module(){ return dependency.notation&& window.modules.has(definition.notation) === false ?window.modules.set(dependency.notation, dot.get(window, dependency.variable)):dot.get(window, dependency.variable) }\n\t}\n\n\tasync function load_es_dependency(dependency){\n\t\ttry{\n\t\t\tif(dependency.notation && window.modules.has(dependency.notation)) return window.modules.get(dependency.notation)\n\t\t\treturn await import(dependency.locator).then(on_module)\n\t\t}\n\t\tcatch(error){ console.trace(error)}\n\t\treturn null\n\n\t\t//scope actions\n\t\tfunction on_module(definition){ return dependency.notation && window.modules.has(dependency.notation) === false ? window.modules.set(dependency.notation, definition):definition }\n\t}\n\n\tasync function load_module(name){\n\t\tconst internal = await window.modules.import.internal()\n\t\tlet item = internal.module(name)\n\t\tif(item){\n\t\t\tname = item.name\n\t\t\tif(item.defined !== true && dot.has(item,'mode.entry') && dot.get(item, 'mode.entry').loaded !== true){\n\t\t\t\tdot.get(item, 'mode.entry').loaded = await (dot.get(item, 'mode.entry').es ? load_es_dependency(dot.get(item, 'mode.entry')):load_dependency(dot.get(item, 'mode.entry'))) !== null\n\t\t\t}\n\t\t\tif(item.defined !== true && 'node_modules' in item){\n\t\t\t\tfor(const dependency of item.node_modules){\n\t\t\t\t\tif(dependency.loaded !== true) dependency.loaded = await (dependency.es ? load_es_dependency(dependency):load_dependency(dependency)) !== null\n\t\t\t\t\tif(dependency.alias) define_module_alias(item, dependency)\n\t\t\t\t}\n\t\t\t\tdefine_module(item)\n\t\t\t}\n\t\t\treturn (item = null, window.modules.get(name))\n\t\t}\n\t\treturn null\n\t}\n\n\tfunction reduce(){\n\t\tif(window.modules.has(arguments[1].notation)) return arguments[0]\n\t\treturn (arguments[0][arguments[1].notation] = eval(`({get(){ return window.modules.dot.get(window,\"${arguments[1].variable}\") }})`), arguments[0])\n\t}\n\n})\n\n", "dangerousExampleEn": "1. \nLine 3: A debug code is remaining.", "safeExampleEn": "1. \nLine 3: Remove the code used for debugging.", "contexts": [{"lineNo": 29, "eventType": "sink", "messageKey": "jschk.LEFTOVER_DEBUG_CODE.TOBE.JS.defect", "params": {}}]}} {"id": "73529706929301173860122c853554a51e9f176466abff8ad45a483a2a3bae41", "license": {"spdx": ["MIT"], "repo": "NoxHarmonium/moussaka-client", "path": "index.js", "repo_head_hexsha": "b82a662440aa3aa8b7435aed1e256f26a755b4c4", "stack_hexsha": "fd3e3212ae71e15935ea2277cc3d99da51e7f7b6", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Leftover debug code", "issueDescriptionEn": "The Leftover debug code checker finds debug code that remains not removed.\nDebug code may contain parts that output sensitive information or allow control over the system. If the program is deployed with debug code remaining, attackers may bypass an authentication process or access restricted information.\nRemove all debug code before deploying the application.", "issueLineNumber": 15, "entireCode": "// Main entry point\n(function (require, module) {\n 'use strict';\n\n // Load main module\n var logger = require('./libs/logger.js');\n var MoussakaClient = require('./libs/moussakaClient.js');\n\n // Expose types\n MoussakaClient.types = {};\n MoussakaClient.types.Color = require('./libs/types/color.js');\n MoussakaClient.types.Position = require('./libs/types/position.js');\n\n // Export\n logger.trace('MoussakaClient module loaded.');\n module.exports = MoussakaClient;\n\n})(require, module);", "dangerousExampleEn": "1. \nLine 3: A debug code is remaining.", "safeExampleEn": "1. \nLine 3: Remove the code used for debugging.", "contexts": [{"lineNo": 15, "eventType": "sink", "messageKey": "jschk.LEFTOVER_DEBUG_CODE.TOBE.JS.defect", "params": {}}]}} {"id": "97b7b9d872a3acf56d76baf0d351d6bf90cacf95014688c4be9f3fba2a3e1de6", "license": {"spdx": ["Apache-2.0"], "repo": "italia/daf-kafka-http-proxy", "path": "lib/topics.js", "repo_head_hexsha": "587a9fc45c7cfc70825e0f68c4b17b1f8c8ebf75", "stack_hexsha": "66803f78041a075a9f586cd64151691fa663bcfa", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Leftover debug code", "issueDescriptionEn": "The Leftover debug code checker finds debug code that remains not removed.\nDebug code may contain parts that output sensitive information or allow control over the system. If the program is deployed with debug code remaining, attackers may bypass an authentication process or access restricted information.\nRemove all debug code before deploying the application.", "issueLineNumber": 8, "entireCode": "var kafka = require('kafka-node'),\n config = require('../config'),\n logger = require('../logger.js').logger,\n topicMap = [],\n\n client = new kafka.Client(config.kafka.zkConnect, config.kafka.clientId.http),\n getClient = function () {\n logger.trace('returning found client');\n return client;\n },\n\n exists = function (client, topic, callback) {\n client.topicExists([topic], function (err, data) {\n topicMap[topic] = {};\n callback(err, data);\n });\n },\n\n refresh = function (client, topic, callback) {\n logger.trace({topic: topic}, 'refreshing the topic information');\n exists(client, topic, function (err) {\n if (err) return callback(err);\n\n logger.trace({topic: topic}, 'refreshing the metadata');\n client.refreshMetadata([topic], callback);\n });\n },\n\n partitions = function (client, topic, callback) {\n logger.trace({ topic : topic}, 'loading partitions for topic');\n refresh(client, topic, function (err) {\n if (err) return callback(err);\n\n logger.trace({ topic : topic}, 'loading the topic partitions from kafka');\n callback(err, client.topicPartitions[topic].length);\n });\n };\n\nmodule.exports = {\n exists: function (topic, callback) {\n if (!!client.topicPartitions[topic])\n return callback(undefined, true);\n return exists(getClient(), topic, callback);\n },\n refresh: function (topic, callback) {\n return refresh(getClient(), topic, callback);\n },\n partitions: function (topic, callback) {\n if (!!client.topicPartitions[topic])\n return callback(undefined, client.topicPartitions[topic].length);\n\n logger.trace('getting partitions');\n return partitions(getClient(), topic, callback);\n }\n};", "dangerousExampleEn": "1. \nLine 3: A debug code is remaining.", "safeExampleEn": "1. \nLine 3: Remove the code used for debugging.", "contexts": [{"lineNo": 8, "eventType": "sink", "messageKey": "jschk.LEFTOVER_DEBUG_CODE.TOBE.JS.defect", "params": {}}]}} {"id": "18cbeaf72d77d5aed555bda47144ac63dffa6550693d8f3ca7222028a34dc53e", "license": {"spdx": ["MIT"], "repo": "fuseio/DAIPoints", "path": "oracle/src/services/agenda.js", "repo_head_hexsha": "d1f5462c347c3f32094c2a8bef18cef888b6cae8", "stack_hexsha": "6939a7805545b0e806fb3d7bc0dbdc89bf7a4336", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Leftover debug code", "issueDescriptionEn": "The Leftover debug code checker finds debug code that remains not removed.\nDebug code may contain parts that output sensitive information or allow control over the system. If the program is deployed with debug code remaining, attackers may bypass an authentication process or access restricted information.\nRemove all debug code before deploying the application.", "issueLineNumber": 38, "entireCode": "require('dotenv').config()\nconst Agenda = require('agenda')\nconst moment = require('moment')\nconst logger = require('./logger')\nconst cache = require('./cache')\nconst { selectWinner, models } = require('../utils/utils')\nconst { Draw, Snapshot } = models\nconst { reward } = require('../utils/tx')\nconst { getCommunityMembersWithBalances, getCommunityMembers } = require('../utils/graph')\n\nconst {\n MONGO_URI,\n PERIODIC_INTERVAL_SECONDS\n} = process.env\n\nconst agenda = new Agenda({ db: { address: MONGO_URI, options: { useUnifiedTopology: true, autoReconnect: false, reconnectTries: 0, reconnectInterval: 0 } } })\n\nconst drawTask = async () => {\n const draw = await Draw.findOne({ state: 'OPEN' })\n if (draw) {\n logger.info(`there's an open draw: ${draw}, ending at: ${draw.endTime}`)\n const now = moment()\n if (now.isSameOrAfter(draw.endTime)) {\n logger.info('need to close draw and open a new one')\n const winner = await selectWinner(draw.id)\n const { rewardAmount } = await reward(winner)\n await Draw.close(draw.id, winner, rewardAmount)\n await Draw.create()\n }\n } else {\n logger.info('there\\'s no open draw - creating one...')\n await Draw.create()\n }\n}\n\nconst snapshotTask = async () => {\n const communityMembersWithBalances = await getCommunityMembersWithBalances()\n logger.trace({ communityMembersWithBalances })\n const draw = await Draw.findOne({ state: 'OPEN' })\n if (draw) {\n logger.info(`there's an open draw: ${draw}, ending at: ${draw.endTime}`)\n await Snapshot.create(draw.id, communityMembersWithBalances)\n } else {\n logger.warn('there\\'s no open draw - creating one...')\n }\n}\n\nconst communityMembersTask = async () => {\n const communityMembers = await getCommunityMembers()\n cache.set('communityMembers', communityMembers)\n}\n\nasync function start () {\n logger.info('Starting Agenda job scheduling')\n\n agenda.on('start', job => logger.info(`Job ${job.attrs.name} starting. id: ${job.attrs._id}`))\n agenda.on('complete', job => logger.info(`Job ${job.attrs.name} finished. id: ${job.attrs._id}`))\n agenda.on('success', job => logger.info(`Job ${job.attrs.name} succeeded. id: ${job.attrs._id}`))\n agenda.on('fail', (error, job) => logger.error(`Job ${job.attrs.name} failed. id: ${job.attrs._id}. ${error}`))\n\n await agenda.start()\n\n agenda.define('draw-state', async (job) => {\n logger.info('draw-state')\n await drawTask()\n })\n\n agenda.define('snapshot', async (job) => {\n logger.info('snapshot')\n await snapshotTask()\n })\n\n agenda.define('community-members', async (job) => {\n logger.info('community-members')\n await communityMembersTask()\n })\n\n await agenda.every(`${PERIODIC_INTERVAL_SECONDS} seconds`, 'draw-state')\n await agenda.every('0 0 * * *', 'snapshot')\n await agenda.every('1 hour', 'community-members')\n\n logger.info('Agenda job scheduling is successfully defined')\n}\n\nmodule.exports = {\n start,\n agenda,\n snapshotTask\n}", "dangerousExampleEn": "1. \nLine 3: A debug code is remaining.", "safeExampleEn": "1. \nLine 3: Remove the code used for debugging.", "contexts": [{"lineNo": 38, "eventType": "sink", "messageKey": "jschk.LEFTOVER_DEBUG_CODE.TOBE.JS.defect", "params": {}}]}} {"id": "38b0caa5235f2df4e365bd4873b951595d6c2ca224a0967e53064a2d9ad9f9b6", "license": {"spdx": ["MIT"], "repo": "fakecoinbase/fioprotocolslashfio-registrations", "path": "server/process-webhooks.js", "repo_head_hexsha": "19c446307e9b6328d529d33588883bfae8ccad3e", "stack_hexsha": "68a10781eadd62c16572f038aa424b0d7d708493", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Leftover debug code", "issueDescriptionEn": "The Leftover debug code checker finds debug code that remains not removed.\nDebug code may contain parts that output sensitive information or allow control over the system. If the program is deployed with debug code remaining, attackers may bypass an authentication process or access restricted information.\nRemove all debug code before deploying the application.", "issueLineNumber": 16, "entireCode": "const fetch = require('isomorphic-fetch')\nconst AbortController = require('abort-controller')\n\nconst crypto = require('crypto')\nconst {createHmac} = crypto\nconst {checkDecrypt} = require('./encryption-check')\n\nconst db = require('./db/models');\nconst {Sequelize, sequelize} = db\nconst {Op} = Sequelize\n\nlet debug = require('debug')('fio:process-webhook')\nconst trace = require('./trace-filter')(() => debug, extend => debug = extend)\n\nasync function all() {\n return trace({postWebhookEvents})()\n}\n\n/**\n*/\nasync function postWebhookEvents() {\n function post(eventsByEndpoint, alias) {\n // these can run in parallel\n const eps = Object.keys(eventsByEndpoint).map(function (endpoint) {\n return eventsByEndpoint[endpoint].map(function (event) {\n // synchronous event delivery\n return postWebhookEvent(endpoint, event, alias)\n })\n })\n\n return Promise.all(eps)\n }\n\n const p = []\n\n const events = await webhookQuery(\n db.AccountPayEvent, apiCols.account_pay_event,\n db.AccountPay, apiCols.account_pay,\n 'AccountPay'\n )\n\n const eventsByEndpoint = groupBy(events, el =>\n el.AccountPay.Account.Wallet.webhook_endpoint)\n\n p.push( post(eventsByEndpoint, 'AccountPay') )\n\n const trxEvents = await webhookQuery(\n db.BlockchainTrxEvent, apiCols.blockchain_trx_event,\n db.BlockchainTrx, apiCols.blockchain_trx,\n 'BlockchainTrx'\n )\n const trxEventsByEndpoint = groupBy(trxEvents, el =>\n el.BlockchainTrx.Account.Wallet.webhook_endpoint)\n\n p.push( post(trxEventsByEndpoint, 'BlockchainTrx') )\n\n return Promise.all(p)\n}\n\n/** One tupple: [endpoint, decrypted webhook shared secret] */\nconst webhookSecretCache = ['', '']\n\nasync function postWebhookEvent(endpoint, event, alias) {\n const {webhook_shared_secret} = event[alias].Account.Wallet\n const {webhook_events} = event[alias].Account.Wallet\n\n let webhookSecret;\n if(webhookSecretCache[0] === event.wallet_referral_code) {\n webhookSecret = webhookSecretCache[1]\n } else {\n webhookSecret = checkDecrypt(\n process.env.DATABASE_ENCRYPT_SECRET,\n webhook_shared_secret\n ).toString()\n webhookSecretCache[0] = event.wallet_referral_code\n webhookSecretCache[1] = webhookSecret\n }\n\n const type = alias === 'AccountPay' ? 'payment' : 'registration'\n const status = alias === 'AccountPay' ? event.pay_status : event.trx_status\n const data = alias === 'AccountPay' ?\n formatPayEvent(event) :\n formatTrxEvent(event)\n\n const attempt = event.WebhookEvent ? event.WebhookEvent.attempt + 1 : 1\n const POST = {type, status, attempt, data}\n const body = JSON.stringify(POST)\n\n const signature = createHmac('sha256', webhookSecret)\n .update(body).digest().toString('hex')\n\n const headers = {\n ['Content-Type']: 'application/json',\n ['X-CC-Webhook-Signature']: signature\n }\n\n const webhookEvent = {}\n webhookEvent.attempt = attempt\n\n const controller = new AbortController();\n const request = { method: 'POST', body, headers, signal: controller.signal }\n let response, timeout\n\n try {\n // fetch can hang for over a minute, wrapping it in a Promise allows an early timeout\n response = await new Promise(async function(resolve, reject) {\n let didTimeout\n timeout = setTimeout(function() {\n controller.abort()\n didTimeout = true\n reject(new Error('timeout'));\n }, process.env.WEBHOOK_TIMOUT || 3000);\n\n const res = await fetch(endpoint, request)\n clearTimeout(timeout)\n\n if(didTimeout) {\n reject(res)\n } else {\n resolve(res)\n }\n })\n } catch (err) {\n webhookEvent.message = err.message\n } finally {\n clearTimeout(timeout)\n\n webhookEvent.response_status = response ? response.status : null\n if(!webhookEvent.message) {\n webhookEvent.message = response ? (await response.text()) : null\n }\n webhookEvent.next_attempt = response && response.ok ? null : new Date(\n // Date.now() instead of last next_attempt is used incase this server has down-time\n Date.now() + (fibonacci(webhookEvent.attempt) * 60 * 1000)\n )\n\n if(debug.enabled) {\n debug('POST', JSON.stringify({endpoint, event: webhookEvent, POST}))\n }\n\n if(webhookEvent.message) {\n webhookEvent.message = webhookEvent.message.substring(0, 200)\n }\n\n if(event.WebhookEvent) {\n await db.WebhookEvent.update(\n webhookEvent,\n {where: {id: event.WebhookEvent.id}}\n )\n } else {\n await sequelize.transaction(async transaction => {\n const tr = {transaction}\n\n const wh = await db.WebhookEvent.create( webhookEvent, tr );\n event.setWebhookEvent(wh)\n await event.save(tr)\n })\n }\n }\n\n return webhookEvent\n}\n\n/**\n Retry wait-times\n*/\nfunction fibonacci(num) {\n if (num <= 1) return 1;\n return fibonacci(num - 1) + fibonacci(num - 2);\n}\n// s = 0; for(i = 1; i <= 18; i++) {console.log(i, fibonacci(i), s += fibonacci(i))}; s/60/24\n\nfunction groupBy(arr, keyFn) {\n const ret = {}\n arr.forEach(el => {\n const key = keyFn(el)\n let value = ret[key]\n if(value === undefined) {\n value = ret[key] = []\n }\n value.push(el)\n })\n return ret\n}\n\n// columns with immutable data, they change by adding new rows\nconst apiCols = {\n wallet: ['referral_code'],\n account: [ 'domain', 'address', 'created', 'owner_key' ],\n account_pay: [ 'pay_source', 'buy_price', ['metadata', 'pay_metadata'], 'extern_id' ],\n account_pay_event: [\n 'extern_status', 'extern_time', 'confirmed_total', 'pending_total',\n 'pay_status', 'pay_status_notes',\n 'created', 'event_id', 'metadata', 'created_by'\n ],\n blockchain_trx: [\n 'type', 'trx_id', 'expiration', 'block_num', 'block_time'\n ],\n blockchain_trx_event: [\n 'created', 'trx_status', 'trx_status_notes', 'created_by'\n ]\n}\n\nfunction webhookQuery (model, cols, eventModel, eventCols, alias) {\n return model.findAll({ // AccountPayEvent or BlockchainTrxEvent\n attributes: [ 'id', ...cols ],\n include: [\n {\n model: db.WebhookEvent,\n required: false,\n },\n {model: eventModel, required: true, // AccountPay or BlockchainTrx\n attributes: [ 'id', ...eventCols ],\n include: {model: db.Account, required: true,\n attributes: [ ...apiCols.account ],\n include: {\n model: db.Wallet, required: true, attributes: [\n 'id', 'webhook_endpoint', 'webhook_shared_secret',\n ...apiCols.wallet,\n ]\n }\n }\n }\n ],\n where: [\n {created: {\n [Op.gte]: Sequelize.col(`\"${alias}->Account->Wallet\".webhook_enabled`),\n }},\n {created: {\n [Op.gte]: Date.now() - (8 * 24 * 60 * 60 * 1000) // 8 days\n }},\n sequelize.literal(\n `(response_status IS NULL OR (response_status < 200 OR response_status >= 300)) ` +\n `AND (next_attempt IS NULL OR now() >= next_attempt) ` +\n `AND (attempt IS NULL OR attempt <= 18) ` + // 18 takes about 7 days\n (alias === 'AccountPay' ?\n `AND pay_status = ANY(webhook_pay_events) `:\n `AND trx_status = ANY(webhook_trx_events) `)\n )\n ],\n order: sequelize.literal(`webhook_endpoint, created`)\n })\n}\n\nfunction formatPayEvent(payEvent) {\n const event = {}\n setCols(event, 'wallet_', payEvent.AccountPay.Account.Wallet, apiCols.wallet)\n setCols(event, 'account_', payEvent.AccountPay.Account, apiCols.account)\n setCols(event, 'pay_', payEvent.AccountPay, apiCols.account_pay)\n setCols(event, 'pay_', payEvent, apiCols.account_pay_event)\n return event\n}\n\nfunction formatTrxEvent(payEvent) {\n const event = {}\n setCols(event, 'wallet_', payEvent.BlockchainTrx.Account.Wallet, apiCols.wallet)\n setCols(event, 'account_', payEvent.BlockchainTrx.Account, apiCols.account)\n setCols(event, 'trx_', payEvent.BlockchainTrx, apiCols.blockchain_trx)\n setCols(event, 'trx_', payEvent, apiCols.blockchain_trx_event)\n return event\n}\n\nfunction setCols(event, prefix, obj, cols) {\n cols.forEach(col => {\n if(Array.isArray(col)) {\n col = col[1] // alias\n }\n if(col.startsWith(prefix)) {\n event[col] = obj[col]\n return\n }\n if(event[prefix + col]) {\n throw new Error('duplicate: ' + col)\n }\n event[prefix + col] = obj[col]\n })\n}\n\nmodule.exports = {\n all: trace({all})\n}", "dangerousExampleEn": "1. \nLine 3: A debug code is remaining.", "safeExampleEn": "1. \nLine 3: Remove the code used for debugging.", "contexts": [{"lineNo": 16, "eventType": "sink", "messageKey": "jschk.LEFTOVER_DEBUG_CODE.TOBE.JS.defect", "params": {}}]}} {"id": "1614878014808486d05eb172117e0acade8317ea53d4343612150290bdf1a878", "license": {"spdx": ["MIT"], "repo": "iomeone/JsModule", "path": "bin/debug/nsis-test.js", "repo_head_hexsha": "9b864d143e819387188809f37f54a78a0bf778dc", "stack_hexsha": "d7f14c1dea8fa5ee450f2eabb36744ac2cbc9024", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Leftover debug code", "issueDescriptionEn": "The Leftover debug code checker finds debug code that remains not removed.\nDebug code may contain parts that output sensitive information or allow control over the system. If the program is deployed with debug code remaining, attackers may bypass an authentication process or access restricted information.\nRemove all debug code before deploying the application.", "issueLineNumber": 33, "entireCode": "//****************************************\n\nvar console = require('console');\nvar curl = require('curl');\nvar file = require('file');\nvar json = require('json');\nvar jstring = require('string');\nvar socket = require('socket');\nvar compress = require('compress');\nvar damatu = require('damatu');\nvar common = require('common');\n\n\n//****************************************\n// nsis module\n//****************************************\n//nsis.exe path\nvar path_nsis = \"D:\\\\NSIS\\\\makensis.exe\";\n//.nsi file path\nvar path_nsi = \"D:\\\\test.nsi\";\n\n//common.cmdpip(\"ping www.baidu.com -t\", \"\");\nvar pips = common.pips();\npips.callback(callback_pips);\npips.start(path_nsis, path_nsi);\nconsole.cin();\npath_nsi = \"D:\\\\test2.nsi\";\npips.start(path_nsis, path_nsi);\n//pips.start(\"ping www.baidu.com -t\", \"\");\n\nfunction callback_pips(str)\n{\n\tfile.trace(\"[pips callback]: \", str);\n}\n\n//console.cin();\n\t", "dangerousExampleEn": "1. \nLine 3: A debug code is remaining.", "safeExampleEn": "1. \nLine 3: Remove the code used for debugging.", "contexts": [{"lineNo": 33, "eventType": "sink", "messageKey": "jschk.LEFTOVER_DEBUG_CODE.TOBE.JS.defect", "params": {}}]}} {"id": "a51020e0896660142a51a6eccd72a9878bcc357f199cc31dab029b3d2d08b9ac", "license": {"spdx": ["MIT"], "repo": "societa-astronomica-g-v-schiaparelli/remote_REST_dome_controller", "path": "board/dome/data/dashboard.js", "repo_head_hexsha": "35a9df776e61e9c5d26516dbd4433917d6b81571", "stack_hexsha": "7889c8eb8637d41754043cb6ac8d0864a1b1d48f", "match": "repo_path"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Leftover debug code", "issueDescriptionEn": "The Leftover debug code checker finds debug code that remains not removed.\nDebug code may contain parts that output sensitive information or allow control over the system. If the program is deployed with debug code remaining, attackers may bypass an authentication process or access restricted information.\nRemove all debug code before deploying the application.", "issueLineNumber": 86, "entireCode": "/*\nRemote REST dome controller\nhttps://github.com/societa-astronomica-g-v-schiaparelli/remote_REST_dome_controller\n\nLicensed under the MIT License .\nSPDX-License-Identifier: MIT\nCopyright (c) 2020-2022, Società Astronomica G. V. Schiaparelli .\nAuthors: <>\n <>\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*/\n\nconst DEBUG = false;\nconst DEBUG_IP = \"\";\n\nconst UPDATE_TIME = 1000;\nvar getStatus_interval;\n\nfunction start() {\n setTimeout(getStatus, 0);\n getStatus_interval = setInterval(getStatus, UPDATE_TIME);\n}\n\nfunction getStatus() {\n const request = new Request(`${DEBUG ? `http://${DEBUG_IP}` : \"\"}/api?json=${encodeURIComponent(JSON.stringify({ \"cmd\": \"status\" }))}`);\n fetchTimeout(request)\n .then(rsp => {\n // update main buttons\n document.getElementById(\"current-status-box\").style.opacity = 1;\n document.getElementById(\"current-status-man\").style.display = !rsp[\"optoin\"][\"auto\"] ? \"\" : \"none\";\n document.getElementById(\"current-status\").innerHTML = `Azimuth: ${rsp[\"dome-azimuth\"]}°${rsp[\"movement-status\"] ? `, moving to ${rsp[\"target-azimuth\"]}°` : \"\"}`;\n const disable_motion_buttons = !rsp[\"optoin\"][\"auto\"];\n document.getElementById(\"az-target\").disabled = disable_motion_buttons;\n document.getElementById(\"slew-to-az-button\").disabled = disable_motion_buttons;\n document.getElementById(\"slew-to-az-button\").className = rsp[\"movement-status\"] ? \"orange\" : \"gray\";\n document.getElementById(\"park-button\").disabled = disable_motion_buttons;\n document.getElementById(\"abort-button\").disabled = disable_motion_buttons;\n // update other buttons\n document.getElementById(\"ignite-switchboard-button\").disabled = rsp[\"optoin\"][\"switchboard-status\"] || disable_motion_buttons;\n document.getElementById(\"find-zero-button\").disabled = disable_motion_buttons;\n document.getElementById(\"restart-button\").disabled = false;\n document.getElementById(\"force-restart-button\").disabled = false;\n document.getElementById(\"turn-off-button\").disabled = disable_motion_buttons;\n document.getElementById(\"reset-EEPROM-button\").disabled = false;\n document.getElementById(\"webserial\").disabled = false;\n document.getElementById(\"infoButton\").disabled = false;\n // update informations\n document.getElementById(\"firmware-version\").innerHTML = rsp[\"firmware-version\"];\n document.getElementById(\"uptime\").innerHTML = rsp[\"uptime\"];\n document.getElementById(\"dome-azimuth\").innerHTML = rsp[\"dome-azimuth\"];\n document.getElementById(\"target-azimuth\").innerHTML = rsp[\"target-azimuth\"];\n document.getElementById(\"movement-status\").innerHTML = rsp[\"movement-status\"];\n document.getElementById(\"in-park\").innerHTML = rsp[\"in-park\"];\n document.getElementById(\"finding-park\").innerHTML = rsp[\"finding-park\"];\n document.getElementById(\"finding-zero\").innerHTML = rsp[\"finding-zero\"];\n document.getElementById(\"cw-motor\").innerHTML = rsp[\"relay\"][\"cw-motor\"];\n document.getElementById(\"ccw-motor\").innerHTML = rsp[\"relay\"][\"ccw-motor\"];\n document.getElementById(\"switchboard\").innerHTML = rsp[\"relay\"][\"switchboard\"];\n document.getElementById(\"auto\").innerHTML = rsp[\"optoin\"][\"auto\"];\n document.getElementById(\"switchboard-status\").innerHTML = rsp[\"optoin\"][\"switchboard-status\"];\n document.getElementById(\"ac-presence\").innerHTML = rsp[\"optoin\"][\"ac-presence\"];\n document.getElementById(\"manual-cw-button\").innerHTML = rsp[\"optoin\"][\"manual-cw-button\"];\n document.getElementById(\"manual-ccw-button\").innerHTML = rsp[\"optoin\"][\"manual-ccw-button\"];\n document.getElementById(\"manual-ignition\").innerHTML = rsp[\"optoin\"][\"manual-ignition\"];\n document.getElementById(\"hostname\").innerHTML = rsp[\"wifi\"][\"hostname\"];\n document.getElementById(\"mac-address\").innerHTML = rsp[\"wifi\"][\"mac-address\"];\n })\n .catch(error => {\n console.trace(`An error has occured: ${error.message}`);\n // update page with default\n // disable main buttons\n document.getElementById(\"current-status-box\").style.opacity = 0.4;\n document.getElementById(\"current-status-man\").style.display = \"none\";\n document.getElementById(\"current-status\").innerHTML = \"State not available\";\n document.getElementById(\"az-target\").disabled = true;\n document.getElementById(\"slew-to-az-button\").disabled = true;\n document.getElementById(\"slew-to-az-button\").className = \"gray\";\n document.getElementById(\"park-button\").disabled = true;\n document.getElementById(\"abort-button\").disabled = true;\n // disable other buttons\n document.getElementById(\"ignite-switchboard-button\").disabled = true;\n document.getElementById(\"find-zero-button\").disabled = true;\n document.getElementById(\"restart-button\").disabled = true;\n document.getElementById(\"force-restart-button\").disabled = true;\n document.getElementById(\"turn-off-button\").disabled = true;\n document.getElementById(\"reset-EEPROM-button\").disabled = true;\n document.getElementById(\"webserial\").disabled = true;\n document.getElementById(\"infoButton\").disabled = true;\n // default info\n document.getElementById(\"firmware-version\").innerHTML = \"ND\";\n document.getElementById(\"uptime\").innerHTML = \"ND\";\n document.getElementById(\"dome-azimuth\").innerHTML = \"ND\";\n document.getElementById(\"target-azimuth\").innerHTML = \"ND\";\n document.getElementById(\"movement-status\").innerHTML = \"ND\";\n document.getElementById(\"in-park\").innerHTML = \"ND\";\n document.getElementById(\"finding-park\").innerHTML = \"ND\";\n document.getElementById(\"finding-zero\").innerHTML = \"ND\";\n document.getElementById(\"cw-motor\").innerHTML = \"ND\";\n document.getElementById(\"ccw-motor\").innerHTML = \"ND\";\n document.getElementById(\"switchboard\").innerHTML = \"ND\";\n document.getElementById(\"auto\").innerHTML = \"ND\";\n document.getElementById(\"switchboard-status\").innerHTML = \"ND\";\n document.getElementById(\"ac-presence\").innerHTML = \"ND\";\n document.getElementById(\"manual-cw-button\").innerHTML = \"ND\";\n document.getElementById(\"manual-ccw-button\").innerHTML = \"ND\";\n document.getElementById(\"manual-ignition\").innerHTML = \"ND\";\n document.getElementById(\"hostname\").innerHTML = \"ND\";\n document.getElementById(\"mac-address\").innerHTML = \"ND\";\n });\n}\n\nfunction command(command) {\n // setup request\n const moving_command = command == \"slew-to-az\";\n let json = { \"cmd\": command }\n if (moving_command) {\n const az = document.getElementById(\"az-target\").value;\n document.getElementById(\"az-target\").value = \"\";\n if (!az || az < 0 || az > 360) {\n alert(\"Error: invalid azimuth.\");\n return;\n }\n clearInterval(getStatus_interval);\n json[\"az-target\"] = az;\n }\n const button = `${command}-button`;\n document.getElementById(button).className = \"orange\";\n // make request\n const request = new Request(`${DEBUG ? `http://${DEBUG_IP}` : \"\"}/api?json=${encodeURIComponent(JSON.stringify(json))}`);\n fetchTimeout(request)\n .then(rsp => {\n if (rsp != \"done\") throw new Error(rsp);\n if (!moving_command) document.getElementById(button).className = \"green\";\n setTimeout(moving_command ? start : () => { document.getElementById(button).className = \"gray\"; }, 2000);\n })\n .catch(error => {\n console.trace(`An error has occured: ${error.message}`);\n document.getElementById(button).className = \"red\";\n setTimeout(moving_command ? start : () => { document.getElementById(button).className = \"gray\"; }, 2000);\n alert(`Request \"${command}\" failed:\\n\\n${error.message}`);\n });\n}\n\nfunction toggleInfo() {\n if (document.getElementById(\"infoBox\").style.display == \"none\") {\n document.getElementById(\"infoBox\").style.display = \"\";\n document.getElementById(\"infoButton\").value = \"Less informations\";\n } else {\n document.getElementById(\"infoBox\").style.display = \"none\";\n document.getElementById(\"infoButton\").value = \"More informations\";\n }\n}\n\nasync function fetchTimeout(url, ms = 3500, { signal, ...options } = {}) {\n const controller = new AbortController();\n const promise = fetch(url, { signal: controller.signal, ...options });\n if (signal) signal.addEventListener(\"abort\", () => controller.abort());\n const timeout = setTimeout(() => controller.abort(), ms);\n const response = await promise.finally(() => clearTimeout(timeout));\n if (!response.ok) throw new Error(`${response.status}, ${response.statusText}`);\n const json = await response.json();\n return json[\"rsp\"];\n}", "dangerousExampleEn": "1. \nLine 3: A debug code is remaining.", "safeExampleEn": "1. \nLine 3: Remove the code used for debugging.", "contexts": [{"lineNo": 86, "eventType": "sink", "messageKey": "jschk.LEFTOVER_DEBUG_CODE.TOBE.JS.defect", "params": {}}]}} {"id": "031d0e3c7f62edc4a56bf3fdd324349f2a10eb01d7082252db8f503e9f3ed1e8", "license": {"spdx": ["MIT"], "repo": "thenodejsboilerplate/joyer", "path": "src/libs/redis.js", "repo_head_hexsha": "2c189e99f2188ed2d4d80ed0ad40ed9d0c4e257a", "stack_hexsha": "f252183cd2258a74a98b6b2b57eaa780a55ec0ea", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Leftover debug code", "issueDescriptionEn": "The Leftover debug code checker finds debug code that remains not removed.\nDebug code may contain parts that output sensitive information or allow control over the system. If the program is deployed with debug code remaining, attackers may bypass an authentication process or access restricted information.\nRemove all debug code before deploying the application.", "issueLineNumber": 21, "entireCode": "//it's the underground for ./cache.js, which wrap the redis function\n\"use strict\";\nvar config = require('../config/get-config');\nvar Redis = require('ioredis');\nvar logger = require('./logger')\nconst env = process.env.NODE_ENV || 'test'\n\nvar client;\nclient = new Redis({\n\t port: config.db[client].redis.port,\n\t host: config.db[client].redis.test.host,\n\t db: config.db[client].redis.db,\n\t password: config.db[client].redis.password\n});\n\nclient.on('ready',function(err) {\n\tif(err){\n\t logger.error('connect to redis error for ready , check your redis config',errr);\t\t\n\t}\n\n logger.trace(\"Redis is ready\");\n// //logger.trace('Entering cheese testing');\n// logger.debug('Got cheese.');\n// logger.info('Cheese is Gouda.');\n// logger.warn('Cheese is quite smelly.');\n// logger.error('Cheese is too ripe!');\n// logger.fatal('Cheese was breeding ground for listeria.');\n});\n\nclient.on(\"connect\", runSample);\n//without expiration version:\n// function runSample() {\n// // Set a value\n// client.set(\"string key\", \"Hello World\", function (err, reply) {\n// console.log(reply.toString());\n// });\n// // Get a value\n// client.get(\"string key\", function (err, reply) {\n// console.log(reply.toString());\n// });\n// }\nfunction runSample() {\n // Set a value with an expiration\n client.set('string key', 'Hello World', Redis.print);\n // Expire in 3 seconds\n client.expire('string key', 3);\n \n // This timer is only to demo the TTL\n // Runs every second until the timeout\n // occurs on the value\n var myTimer = setInterval(function() {\n client.get('string key', function (err, reply) {\n if(reply) {\n console.log('I live: ' + reply.toString());\n } else {\n clearTimeout(myTimer);\n console.log('I expired');\n client.quit();\n }\n });\n }, 1000);\n}\n\nclient.on('error', function (err) {\n if (err) {\n logger.error('connect to redis error, check your redis config', err);\n process.exit(1);\n }\n});\n\n\n\nexports = module.exports = client;", "dangerousExampleEn": "1. \nLine 3: A debug code is remaining.", "safeExampleEn": "1. \nLine 3: Remove the code used for debugging.", "contexts": [{"lineNo": 21, "eventType": "sink", "messageKey": "jschk.LEFTOVER_DEBUG_CODE.TOBE.JS.defect", "params": {}}]}} {"id": "787b262b9f7e1624171510b589af78d32fb466557c57aa8d261e4ac42aace765", "license": {"spdx": ["MIT"], "repo": "sebastienvercammen/console-remote", "path": "tests.js", "repo_head_hexsha": "d015a903d3755d61741f680b821dc34a44d2e08d", "stack_hexsha": "6d8bb3ac4337b7589b8a50ef87be2e9a9b60cdc6", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Leftover debug code", "issueDescriptionEn": "The Leftover debug code checker finds debug code that remains not removed.\nDebug code may contain parts that output sensitive information or allow control over the system. If the program is deployed with debug code remaining, attackers may bypass an authentication process or access restricted information.\nRemove all debug code before deploying the application.", "issueLineNumber": 151, "entireCode": "// Console.Re API Tests\n\nconst testing = require('testing'),\n configs = require('./config'), // edit ./config.js and change console.re channel name\n disconnect = true;\n\nif (process.env.CHANNEL) process.env.SERVER_CHANNEL = process.env.CHANNEL;\nif (process.env.SERVER_CHANNEL === 'YOUR-CHANNEL-NAME') process.env.SERVER_CHANNEL = 'NodeTest';\n\nconst cl = require('./lib/connector.node.js').connect(process.env.SERVER_DOMAIN, process.env.SERVER_PORT, process.env.SERVER_CHANNEL, disconnect);\n\nconst string = 'Test',\n object = {\n key1: 1,\n key2: 2\n },\n array = [1, 2, 3, 4, 5],\n number = 43,\n bbcodes = [\n '[noparse][i]Italic[/i][/noparse]',\n '[noparse][b]Bold[/b][/noparse]',\n '[noparse][u]Underline[/u][/noparse]',\n '[noparse][]red|green|blue|yellow|orange|lime|white|black[/][/noparse]',\n '[noparse][size=]1-20[/size][/noparse]'\n ];\n\nfunction testConsoleClear(callback) {\n testing.assert(\n console.re.clear(),\n 'testConsoleClear',\n callback\n );\n testing.success(\"console.re.clear(); passed\", callback);\n}\n\nfunction testConsoleTime(callback) {\n testing.assert(\n console.re.time('run timer'),\n 'testConsoleTime',\n callback\n );\n testing.success(\"console.re.time('run timer'); passed\", callback);\n}\n\nfunction testConsoleLog(callback) {\n testing.assert(\n console.re.log('This is a %s', string),\n 'testConsoleLog string',\n callback\n );\n testing.success(\"console.re.log('This is a %s', string); passed\");\n\n testing.assert(\n console.re.log('This is an %s', object),\n 'testConsoleLog object',\n callback\n );\n testing.success(\"console.re.log('This is an %s', object); passed\");\n\n testing.assert(\n console.re.log('This is an %s', array),\n 'testConsoleLog array',\n callback\n );\n testing.success(\"console.re.log('This is an %s', array); passed\");\n\n testing.assert(\n console.re.log('This is a number %d', number),\n 'testConsoleLog number',\n callback\n );\n testing.success(\"console.re.log('This is a number %d', number); passed\");\n\n testing.assert(\n console.re.log('simple log output of [i]process.env[/i] %s', process.env),\n 'testConsoleLog process.env',\n callback\n );\n testing.success(\"console.re.log('simple log output of [i]process.env[/i] %s', process.env); passed\", callback);\n}\n\nfunction testConsoleInfo(callback) {\n testing.assert(\n console.re.info('using [[i]bbcodes[/i]] %s output can has in styles: [i]Italic[/i] [b]Bold[/b] [u]Underline[/u] and colors: [red]%s[/red] [green]%s[/green] [blue]%s[/blue] [yellow]%s[/yellow] [orange]%s[/orange] [lime]%s[/lime] [white]%s[/white] [black]%s[/black]', bbcodes, 'red', 'green', 'blue', 'yellow', 'orange', 'lime', 'white', 'black'),\n 'testConsoleInfo',\n callback\n );\n testing.success(\"console.re.info('using [[i]bbcodes[/i]] %s output can has styles: [i]Italic[/i] [b]Bold[/b] [u]Underline[/u] and colors: [red]%s[/red] [green]%s[/green] [blue]%s[/blue] [yellow]%s[/yellow] [orange]%s[/orange] [lime]%s[/lime] [white]%s[/white] [black]%s[/black]', bbcodes, 'red', 'green', 'blue', 'yellow', 'orange', 'lime', 'white', 'black'); passed\", callback);\n}\n\nfunction testConsoleCount(callback) {\n testing.assert(\n console.re.count('counter one %d'),\n 'testConsoleCount',\n callback\n );\n testing.success(\"console.re.count('counter one %d'); passed\", callback);\n}\n\nfunction testConsoleDebug(callback) {\n testing.assert(\n console.re.debug(\"debug output for %s and %s\", {\n key1: 'one',\n key2: 'two',\n key3: 'three'\n }, [1, 2, 3, 'one', 'two', 'three']),\n 'testConsoleDebug',\n callback\n );\n testing.success(\"console.re.debug('debug output for %s and %s', {key1:'one',key2:'two',key3:'three'}, [1,2,3,'one','two','three']); passed\", callback);\n}\n\nfunction testConsoleWarn(callback) {\n testing.assert(\n console.re.warn('this is a warning level message'),\n 'testConsoleWarn',\n callback\n );\n testing.success(\"console.re.warn('this is a warning level message'); passed\", callback);\n}\n\nfunction testConsoleError(callback) {\n testing.assert(\n console.re.error('[red]output any error message using error level[/red]'),\n 'testConsoleError',\n callback\n );\n testing.success(\"console.re.error('[red]output any error message using error level[/red]'); passed\", callback);\n}\n\nfunction testConsoleTest(callback) {\n testing.assert(\n console.re.test(\"10 + 1\", \"[1,2,3,4,5,6]\", \"'text'\", \"1==1\", \"'ab'=='ba'\"),\n 'testConsoleTest',\n callback\n );\n testing.success('console.re.test(\"10 + 1\",\"[1,2,3,4,5,6]\",\"text\",\"1==2\",\"ab==ba\"); passed', callback);\n}\n\nfunction testConsoleAssert(callback) {\n testing.assert(\n console.re.assert(1 !== 1, '1!==1 Assertion Failure‌'),\n 'testConsoleAssert',\n callback\n );\n testing.success(\"console.re.assert(1!==1, 'Assertion 1!==1 has Failure‌'); passed\", callback);\n}\n\nfunction testConsoleTrace(callback) {\n testing.assert(\n console.re.trace('Stack Trace output'),\n 'testConsoleTrace',\n callback\n );\n testing.success(\"console.re.trace('Stack Trace output'); passed\", callback);\n}\n\nfunction testConsoleTimeEnd(callback) {\n testing.assert(\n console.re.timeEnd('run timer'),\n 'testConsoleTimeEnd',\n callback\n );\n testing.success(\"console.re.timeEnd('run timer'); passed\", callback);\n}\n\nfunction testResults(error, result) {\n console.re.info('Console.Re API Tests %s', 'end');\n\n if (error) {\n testing.failure(`Console.Re API tests failed: ${error}`);\n } else {\n console.info('Console.Re API all tests passed');\n }\n}\n\nfunction consoleReTests() {\n console.re.info('Console.Re API Tests %s', 'started');\n\n testing.run([\n testConsoleClear,\n testConsoleTime,\n testConsoleLog,\n testConsoleInfo,\n testConsoleCount,\n testConsoleDebug,\n testConsoleWarn,\n testConsoleError,\n testConsoleTest,\n testConsoleAssert,\n testConsoleTrace,\n testConsoleTimeEnd\n ], testResults);\n}\n\nconsoleReTests();", "dangerousExampleEn": "1. \nLine 3: A debug code is remaining.", "safeExampleEn": "1. \nLine 3: Remove the code used for debugging.", "contexts": [{"lineNo": 151, "eventType": "sink", "messageKey": "jschk.LEFTOVER_DEBUG_CODE.TOBE.JS.defect", "params": {}}]}} {"id": "cc6bae53ac47fea7e46d6a55509e650eb30933fb66b19518f12baf35b0da68a8", "license": {"spdx": ["BSD-3-Clause"], "repo": "jjrasche/cell-based-RC-control", "path": "src/content/peerconnection/munge-sdp/js/main.js", "repo_head_hexsha": "5d176adc45e559e753ee4fc13ec2173da9cd1abc", "stack_hexsha": "97e9b816775e5cb66e2a95a27e74db24539e1d63", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Leftover debug code", "issueDescriptionEn": "The Leftover debug code checker finds debug code that remains not removed.\nDebug code may contain parts that output sensitive information or allow control over the system. If the program is deployed with debug code remaining, attackers may bypass an authentication process or access restricted information.\nRemove all debug code before deploying the application.", "issueLineNumber": 97, "entireCode": "/*\n * Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree.\n */\n\n'use strict';\n\nvar getMediaButton = document.querySelector('button#getMedia');\nvar createPeerConnectionButton =\n document.querySelector('button#createPeerConnection');\nvar createOfferButton = document.querySelector('button#createOffer');\nvar setOfferButton = document.querySelector('button#setOffer');\nvar createAnswerButton = document.querySelector('button#createAnswer');\nvar setAnswerButton = document.querySelector('button#setAnswer');\nvar hangupButton = document.querySelector('button#hangup');\n\ngetMediaButton.onclick = getMedia;\ncreatePeerConnectionButton.onclick = createPeerConnection;\ncreateOfferButton.onclick = createOffer;\nsetOfferButton.onclick = setOffer;\ncreateAnswerButton.onclick = createAnswer;\nsetAnswerButton.onclick = setAnswer;\nhangupButton.onclick = hangup;\n\nvar offerSdpTextarea = document.querySelector('div#local textarea');\nvar answerSdpTextarea = document.querySelector('div#remote textarea');\n\nvar audioSelect = document.querySelector('select#audioSrc');\nvar videoSelect = document.querySelector('select#videoSrc');\n\naudioSelect.onchange = videoSelect.onchange = getMedia;\n\nvar localVideo = document.querySelector('div#local video');\nvar remoteVideo = document.querySelector('div#remote video');\n\nvar selectSourceDiv = document.querySelector('div#selectSource');\n\nvar localPeerConnection;\nvar remotePeerConnection;\nvar localStream;\nvar sdpConstraints = {\n 'mandatory': {\n 'OfferToReceiveAudio': true,\n 'OfferToReceiveVideo': true\n }\n};\n\ngetSources();\n\nfunction getSources() {\n if (typeof MediaStreamTrack === 'undefined') {\n alert(\n 'This browser does not support MediaStreamTrack.\\n\\nTry Chrome Canary.');\n } else {\n navigator.mediaDevices.enumerateDevices().then(gotSources);\n }\n}\n\nfunction gotSources(sourceInfos) {\n selectSourceDiv.classList.remove('hidden');\n var audioCount = 0;\n var videoCount = 0;\n for (var i = 0; i < sourceInfos.length; i++) {\n var option = document.createElement('option');\n option.value = sourceInfos[i].id;\n option.text = sourceInfos[i].label;\n if (sourceInfos[i].kind === 'audioinput') {\n audioCount++;\n if (option.text === '') {\n option.text = 'Audio ' + audioCount;\n }\n audioSelect.appendChild(option);\n } else if (sourceInfos[i].kind === 'videoinput') {\n videoCount++;\n if (option.text === '') {\n option.text = 'Video ' + videoCount;\n }\n videoSelect.appendChild(option);\n } else {\n console.log('unknown', JSON.stringify(sourceInfos[i]));\n }\n }\n}\n\nfunction getMedia() {\n getMediaButton.disabled = true;\n createPeerConnectionButton.disabled = false;\n\n if (localStream) {\n localVideo.src = null;\n localStream.stop();\n }\n var audioSource = audioSelect.value;\n trace('Selected audio source: ' + audioSource);\n var videoSource = videoSelect.value;\n trace('Selected video source: ' + videoSource);\n\n var constraints = {\n audio: {\n optional: [{\n sourceId: audioSource\n }]\n },\n video: {\n optional: [{\n sourceId: videoSource\n }]\n }\n };\n trace('Requested local stream');\n getUserMedia(constraints, gotStream, function(e) {\n console.log('navigator.getUserMedia error: ', e);\n });\n}\n\nfunction gotStream(stream) {\n trace('Received local stream');\n // Call the polyfill wrapper to attach the media stream to this element.\n attachMediaStream(localVideo, stream);\n localStream = stream;\n}\n\nfunction createPeerConnection() {\n createPeerConnectionButton.disabled = true;\n createOfferButton.disabled = false;\n createAnswerButton.disabled = false;\n setOfferButton.disabled = false;\n setAnswerButton.disabled = false;\n hangupButton.disabled = false;\n trace('Starting call');\n var videoTracks = localStream.getVideoTracks();\n var audioTracks = localStream.getAudioTracks();\n if (videoTracks.length > 0) {\n trace('Using video device: ' + videoTracks[0].label);\n }\n if (audioTracks.length > 0) {\n trace('Using audio device: ' + audioTracks[0].label);\n }\n var servers = null;\n localPeerConnection = new RTCPeerConnection(servers);\n trace('Created local peer connection object localPeerConnection');\n localPeerConnection.onicecandidate = iceCallback1;\n remotePeerConnection = new RTCPeerConnection(servers);\n trace('Created remote peer connection object remotePeerConnection');\n remotePeerConnection.onicecandidate = iceCallback2;\n remotePeerConnection.onaddstream = gotRemoteStream;\n\n localPeerConnection.addStream(localStream);\n trace('Adding Local Stream to peer connection');\n}\n\nfunction onSetSessionDescriptionSuccess() {\n trace('Set session description success.');\n}\n\nfunction onSetSessionDescriptionError(error) {\n trace('Failed to set session description: ' + error.toString());\n}\n\n// Workaround for crbug/322756.\nfunction maybeAddLineBreakToEnd(sdp) {\n var endWithLineBreak = new RegExp(/\\n$/);\n if (!endWithLineBreak.test(sdp)) {\n return sdp + '\\n';\n }\n return sdp;\n}\n\nfunction createOffer() {\n localPeerConnection.createOffer(gotDescription1,\n onCreateSessionDescriptionError);\n}\n\nfunction onCreateSessionDescriptionError(error) {\n trace('Failed to create session description: ' + error.toString());\n}\n\nfunction setOffer() {\n var sdp = offerSdpTextarea.value;\n sdp = maybeAddLineBreakToEnd(sdp);\n var offer = new RTCSessionDescription({\n type: 'offer',\n sdp: sdp\n });\n localPeerConnection.setLocalDescription(offer,\n onSetSessionDescriptionSuccess,\n onSetSessionDescriptionError);\n trace('Modified Offer from localPeerConnection \\n' + sdp);\n remotePeerConnection.setRemoteDescription(offer,\n onSetSessionDescriptionSuccess,\n onSetSessionDescriptionError);\n}\n\nfunction gotDescription1(description) {\n offerSdpTextarea.disabled = false;\n offerSdpTextarea.value = description.sdp;\n}\n\nfunction createAnswer() {\n // Since the 'remote' side has no media stream we need\n // to pass in the right constraints in order for it to\n // accept the incoming offer of audio and video.\n remotePeerConnection.createAnswer(gotDescription2,\n onCreateSessionDescriptionError,\n sdpConstraints);\n}\n\nfunction setAnswer() {\n var sdp = answerSdpTextarea.value;\n sdp = maybeAddLineBreakToEnd(sdp);\n var answer = new RTCSessionDescription({\n type: 'answer',\n sdp: sdp\n });\n remotePeerConnection.setLocalDescription(answer,\n onSetSessionDescriptionSuccess,\n onSetSessionDescriptionError);\n trace('Modified Answer from remotePeerConnection \\n' + sdp);\n localPeerConnection.setRemoteDescription(answer,\n onSetSessionDescriptionSuccess,\n onSetSessionDescriptionError);\n}\n\nfunction gotDescription2(description) {\n answerSdpTextarea.disabled = false;\n answerSdpTextarea.value = description.sdp;\n}\n\nfunction hangup() {\n remoteVideo.src = '';\n trace('Ending call');\n // localStream.stop();\n localPeerConnection.close();\n remotePeerConnection.close();\n localPeerConnection = null;\n remotePeerConnection = null;\n offerSdpTextarea.disabled = true;\n answerSdpTextarea.disabled = true;\n getMediaButton.disabled = false;\n createPeerConnectionButton.disabled = true;\n createOfferButton.disabled = true;\n setOfferButton.disabled = true;\n createAnswerButton.disabled = true;\n setAnswerButton.disabled = true;\n hangupButton.disabled = true;\n}\n\nfunction gotRemoteStream(e) {\n // Call the polyfill wrapper to attach the media stream to this element.\n attachMediaStream(remoteVideo, e.stream);\n trace('Received remote stream');\n}\n\nfunction iceCallback1(event) {\n if (event.candidate) {\n remotePeerConnection.addIceCandidate(new RTCIceCandidate(event.candidate),\n onAddIceCandidateSuccess, onAddIceCandidateError);\n trace('Local ICE candidate: \\n' + event.candidate.candidate);\n }\n}\n\nfunction iceCallback2(event) {\n if (event.candidate) {\n localPeerConnection.addIceCandidate(new RTCIceCandidate(event.candidate),\n onAddIceCandidateSuccess, onAddIceCandidateError);\n trace('Remote ICE candidate: \\n ' + event.candidate.candidate);\n }\n}\n\nfunction onAddIceCandidateSuccess() {\n trace('AddIceCandidate success.');\n}\n\nfunction onAddIceCandidateError(error) {\n trace('Failed to add Ice Candidate: ' + error.toString());\n}", "dangerousExampleEn": "1. \nLine 3: A debug code is remaining.", "safeExampleEn": "1. \nLine 3: Remove the code used for debugging.", "contexts": [{"lineNo": 97, "eventType": "sink", "messageKey": "jschk.LEFTOVER_DEBUG_CODE.TOBE.JS.defect", "params": {}}]}} {"id": "a517335139257903f69a5d90822b0bef140a1080d34403bbbde89830c5838ce6", "license": {"spdx": ["Apache-2.0"], "repo": "openziti/ziti-browzer-core", "path": "src/channel/channel.js", "repo_head_hexsha": "88369bd503edfa781d392922964b24fefcc22b7b", "stack_hexsha": "c622ec0c8b31daac5e6b3e0ae83e70d8347d11cc", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Leftover debug code", "issueDescriptionEn": "The Leftover debug code checker finds debug code that remains not removed.\nDebug code may contain parts that output sensitive information or allow control over the system. If the program is deployed with debug code remaining, attackers may bypass an authentication process or access restricted information.\nRemove all debug code before deploying the application.", "issueLineNumber": 167, "entireCode": "/*\nCopyright Netfoundry, Inc.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\nhttps://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Module dependencies.\n */\n\nimport { flatOptions } from '../utils/flat-options'\nimport { defaultOptions } from './channel-options'\nimport { ZitiConnections } from './connections';\nimport { ZitiWASMTLSConnection } from './wasm-tls-connection';\nimport { Header } from './header';\nimport { ZitiWebSocket } from '../websocket/websocket';\nimport { ZitiSocket } from '../http/ziti-socket';\nimport { Messages } from './messages';\nimport { ZitiEdgeProtocol } from '../channel/protocol';\nimport throwIf from '../utils/throwif';\nimport {\n appendBuffer,\n toUTF8Array,\n sumBy,\n concatTypedArrays\n} from '../utils/utils';\n\nimport { isUndefined, isNull, isEqual, forEach } from 'lodash-es';\nimport { Mutex } from 'async-mutex';\nimport { Buffer } from 'buffer';\n\n//TODO: this breaks the build at the moment... figure out why!\nimport sodium from 'libsodium-wrappers';\n\nimport PromiseController from 'promise-controller';\nimport formatMessage from 'format-message';\n\n\n \n/**\n * ZitiChannel\n */\nclass ZitiChannel {\n\n /**\n * \n */\n constructor(options) {\n\n let _options = flatOptions(options, defaultOptions);\n\n this._session_token = _options.session_token;\n this._network_session_token = _options.network_session_token;\n\n this._zitiContext = _options.zitiContext;\n\n this._id = this._zitiContext.getNextChannelId();\n\n this._data = _options.data;\n\n this._timeout = _options.timeout;\n this._helloTimeout = _options.helloTimeout;\n\n this._state = ZitiEdgeProtocol.conn_state.Initial;\n\n this._msgSeq = -1;\n\n this._edgeRouter = _options.edgeRouter;\n this._edgeRouterHost = this._edgeRouter.hostname;\n\n this._connections = new ZitiConnections();\n\n this._zws = new ZitiWebSocket( this._edgeRouter.urls.ws + '/ws' , { \n zitiContext: this._zitiContext,\n });\n this._callerId = \"ws:\";\n\n this._zws.onMessage.addListener(this._recvFromWire, this);\n\n this._zws.onClose.addListener(this._recvClose, this);\n\n this._zws.onSend.addListener(this._recvSend, this);\n\n this._createHelloController();\n\n // Set the maximum timestamp\n this._helloCompletedTimestamp = new Date(8640000000000000); // http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.1\n\n this._messages = new Messages({ zitiContext: this._zitiContext, channel: this });\n\n this._view_version = new Uint8Array(new ArrayBuffer(4));\n this._view_version.set(ZitiEdgeProtocol.VERSION, 0);\n\n this._mutex = new Mutex();\n\n }\n\n get zitiContext() {\n return this._zitiContext;\n }\n\n get id() {\n return this._id;\n }\n\n get tlsConn() {\n return this._tlsConn;\n }\n\n get data() {\n return this._data;\n }\n\n get state() {\n return this._state;\n }\n set state(state) {\n this._state = state;\n }\n\n getAndIncrementSequence() {\n return this._msgSeq++;\n }\n\n get edgeRouterHost() {\n return this._edgeRouterHost;\n }\n\n get helloCompletedTimestamp() {\n return this._helloCompletedTimestamp;\n }\n\n get isHelloCompleted() {\n return Boolean(this._helloCompleted);\n }\n\n /**\n * \n */\n _createHelloController() {\n const helloTimeout = this._helloTimeout || this._timeout;\n this._helloing = new PromiseController({\n timeout: helloTimeout,\n timeoutReason: `Can't complete 'Hello' within allowed timeout: ${helloTimeout} ms.`\n });\n }\n\n /**\n * Remain in lazy-sleepy loop until tlsConn has completed its TLS handshake.\n * \n */\n async awaitTLSHandshakeComplete() {\n let self = this;\n return new Promise((resolve) => {\n (function waitForTLSHandshakeComplete() {\n if (!self._tlsConn.connected) {\n self._zitiContext.logger.trace('awaitTLSHandshakeComplete() tlsConn for ch[%d] TLS handshake still not complete', self.id);\n setTimeout(waitForTLSHandshakeComplete, 100); \n } else {\n self._zitiContext.logger.trace('tlsConn for ch[%d] TLS handshake is now complete', self.id);\n let result = self._tlsConn.ssl_get_verify_result();\n if (result !== 1) {\n self._zitiContext.logger.error('tlsConn for ch[%d] fails TLS verification', self.id);\n }\n return resolve();\n }\n })();\n });\n }\n\n /**\n * Do Hello handshake between this channel and associated Edge Router.\n * \n */\n async hello() {\n\n this._zitiContext.logger.trace('ZitiChannel.hello entered for ch[%o]', this);\n\n await this._zws.open();\n\n this._zitiContext.logger.trace('ZitiChannel.hello _zws.open completed for ch[%o]', this);\n\n if (this.isHelloCompleted) {\n this._zitiContext.logger.trace('Hello handshake was previously completed');\n return new Promise( async (resolve) => {\n resolve( {channel: this, data: null});\n });\n }\n\n if (isEqual(this._callerId, \"ws:\")) {\n\n // this._zitiContext.ssl_CTX_new();\n // // this._zitiContext.bio_new_ssl_connect();\n // // this._zitiContext.bio_set_conn_hostname('www.google.com:443');\n // // this._zitiContext.bio_do_connect();\n \n // this._zitiContext.ssl_new();\n // this._zitiContext.ssl_set_fd( this.id );\n // this._zitiContext.ssl_connect();\n\n this._tlsConn = new ZitiWASMTLSConnection({\n zitiContext: this._zitiContext,\n ws: this._zws,\n ch: this,\n datacb: this._recvFromWireAfterDecrypt\n });\n await this._tlsConn.pullKeyPair();\n \n await this._tlsConn.create();\n\n this._zitiContext.logger.debug('initiating TLS handshake');\n\n this._tlsConn.handshake();\n\n await this.awaitTLSHandshakeComplete();\n\n this._zitiContext.logger.debug('TLS handshake completed');\n\n }\n\n this._zitiContext.logger.debug('initiating message: ZitiEdgeProtocol.content_type.HelloType: ', ZitiEdgeProtocol.header_type.StringType);\n\n let headers = [\n new Header( ZitiEdgeProtocol.header_id.SessionToken, { \n headerType: ZitiEdgeProtocol.header_type.StringType, \n headerData: this._session_token \n }),\n new Header( ZitiEdgeProtocol.header_id.CallerId, { \n headerType: ZitiEdgeProtocol.header_type.StringType, \n headerData: this._callerId \n })\n ]; \n\n let sequence = this.getAndIncrementSequence();\n\n let msg = await this.sendMessage( ZitiEdgeProtocol.content_type.HelloType, headers, null, { \n sequence: sequence,\n });\n\n this._helloCompletedTimestamp = Date.now();\n this._helloCompleted = true;\n this.state = (ZitiEdgeProtocol.conn_state.Connected);\n this._zitiContext.logger.debug('ch[%d] Hello handshake to Edge Router [%s] completed at timestamp[%o]', this._id, this._edgeRouterHost, this._helloCompletedTimestamp);\n\n return new Promise( async (resolve) => {\n resolve( {channel: this, data: null});\n });\n\n }\n\n /**\n * Connect specified Connection to associated Edge Router.\n * \n */\n async connect(conn) {\n\n const self = this;\n return new Promise( async (resolve, reject) => {\n \n self._zitiContext.logger.debug('initiating Connect to Edge Router [%s] for conn[%d]', this._edgeRouterHost, conn.id);\n \n await sodium.ready;\n \n let keypair = sodium.crypto_kx_keypair();\n \n conn.keypair = (keypair);\n \n let sequence = this.getAndIncrementSequence();\n\n let headers = [\n \n new Header( ZitiEdgeProtocol.header_id.ConnId, {\n headerType: ZitiEdgeProtocol.header_type.IntType,\n headerData: conn.id\n }),\n \n new Header( ZitiEdgeProtocol.header_id.SeqHeader, { \n headerType: ZitiEdgeProtocol.header_type.IntType, \n headerData: 0 \n }),\n \n ];\n\n if (conn.encrypted) { // if connected to a service that has 'encryptionRequired'\n\n headers.push(\n \n new Header( ZitiEdgeProtocol.header_id.PublicKey, { \n headerType: ZitiEdgeProtocol.header_type.Uint8ArrayType, \n headerData: keypair.publicKey\n })\n \n );\n }\n \n conn.state = (ZitiEdgeProtocol.conn_state.Connecting);\n \n self._zitiContext.logger.debug('about to send Connect to Edge Router [%s] for conn[%d]', conn.channel.edgeRouterHost, conn.id);\n \n let msg = await self.sendMessage( ZitiEdgeProtocol.content_type.Connect, headers, self._network_session_token, { \n conn: conn,\n sequence: sequence,\n } \n );\n\n self._zitiContext.logger.debug('connect() calling _recvConnectResponse() for conn[%d]', conn.id);\n\n await self._recvConnectResponse(msg.data, conn);\n \n resolve();\n \n });\n }\n\n /**\n * Close specified Connection to associated Edge Router.\n * \n */\n async close(conn) {\n\n const self = this;\n return new Promise( async (resolve, reject) => {\n \n self._zitiContext.logger.debug('initiating Close to Edge Router [%s] for conn[%d]', this._edgeRouterHost, conn.id);\n \n let sequence = conn.getAndIncrementSequence();\n\n let headers = [\n \n new Header( ZitiEdgeProtocol.header_id.ConnId, {\n headerType: ZitiEdgeProtocol.header_type.IntType,\n headerData: conn.id\n }),\n \n new Header( ZitiEdgeProtocol.header_id.SeqHeader, { \n headerType: ZitiEdgeProtocol.header_type.IntType, \n headerData: sequence\n }),\n \n ];\n \n self._zitiContext.logger.debug('about to send Close to Edge Router [%s] for conn[%d]', conn.channel.edgeRouterHost, conn.id);\n \n let msg = await self.sendMessage( ZitiEdgeProtocol.content_type.StateClosed, headers, self._network_session_token, { \n conn: conn,\n sequence: sequence,\n } \n );\n\n self._zitiContext.logger.debug('close() completed with response[%o]', msg);\n\n conn.state = (ZitiEdgeProtocol.conn_state.Closed);\n \n resolve();\n \n });\n }\n\n /**\n * Receives response from Edge 'Connect' message.\n * \n */\n async _recvConnectResponse(msg, expectedConn) {\n\n // let buffer = await msg.arrayBuffer();\n let buffer = await msg.buffer;\n let contentTypeView = new Int32Array(buffer, 4, 1);\n let contentType = contentTypeView[0];\n let sequenceView = new Int32Array(buffer, 8, 1);\n let sequence = sequenceView[0];\n let connId = await this._messageGetConnId(msg);\n let conn = this._connections._getConnection(connId);\n throwIf(isUndefined(conn), formatMessage('Conn not found. Seeking connId { actual }', { actual: connId}) );\n if (!isEqual(conn.id, expectedConn.id)) {\n this._zitiContext.logger.error(\"_recvConnectResponse() actual conn[%d] expected conn[%d]\", conn.id, expectedConn.id);\n }\n\n this._zitiContext.logger.debug(\"ConnectResponse contentType[%d] seq[%d] received for conn[%d]\", contentType, sequence, conn.id);\n\n switch (contentType) {\n\n case ZitiEdgeProtocol.content_type.StateClosed:\n\n this._zitiContext.logger.warn(\"conn[%d] failed to connect on ch[%d]\", conn.id, this.id);\n conn.state = (ZitiEdgeProtocol.conn_state.Closed);\n break;\n\n case ZitiEdgeProtocol.content_type.StateConnected:\n\n if (conn.state == ZitiEdgeProtocol.conn_state.Connecting) {\n this._zitiContext.logger.debug(\"conn[%d] connected\", conn.id);\n\n if (conn.encrypted) { // if connected to a service that has 'encryptionRequired'\n\n await this._establish_crypto(conn, msg);\n this._zitiContext.logger.debug(\"establish_crypto completed for conn[%d]\", conn.id);\n\n await this._send_crypto_header(conn);\n this._zitiContext.logger.debug(\"send_crypto_header completed for conn[%d]\", conn.id);\n\n }\n\n conn.state = (ZitiEdgeProtocol.conn_state.Connected);\n }\n\n else if (conn.state == ZitiEdgeProtocol.conn_state.Closed || conn.state == ZitiEdgeProtocol.conn_state.Timedout) {\n this._zitiContext.logger.warn(\"received connect reply for closed/timedout conne[%d]\", conn.id);\n // ziti_disconnect(conn);\n }\n break;\n\n default:\n this._zitiContext.logger.error(\"unexpected content_type[%d] conn[%d]\", contentType, conn.id);\n // ziti_disconnect(conn);\n }\n\n }\n\n /**\n * \n */\n async _establish_crypto(conn, msg) {\n\n this._zitiContext.logger.debug(\"_establish_crypto(): entered for conn[%d]\", conn.id);\n\n let result = await this._messageGetBytesHeader(msg, ZitiEdgeProtocol.header_id.PublicKey);\n let peerKey = result.data;\n this._zitiContext.logger.debug(\"_establish_crypto(): peerKey is: \", peerKey);\n\n if (peerKey == undefined) {\n this._zitiContext.logger.debug(\"_establish_crypto(): did not receive peer key. connection[%d] will not be encrypted: \", conn.id);\n conn.encrypted = false;\n return;\n }\n\n if (conn.state == ZitiEdgeProtocol.conn_state.Connecting) {\n\n let keypair = conn.keypair();\n\n let results = sodium.crypto_kx_client_session_keys(keypair.publicKey, keypair.privateKey, peerKey);\n\n conn.setSharedRx(results.sharedRx);\n conn.setSharedTx(results.sharedTx);\n\n } else {\n this._zitiContext.logger.error(\"_establish_crypto(): cannot establish crypto while connection is in %d state: \", conn.state);\n }\n\n }\n\n /**\n * Receives response from Edge 'Data' message where we sent the Crypto header.\n * \n */\n async _recvCryptoResponse(msg) {\n\n let connId = await this._messageGetConnId(msg);\n this._zitiContext.logger.debug(\"_recvCryptoResponse(): entered for conn[%d]\", connId);\n let conn = this._connections._getConnection(connId);\n throwIf(isUndefined(conn), formatMessage('Conn not found. Seeking connId { actual }', { actual: connId}) );\n\n //\n let buffer = await msg.buffer;\n let headersLengthView = new Int32Array(buffer, 12, 1);\n let headersLength = headersLengthView[0];\n var bodyView = new Uint8Array(buffer, 20 + headersLength);\n\n let state_in = sodium.crypto_secretstream_xchacha20poly1305_init_pull(bodyView, conn.sharedRx);\n \n conn.setCrypt_i(state_in);\n\n // Indicate that subsequent sends on this connection should be encrypted\n conn.encrypted = true;\n\n // Unblock writes to the connection now that we have sent the crypto header\n conn.setCryptoEstablishComplete(true);\n\n this._zitiContext.logger.debug(\"_recvCryptoResponse(): setCryptoEstablishComplete for conn[%d]\", connId);\n\n }\n\n /**\n * Remain in lazy-sleepy loop until specified connection's crypto handshake is complete.\n * \n * @param {*} conn \n */\n awaitConnectionCryptoEstablishComplete(conn) {\n return new Promise((resolve) => {\n (function waitForCryptoEstablishComplete() {\n if (conn.cryptoEstablishComplete) {\n conn.zitiContext.logger.debug('Connection [%d] now Crypto-enabled with Edge Router', conn.id);\n return resolve();\n }\n conn.zitiContext.logger.debug('awaitConnectionCryptoEstablishComplete() conn[%d] still not yet CryptoEstablishComplete', conn.id);\n setTimeout(waitForCryptoEstablishComplete, 100);\n })();\n });\n }\n\n /**\n * \n */\n async _send_crypto_header(conn) {\n\n const self = this;\n return new Promise( async (resolve, reject) => {\n\n let results = sodium.crypto_secretstream_xchacha20poly1305_init_push( conn.sharedTx );\n\n conn.setCrypt_o(results);\n\n let sequence = conn.getAndIncrementSequence();\n\n let headers = [\n\n new Header( ZitiEdgeProtocol.header_id.ConnId, {\n headerType: ZitiEdgeProtocol.header_type.IntType,\n headerData: conn.id\n }),\n\n new Header( ZitiEdgeProtocol.header_id.SeqHeader, { \n headerType: ZitiEdgeProtocol.header_type.IntType, \n headerData: sequence \n })\n\n ]; \n\n self._zitiContext.logger.debug('_send_crypto_header(): conn[%d] sending Data [%o]', conn.id, conn.crypt_o.header);\n\n let msg = await self.sendMessage( ZitiEdgeProtocol.content_type.Data, headers, conn.crypt_o.header, {\n conn: conn,\n sequence: sequence,\n }\n );\n\n self._zitiContext.logger.debug('_send_crypto_header() calling _recvCryptoResponse() for conn[%d]', conn.id);\n await self._recvCryptoResponse(msg.data, conn);\n\n resolve();\n\n });\n }\n\n /**\n * Write data over specified Edge Router connection.\n *\n * @returns {Promise}\n */\n async write(conn, data) {\n\n if (!isEqual(conn.state, ZitiEdgeProtocol.conn_state.Closed)) {\n\n let sequence = conn.getAndIncrementSequence();\n\n let headers = [\n new Header( ZitiEdgeProtocol.header_id.ConnId, {\n headerType: ZitiEdgeProtocol.header_type.IntType,\n headerData: conn.id\n }),\n new Header( ZitiEdgeProtocol.header_id.SeqHeader, { \n headerType: ZitiEdgeProtocol.header_type.IntType, \n headerData: sequence \n })\n ];\n\n this.sendMessageNoWait( ZitiEdgeProtocol.content_type.Data, headers, data, { conn: conn, sequence: sequence });\n }\n }\n\n /**\n * Sends message and waits for response.\n *\n * @param {String|Number} contentType\n * @param {[Header]} headers\n * @param {*} body\n * @param {Object} [options]\n * @returns {Promise}\n */\n sendMessage(contentType, headers, body, options = {}) {\n const timeout = options.timeout !== undefined ? options.timeout : this._timeout;\n let messageId;\n if (!isUndefined(options.sequence)) {\n messageId = options.sequence;\n } else if (!isUndefined(this._sequence)) {\n messageId = this._sequence;\n } \n throwIf(isUndefined(messageId), formatMessage('messageId is undefined', { } ) );\n \n let messagesQueue = this._messages;\n let conn;\n if (!isUndefined(options.conn)) {\n conn = options.conn;\n messagesQueue = options.conn.messages;\n }\n\n this._zitiContext.logger.debug(\"send -> conn[%o] seq[%o] contentType[%o] body[%s]\", (conn ? conn.id : 'n/a'), messageId, contentType, (body ? body.toString() : 'n/a'));\n\n return messagesQueue.create(messageId, () => {\n this._sendMarshaled(contentType, headers, body, options, messageId);\n }, timeout);\n }\n\n /**\n * Sends message and does not wait for response.\n *\n * @param {String|Number} contentType\n * @param {[Header]} headers\n * @param {*} body\n * @param {Object} [options]\n * @returns {Promise}\n */\n sendMessageNoWait(contentType, headers, body, options = {}) {\n const timeout = options.timeout !== undefined ? options.timeout : this._timeout;\n const messageId = options.sequence || this._sequence;\n // this._zitiContext.logger.debug(\"send (no wait) -> conn[%o] seq[%o] contentType[%o]\", \n // (options.conn ? options.conn.id : 'n/a'), \n // messageId, \n // contentType, \n // (body ? body.toString() : 'n/a'));\n\n this._zitiContext.logger.debug(\"send (no wait) -> conn[%o] seq[%o] contentType[%o] bodyLen[%o] \", \n (options.conn ? options.conn.id : 'n/a'), \n messageId, contentType, \n (body ? body.length : 'n/a'),\n (body ? body.toString() : 'n/a')\n );\n\n this._sendMarshaled(contentType, headers, body, options, messageId);\n }\n\n /**\n * Marshals message into binary wire format and sends to the Edge Router.\n *\n * @param {String|Number} contentType\n * @param {[Header]} headers\n * @param {*} body\n * @param {Object} [options]\n * @param {int} messageId\n */\n _sendMarshaled(contentType, headers, body, options, messageId) {\n\n let dataToMarshal = body;\n\n if (contentType != ZitiEdgeProtocol.content_type.HelloType) {\n\n let connId;\n forEach(headers, function(header) {\n if (header.getId() == ZitiEdgeProtocol.header_id.ConnId) {\n connId = header.getData();\n }\n });\n throwIf(isUndefined(connId), formatMessage('Cannot find ConnId header', { } ) );\n\n let conn = this._connections._getConnection(connId);\n throwIf(isUndefined(conn), formatMessage('Conn not found. Seeking connId { actual }', { actual: connId}) );\n\n if (conn.encrypted && conn.cryptoEstablishComplete) { // if connected to a service that has 'encryptionRequired'\n\n let [state_out, header] = [conn.crypt_o.state, conn.crypt_o.header];\n\n let encryptedData = sodium.crypto_secretstream_xchacha20poly1305_push(\n state_out,\n body,\n null,\n sodium.crypto_secretstream_xchacha20poly1305_TAG_MESSAGE);\n\n dataToMarshal = encryptedData;\n }\n }\n\n const wireData = this._marshalMessage(contentType, headers, dataToMarshal, options, messageId);\n this._zitiContext.logger.trace(\"_sendMarshaled -> wireDataLen[%o] \", wireData.byteLength);\n\n this._dumpHeaders(' -> ', wireData);\n\n // Inject the listener if specified\n if (options.listener !== undefined) {\n this._zws.onMessage.addOnceListener(options.listener, this);\n }\n\n // If connected to a WS edge router\n if (isEqual(this._callerId, \"ws:\")) {\n this._tlsConn.tls_write(wireData);\n }\n else {\n this._zws.send(wireData);\n }\n }\n\n /**\n * Marshals message into binary wire format.\n *\n * @param {String|Number} contentType\n * @param {[Header]} headers\n * @param {*} body\n * @param {Object} [options]\n * @returns {byte[]} \n */\n _marshalMessage(contentType, headers, body, options, messageId) {\n\n // wire-protocol: message-section\n let buffer_message_section = new ArrayBuffer(\n 4 // Version\n +4 // ContentType (offset 4)\n +4 // Sequence (offset 8)\n +4 // hdrs-len (offset 12)\n +4 // body-len (offset 16)\n );\n \n // wire-protocol: Version\n let view_message_section = new Uint8Array(buffer_message_section);\n view_message_section.set(\n ZitiEdgeProtocol.VERSION, \n 0 // Offset 0\n );\n \n var bytes = new Buffer(4);\n \n // wire-protocol: ContentType\n bytes.writeUInt32LE(contentType, 0);\n view_message_section.set(\n bytes, \n 4 // Offset 4\n );\n \n bytes = new Buffer(4);\n \n // wire-protocol: Sequence\n bytes.writeInt32LE(messageId, 0);\n view_message_section.set(\n bytes, \n 8 // Offset 8\n );\n \n bytes = new Buffer(4);\n \n let hdrsLen = sumBy(headers, function (header) {\n return header.getLength(); \n });\n\n // wire-protocol: hdrs-len\n bytes.writeInt32LE(hdrsLen, 0);\n view_message_section.set(\n bytes, \n 12 // Offset 12\n );\n \n bytes = new Buffer(4);\n \n // wire-protocol: body-len\n let bodyLength = 0;\n if (!isNull(body)) {\n bodyLength = body.length;\n }\n\n bytes.writeUInt32LE(bodyLength, 0);\n view_message_section.set(\n bytes, \n 16 // Offset 16\n );\n \n // wire-protocol: headers\n let buffer_headers_section = new ArrayBuffer(hdrsLen);\n let view_headers_section = new Uint8Array(buffer_headers_section);\n let view_headers_section_offset = 0;\n forEach(headers, function(header) {\n view_headers_section.set(header.getBytesForWire(), view_headers_section_offset);\n view_headers_section_offset += header.getLength(); \n });\n \n \n // wire-protocol: body\n let buffer_body_section = new ArrayBuffer(bodyLength);\n if (bodyLength > 0) {\n let view_body_section = new Uint8Array(buffer_body_section);\n let body_bytes;\n if (typeof body === 'string') {\n body_bytes = toUTF8Array(body);\n } else {\n body_bytes = body;\n }\n let bytesBuffer = Buffer.from(body_bytes);\n view_body_section.set(bytesBuffer, 0);\n }\n \n // Put it all together\n this._zitiContext.logger.trace(\"_marshalMessage -> buffer_message_section Len[%o] \", buffer_message_section.byteLength);\n this._zitiContext.logger.trace(\"_marshalMessage -> buffer_headers_section Len[%o] \", buffer_headers_section.byteLength);\n this._zitiContext.logger.trace(\"_marshalMessage -> buffer_body_section Len[%o] \", buffer_body_section.byteLength);\n let buffer_combined = appendBuffer(buffer_message_section, buffer_headers_section);\n buffer_combined = appendBuffer(buffer_combined, buffer_body_section);\n let view_combined = new Uint8Array(buffer_combined);\n \n return view_combined.buffer;\n }\n\n /**\n * Receives a send event from the Websocket.\n * \n * @param {*} data \n */\n async _recvSend(data) {\n if (!isUndefined(this._zws)) {\n if (!isNull(this._zws._ws)) {\n this._zitiContext.logger.debug('_recvSend -> data[%o] sentLen[%o] bufferedLen[%o]', data, data.byteLength, this._zws._ws.bufferedAmount);\n }\n }\n }\n\n /**\n * Receives a close event from the Websocket.\n * \n * @param {*} data \n */\n async _recvClose(data) {\n\n this._zitiContext.closeChannelByEdgeRouter( this._edgeRouterHost );\n\n }\n\n /**\n * Receives a message from the Edge Router.\n * \n * @param {*} data \n */\n async _recvFromWire(data) {\n let buffer = await data.arrayBuffer();\n this._zitiContext.logger.debug(\"_recvFromWire <- data len[%o]\", buffer.byteLength);\n this._tlsConn.process(buffer);\n }\n\n /**\n * Receives un-encrypted binary data from the Edge Router (which is either an entire edge protocol message, or a fragment thereof)\n * \n * @param ArrayBuffer data \n */\n async _recvFromWireAfterDecrypt(ch, data) {\n\n let buffer = data;\n\n if (!isUndefined(ch._partialMessage)) { // if we are awaiting rest of a partial msg to arrive, append this chunk onto the end, then proceed\n let dataView = new Uint8Array(data);\n ch._partialMessage = concatTypedArrays(ch._partialMessage, dataView);\n buffer = ch._partialMessage.buffer.slice(0);\n } \n\n let versionView = new Uint8Array(buffer, 0, 4);\n throwIf(!isEqual(versionView[0], ch._view_version[0]), formatMessage('Unexpected message version. Got { actual }, expected { expected }', { actual: versionView[0], expected: ch._view_version[0]}) );\n\n let headersLengthView = new Int32Array(buffer, 12, 1);\n let headersLength = headersLengthView[0];\n\n let bodyLengthView = new Int32Array(buffer, 16, 1);\n let bodyLength = bodyLengthView[0];\n\n let msgLength = ( 20 + headersLength + bodyLength );\n\n if (isEqual(msgLength, buffer.byteLength)) { // if entire edge message is present, proceed with unmarshaling effort\n\n ch._partialMessage = undefined;\n \n ch._tryUnmarshal(buffer);\n\n } else {\n\n ch._partialMessage = new Uint8Array(buffer);\n\n if (buffer.byteLength > 20) { // if we have a portion of the data section of the edge message \n ch._zitiContext.logger.debug(\"Only [%o] of msgLength [%o] received; will await rest of fragments before unmarshaling\", buffer.byteLength, msgLength);\n }\n }\n }\n\n /**\n * Unmarshals binary from the wire into a message\n * \n * @param {*} data \n */\n async _tryUnmarshal(data) {\n\n let buffer = data;\n\n let versionView = new Uint8Array(buffer, 0, 4);\n throwIf(!isEqual(versionView[0], this._view_version[0]), formatMessage('Unexpected message version. Got { actual }, expected { expected }', { actual: versionView[0], expected: this._view_version[0]}) );\n\n let contentTypeView = new Int32Array(buffer, 4, 1);\n let contentType = contentTypeView[0];\n\n let sequenceView = new Int32Array(buffer, 8, 1);\n this._zitiContext.logger.trace(\"recv <- contentType[%o] seq[%o]\", contentType, sequenceView[0]);\n\n let responseSequence = sequenceView[0];\n\n let headersLengthView = new Int32Array(buffer, 12, 1);\n let headersLength = headersLengthView[0];\n this._zitiContext.logger.trace(\"recv <- headersLength[%o]\", headersLength);\n\n let bodyLengthView = new Int32Array(buffer, 16, 1);\n let bodyLength = bodyLengthView[0];\n this._zitiContext.logger.trace(\"recv <- bodyLength[%o]\", bodyLength);\n\n this._dumpHeaders(' <- ', buffer);\n var bodyView = new Uint8Array(buffer, 20 + headersLength);\n\n let connId;\n let conn;\n let replyForView;\n let haveResponseSequence = false;\n\n const release = await this._mutex.acquire();\n\n /**\n * First Data msg for a new connection needs special handling\n */\n if (contentType == ZitiEdgeProtocol.content_type.Data) {\n connId = await this._messageGetConnId(data);\n if (!isUndefined(connId)) {\n conn = this._connections._getConnection(connId);\n if (!isUndefined(conn)) {\n if (isEqual(conn.state, ZitiEdgeProtocol.conn_state.Connecting)) {\n let result = await this._messageGetBytesHeader(data, ZitiEdgeProtocol.header_id.SeqHeader);\n if (!isUndefined(result)) {\n replyForView = new Int32Array(result.data, 0, 1);\n responseSequence = replyForView[0];\n haveResponseSequence = true;\n this._zitiContext.logger.debug(\"recv <- ReplyFor[%o] (should be for the crypto_header response)\", responseSequence);\n } \n }\n }\n }\n }\n\n\n if (!haveResponseSequence && (contentType >= ZitiEdgeProtocol.content_type.StateConnected)) {\n\n let result = await this._messageGetBytesHeader(data, ZitiEdgeProtocol.header_id.ReplyFor);\n if (!isUndefined(result)) {\n\n replyForView = new DataView( result.data.buffer.slice(result.data.byteOffset, result.data.byteLength + result.data.byteOffset) );\n responseSequence = replyForView.getInt32(0, true); // second parameter truethy == want little endian;\n this._zitiContext.logger.trace(\"recv <- ReplyFor[%o]\", responseSequence);\n\n } else {\n\n if ( isEqual(contentType, ZitiEdgeProtocol.content_type.Data) && isEqual(bodyLength, 0) ) {\n\n let result = await this._messageGetBytesHeader(data, ZitiEdgeProtocol.header_id.SeqHeader);\n replyForView = new Int32Array(result.data, 0, 1);\n responseSequence = replyForView[0];\n this._zitiContext.logger.trace(\"recv <- Close Response For [%o]\", responseSequence); \n \n } else {\n\n this._zitiContext.logger.trace(\"recv <- ReplyFor[%o]\", 'n/a'); \n responseSequence--;\n this._zitiContext.logger.trace(\"reducing seq by 1 to [%o]\", responseSequence);\n\n }\n }\n }\n\n\n if ((contentType >= ZitiEdgeProtocol.content_type.Connect) && (isUndefined(conn))) {\n let connId = await this._messageGetConnId(data);\n throwIf(isUndefined(connId), formatMessage('Cannot find ConnId header', { } ) );\n conn = this._connections._getConnection(connId);\n throwIf(isUndefined(conn), formatMessage('Conn not found. Seeking connId { actual }', { actual: connId}) );\n }\n\n /**\n * Data msgs might need to be decrypted before passing along\n */\n if (contentType == ZitiEdgeProtocol.content_type.Data) {\n\n if (bodyLength > 0) {\n\n if (conn.encrypted && conn.cryptoEstablishComplete) { // if connected to a service that has 'encryptionRequired'\n\n let unencrypted_data = sodium.crypto_secretstream_xchacha20poly1305_pull(conn.crypt_i, bodyView);\n\n if (!unencrypted_data) {\n this._zitiContext.logger.error(\"crypto_secretstream_xchacha20poly1305_pull failed. bodyLength[%d]\", bodyLength);\n }\n\n try {\n let [m1, tag1] = [sodium.to_string(unencrypted_data.message), unencrypted_data.tag];\n let len = m1.length;\n if (len > 2000) {\n len = 2000;\n }\n this._zitiContext.logger.trace(\"recv <- unencrypted_data (first 2000): %s\", m1.substring(0, len));\n\n //\n let dbgStr = m1.substring(0, len);\n this._zitiContext.logger.trace(\"recv <- data (first 2000): %s\", dbgStr);\n\n } catch (e) { }\n\n bodyView = unencrypted_data.message;\n } else {\n /* debug...\n let len = bodyView.length;\n if (len > 2000) {\n len = 2000;\n }\n let dbgStr = String.fromCharCode.apply(null, bodyView).substring(0, len);\n this._zitiContext.logger.debug(\"recv <- data (first 2000): %s\", dbgStr);\n */\n\n //temp debugging\n // if (dbgStr.includes(\"var openMe = (window.parent\")) {\n\n // let str = String.fromCharCode.apply(null, bodyView).substring(0, bodyView.length);\n\n // // str = str.replace('var openMe = (window.parent', 'debugger; var openMe = (window.parent');\n\n // if (str.indexOf( '/api/extplugins/config' ) !== -1) {\n // debugger\n // }\n\n // this._zitiContext.logger.debug(\"============== DEBUG INJECT: %s\", str);\n\n // bodyView = new TextEncoder(\"utf-8\").encode(str);\n \n // }\n\n }\n }\n\n // \n let dataCallback = conn.dataCallback;\n if (!isUndefined(dataCallback)) {\n this._zitiContext.logger.trace(\"recv <- contentType[%o] seq[%o] passing body to dataCallback\", contentType, sequenceView[0]);\n dataCallback(conn, bodyView);\n }\n }\n \n this._zitiContext.logger.trace(\"recv <- response body: \", bodyView);\n this._tryHandleResponse(conn, responseSequence, {channel: this, data: bodyView});\n\n release();\n }\n\n /**\n * \n */\n _tryHandleResponse(conn, responseSequence, data) {\n\n if (!isUndefined(conn)) {\n let socket = conn.socket;\n if (!isUndefined(socket)) {\n if (socket.isWebSocket) {\n return;\n }\n }\n }\n\n\n let messagesQueue = this._messages;\n if (!isUndefined(conn)) {\n messagesQueue = conn.messages;\n }\n this._zitiContext.logger.trace(\"_tryHandleResponse(): conn[%d] seq[%d]\", (conn ? conn.id : 'n/a'), responseSequence);\n if (!isNull(responseSequence)) {\n messagesQueue.resolve(responseSequence, data);\n } else {\n debugger\n }\n }\n \n /**\n * \n */\n async _dumpHeaders(pfx, buffer) {\n\n var headersView = new Int32Array(buffer, 12, 1);\n\n let headersLength = headersView[0];\n let headersOffset = 16 + 4;\n let ndx = 0;\n\n let view = new DataView(buffer);\n\n this._zitiContext.logger.trace(\"_dumpHeaders: \"+pfx+\"vv----------------------------------\");\n\n for ( ; ndx < headersLength; ) {\n\n var _headerId = view.getInt32(headersOffset + ndx, true);\n ndx += 4;\n\n var _headerDataLength = view.getInt32(headersOffset + ndx, true);\n ndx += 4;\n\n var _headerData = new Uint8Array(buffer, headersOffset + ndx, _headerDataLength);\n ndx += _headerDataLength;\n\n let connId = 'n/a';\n if (isEqual(_headerId, ZitiEdgeProtocol.header_id.ConnId)) {\n let buffer = Buffer.from(_headerData);\n connId = buffer.readUIntLE(0, _headerDataLength);\n }\n\n this._zitiContext.logger.trace(\"headerId[%d] conn[%d] dataLength[%d] data[%o]\", _headerId, connId, _headerDataLength, _headerData);\n }\n\n this._zitiContext.logger.trace(\"_dumpHeaders: \"+pfx+\"^^----------------------------------\");\n }\n\n /**\n * \n */\n async _findHeader(msg, headerToFind) {\n\n let buffer;\n\n if (!isUndefined(msg.arrayBuffer)) {\n buffer = await msg.arrayBuffer();\n } else if (!isUndefined(msg.buffer)) {\n buffer = await msg.buffer;\n } else {\n buffer = msg;\n }\n\n var headersView = new Int32Array(buffer, 12, 1);\n\n let headersLength = headersView[0];\n let headersOffset = 16 + 4;\n let ndx = 0;\n\n let view = new DataView(buffer);\n\n for ( ; ndx < headersLength; ) {\n\n var _headerId = view.getInt32(headersOffset + ndx, true);\n ndx += 4;\n\n var _headerDataLength = view.getInt32(headersOffset + ndx, true);\n ndx += 4;\n\n var _headerData = new Uint8Array(buffer, headersOffset + ndx, _headerDataLength);\n ndx += _headerDataLength;\n\n if (_headerId == headerToFind) {\n\n let result = {\n dataLength: _headerDataLength,\n data: _headerData,\n };\n\n return result;\n }\n }\n\n return undefined;\n }\n\n /**\n * \n */\n async _messageGetBytesHeader(msg, headerToFind) {\n return await this._findHeader(msg, headerToFind);\n }\n\n /**\n * \n */\n async _messageGetConnId(msg) {\n let results = await this._findHeader(msg, ZitiEdgeProtocol.header_id.ConnId);\n throwIf(results == undefined, formatMessage('No ConnId header found'));\n\n var length = results.data.length;\n let buffer = Buffer.from(results.data);\n var connId = buffer.readUIntLE(0, length);\n\n return connId;\n }\n\n getConnection(id) {\n return this._connections._getConnection(id);\n }\n\n\n getSocket() {\n return this._socket;\n }\n setSocket(socket) {\n this._socket = socket;\n }\n getDataCallback() {\n return this._dataCallback;\n }\n setDataCallback(fn) {\n this._dataCallback = fn;\n }\n\n // getEncrypted() {\n // return this._encrypted;\n // }\n // setEncrypted(encrypted) {\n // this._encrypted = encrypted;\n // }\n\n getCryptoEstablishComplete() {\n return this._cryptoEstablishComplete;\n }\n setCryptoEstablishComplete(complete) {\n this._cryptoEstablishComplete = complete;\n }\n\n getKeypair() {\n return this._keypair;\n }\n setKeypair(keypair) {\n this._keypair = keypair;\n }\n\n getSharedRx() {\n return this._sharedRx;\n }\n setSharedRx(sharedRx) {\n this._sharedRx = sharedRx;\n }\n\n getSharedTx() {\n return this._sharedTx;\n }\n setSharedTx(sharedTx) {\n this._sharedTx = sharedTx;\n }\n\n getCrypt_o() {\n return this._crypt_o;\n }\n setCrypt_o(crypt_o) {\n this._crypt_o = crypt_o;\n }\n\n getCrypt_i() {\n return this._crypt_i;\n }\n setCrypt_i(crypt_i) {\n this._crypt_i = crypt_i;\n }\n\n}\n\n// Export class\nexport {\n ZitiChannel\n}", "dangerousExampleEn": "1. \nLine 3: A debug code is remaining.", "safeExampleEn": "1. \nLine 3: Remove the code used for debugging.", "contexts": [{"lineNo": 166, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "166"}}, {"lineNo": 167, "eventType": "sink", "messageKey": "jschk.LEFTOVER_DEBUG_CODE.TOBE.JS.defect", "params": {}}]}} {"id": "a7b00082990d1b58f5916d29aea121473b9a581c92569fb7ac6d78c7ac38c6ee", "license": {"spdx": ["MIT"], "repo": "pip-services-social/pip-services-comments-dart", "path": "obj/src/persistence/CommentsMemoryPersistence.js", "repo_head_hexsha": "78713e9495fbe964022763a3ca86f08fc99d2e75", "stack_hexsha": "d03cf2fe383545090499cb4e9fbd2fd4caa07466", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Leftover debug code", "issueDescriptionEn": "The Leftover debug code checker finds debug code that remains not removed.\nDebug code may contain parts that output sensitive information or allow control over the system. If the program is deployed with debug code remaining, attackers may bypass an authentication process or access restricted information.\nRemove all debug code before deploying the application.", "issueLineNumber": 63, "entireCode": "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.CommentsMemoryPersistence = void 0;\nlet _ = require('lodash');\nconst pip_services3_commons_node_1 = require(\"pip-services3-commons-node\");\nconst pip_services3_data_node_1 = require(\"pip-services3-data-node\");\nclass CommentsMemoryPersistence extends pip_services3_data_node_1.IdentifiableMemoryPersistence {\n constructor() {\n super();\n }\n composeFilter(filter) {\n filter = filter || new pip_services3_commons_node_1.FilterParams();\n let ref_id = filter.getAsNullableString('ref_id');\n let ref_type = filter.getAsNullableString('ref_type');\n let parent_id = filter.getAsNullableString('parent_id');\n let parent_ids = filter.getAsObject('parent_ids');\n let creator_id = filter.getAsNullableString('creator_id');\n let time_from = filter.getAsNullableDateTime('time_from');\n let time_to = filter.getAsNullableDateTime('time_to');\n let empty_parents = filter.getAsBooleanWithDefault('empty_parents', false);\n let deleted = filter.getAsNullableBoolean('deleted');\n let comment_state = filter.getAsNullableString('comment_state');\n if (_.isString(parent_ids))\n parent_ids = parent_ids.split(',');\n if (!_.isArray(parent_ids))\n parent_ids = null;\n return (item) => {\n if (ref_id && (item.refs == null || item.refs.map(x => x.id).indexOf(ref_id) < 0))\n return false;\n if (ref_type && (item.refs == null || item.refs.map(x => x.type).indexOf(ref_type) < 0))\n return false;\n if (parent_id && (item.parent_ids == null || item.parent_ids.indexOf(parent_id) < 0))\n return false;\n if (parent_ids && (item.parent_ids == null || !parent_ids.some(r => item.parent_ids.includes(r) == true)))\n return false;\n if (empty_parents && item.parent_ids && item.parent_ids.length > 0)\n return false;\n if (creator_id && comment_state) {\n if (item.creator_id != creator_id && item.comment_state != comment_state)\n return false;\n }\n else {\n if (creator_id && item.creator_id != creator_id)\n return false;\n if (comment_state && item.comment_state != comment_state)\n return false;\n }\n if (deleted != null && item.deleted != deleted)\n return false;\n if (time_from && (item.create_time == null || pip_services3_commons_node_1.DateTimeConverter.toNullableDateTime(item.create_time) < time_from))\n return false;\n if (time_to && (item.create_time == null || pip_services3_commons_node_1.DateTimeConverter.toNullableDateTime(item.create_time) > time_to))\n return false;\n return true;\n };\n }\n getPageByFilter(correlationId, filter, paging, callback) {\n super.getPageByFilter(correlationId, this.composeFilter(filter), paging, null, null, callback);\n }\n getOneById(correlationId, id, callback) {\n let item = _.find(this._items, (item) => item.id == id);\n if (item != null)\n this._logger.trace(correlationId, \"Found comment by %s\", id);\n else\n this._logger.trace(correlationId, \"Cannot find comment by %s\", id);\n callback(null, item);\n }\n create(correlationId, comment, callback) {\n super.create(null, comment, (err, item) => {\n if (item != null)\n this._logger.trace(correlationId, \"Create comment by %s\", comment);\n else\n this._logger.trace(correlationId, \"Cannot create key by %s\", comment);\n callback(err, item);\n });\n }\n increment(correlationId, id, callback) {\n this.getOneById(correlationId, id, (err, item) => {\n var _a;\n if (err) {\n if (callback)\n callback(err, item);\n }\n if (item) {\n item.children_counter = ((_a = item.children_counter) !== null && _a !== void 0 ? _a : 0) + 1;\n this.update(correlationId, item, callback);\n }\n else {\n callback(err, item);\n }\n });\n }\n decrement(correlationId, id, callback) {\n this.getOneById(correlationId, id, (err, item) => {\n var _a;\n if (err) {\n if (callback)\n callback(err, item);\n }\n if (item) {\n item.children_counter = ((_a = item.children_counter) !== null && _a !== void 0 ? _a : 0) - 1;\n this.update(correlationId, item, callback);\n }\n else {\n callback(err, item);\n }\n });\n }\n addMeme(correlationId, id, creator_id, meme_type, callback) {\n let item = _.find(this._items, item => item.id == id);\n if (item == null) {\n this._logger.trace(correlationId, \"Item %s was not found\", id);\n callback(null, null);\n return;\n }\n if (!item.memes) {\n item.memes = new Array();\n }\n let memes = item.memes.filter((item) => { return item.type == meme_type; });\n if (memes.length > 0) {\n if (memes[0].creator_ids && !memes[0].creator_ids.includes(creator_id)) {\n memes[0].count += 1;\n memes[0].creator_ids.push(creator_id);\n }\n else {\n let err = new pip_services3_commons_node_1.InternalException(correlationId, 'ALREADY_EXIST', 'User is already add meme this type').withDetails(\"creator_id\", creator_id)\n .withDetails(\"meme_type\", meme_type)\n .withDetails(\"meme_id\", item.id);\n callback(err, null);\n return;\n }\n }\n else {\n let meme = {\n type: meme_type,\n count: 1,\n creator_ids: [creator_id]\n };\n item.memes.push(meme);\n }\n this._logger.trace(correlationId, \"Updated state item %s\", item.id);\n this.save(correlationId, (err) => {\n callback(err, item);\n });\n }\n removeMeme(correlationId, id, creator_id, meme_type, callback) {\n let item = _.find(this._items, item => item.id == id);\n if (item == null) {\n this._logger.trace(correlationId, \"Item %s was not found\", id);\n callback(null, null);\n return;\n }\n if (!item.memes) {\n item.memes = new Array();\n }\n let memes = item.memes.filter((item) => { return item.type == meme_type; });\n if (memes.length > 0) {\n if (memes[0].creator_ids && memes[0].creator_ids.includes(creator_id)) {\n memes[0].count -= 1;\n let index = memes[0].creator_ids.indexOf(creator_id);\n memes[0].creator_ids.splice(index, 1);\n }\n else {\n let err = new pip_services3_commons_node_1.NotFoundException(correlationId, 'NOT_FOUND', 'Meme with this type not found for this user').withDetails(\"creator_id\", creator_id)\n .withDetails(\"meme_type\", meme_type)\n .withDetails(\"meme_id\", item.id);\n callback(err, null);\n return;\n }\n }\n else {\n let err = new pip_services3_commons_node_1.NotFoundException(correlationId, 'NOT_FOUND', 'Meme with this type not found for this user').withDetails(\"creator_id\", creator_id)\n .withDetails(\"meme_type\", meme_type)\n .withDetails(\"meme_id\", item.id);\n callback(err, null);\n return;\n }\n this._logger.trace(correlationId, \"Updated state item %s\", item.id);\n this.save(correlationId, (err) => {\n callback(err, item);\n });\n }\n updateState(correlationId, id, state, callback) {\n let item = _.find(this._items, item => item.id == id);\n if (item == null) {\n this._logger.trace(correlationId, \"Item %s was not found\", id);\n callback(null, null);\n return;\n }\n item.comment_state = state;\n this._logger.trace(correlationId, \"Updated state item %s\", item.id);\n this.save(correlationId, (err) => {\n callback(err, item);\n });\n }\n markAsDeleted(correlationId, id, callback) {\n let item = _.find(this._items, item => item.id == id);\n if (item == null) {\n this._logger.trace(correlationId, \"Item %s was not found\", id);\n callback(null, null);\n return;\n }\n item.deleted = true;\n this._logger.trace(correlationId, \"Item %s mark as deleted\", item.id);\n this.save(correlationId, (err) => {\n callback(err, item);\n });\n }\n}\nexports.CommentsMemoryPersistence = CommentsMemoryPersistence;\n//# sourceMappingURL=CommentsMemoryPersistence.js.map", "dangerousExampleEn": "1. \nLine 3: A debug code is remaining.", "safeExampleEn": "1. \nLine 3: Remove the code used for debugging.", "contexts": [{"lineNo": 62, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "63"}}, {"lineNo": 63, "eventType": "sink", "messageKey": "jschk.LEFTOVER_DEBUG_CODE.TOBE.JS.defect", "params": {}}]}} {"id": "b8cf8fd552f6375fa3d24ba173b2c4e5dea209b3047782952921960ef3382cfb", "license": {"spdx": ["MIT"], "repo": "dg711/feedr", "path": "routes/getfeed.js", "repo_head_hexsha": "4c09bfdbe9a5e47fb820a22cc4f38545e3d12c26", "stack_hexsha": "e154299db5ef5687e176e9330553cec4728595d2", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Leftover debug code", "issueDescriptionEn": "The Leftover debug code checker finds debug code that remains not removed.\nDebug code may contain parts that output sensitive information or allow control over the system. If the program is deployed with debug code remaining, attackers may bypass an authentication process or access restricted information.\nRemove all debug code before deploying the application.", "issueLineNumber": 20, "entireCode": "var elasticsearch = require('elasticsearch');\nvar feedmap = require('../feedmap.js');\n\nvar express = require('express');\nvar router = express.Router();\nvar timeSince = require('../utilities.js').timeSince;\nvar HTMLParser = require('fast-html-parser');\n\nvar client = new elasticsearch.Client( {\n hosts: [\n 'http://localhost:9200/'\n ]\n});\n\nclient.ping({\n // ping usually has a 3000ms timeout\n requestTimeout: 1000\n}, function (error) {\n if (error) {\n console.trace('Elasticsearch cluster is down!');\n process.exit();\n } else {\n console.log('Elasticsearch connnection is healthy.');\n }\n});\n\n\n\nfunction getSrcFromAttrString(str){\n var attrArray = str.split(\" \");\n var o = {};\n attrArray.forEach(function(e){\n e = e.split(\"=\");\n if (e[0] == 'src') o.src = e[1].trim().substring(1, e[1].length - 2);\n });\n\n return o.src;\n}\n\nrouter.get('/:from', function(request, response) {\n\n\n var pageNum = request.params.from > 0 ? request.params.from : 1;\n var perPage = 12; //request.params.per_page;\n var userQuery = request.query.query_string;\n var aliasoptions = request.query.aliases ? request.query.aliases : feedmap.keys();\n if (typeof aliasoptions === \"string\") aliasoptions = [aliasoptions];\n console.log(aliasoptions);\n function queryelasticsearch(q_index, userQuery, aliases, fromPage, pagesize) {\n\n var searchParams;\n\n if (userQuery) {\n console.log(\"if\");\n searchParams = {\n index: q_index,\n from: (fromPage - 1) * pagesize,\n size: pagesize,\n body: {\n query : {\n filtered : {\n filter : {\n terms : {\n alias : aliases\n }\n },\n query : {\n match : {\n title : {\n query : userQuery,\n operator : 'or'\n }\n }\n }\n }\n },\n sort : [\n {\n \"published\" : {\n order : \"desc\"\n }\n }\n ]\n }\n };\n\n\n } else {\n searchParams = {\n index: q_index,\n from: (fromPage - 1) * pagesize,\n size: pagesize,\n body: {\n query : {\n filtered : {\n filter : {\n terms : {\n alias : aliases\n }\n },\n query : {\n match_all : {}\n }\n }\n },\n sort : [\n {\n \"published\" : {\n order : \"desc\"\n }\n }\n ]\n }\n };\n }\n\n\n client.search(searchParams, function (err, res) {\n\n if (err) {\n // handle error\n console.log(\"error occured :\", err);\n throw err;\n }\n\n\n var results = res.hits.hits.map(function (item) {\n\n\n\n var articleDate = timeSince(new Date(item._source.published));\n\n return {\n id : item._id,\n title : item._source.title,\n date : articleDate + \" ago\",\n feedalias : item._source.alias\n };\n });\n\n response.send({\n feeds: results,\n page: fromPage,\n pages: Math.ceil(res.hits.total / pagesize)\n });\n });\n\n}\n\n queryelasticsearch('reader', userQuery, aliasoptions, pageNum, perPage);\n\n});\n\nmodule.exports = router;", "dangerousExampleEn": "1. \nLine 3: A debug code is remaining.", "safeExampleEn": "1. \nLine 3: Remove the code used for debugging.", "contexts": [{"lineNo": 19, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "19"}}, {"lineNo": 20, "eventType": "sink", "messageKey": "jschk.LEFTOVER_DEBUG_CODE.TOBE.JS.defect", "params": {}}]}} {"id": "bcb8f4f5940d8c25fb904930d6ef8db54ebae2a7f1bcc13c97bc0bc62d5d545b", "license": {"spdx": ["MIT"], "repo": "bassoGeorge/husky-talisman", "path": "src/index.js", "repo_head_hexsha": "798237353f9d3bcaa9a039f380a002a5ed10f58f", "stack_hexsha": "974b83270432c46fb025324c1beba03e3e9eec0e", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Leftover debug code", "issueDescriptionEn": "The Leftover debug code checker finds debug code that remains not removed.\nDebug code may contain parts that output sensitive information or allow control over the system. If the program is deployed with debug code remaining, attackers may bypass an authentication process or access restricted information.\nRemove all debug code before deploying the application.", "issueLineNumber": 26, "entireCode": "import { install } from './install'\nimport { fileExists as installCheck } from './file-exists'\nimport { makeExecutable } from './make-executable'\nimport { matchChecksum } from './match-checksum'\nimport { runner } from './runner'\nimport { writeFile } from './write-file'\n\nimport {\n ACCEPTABLE_INPUT,\n MESSAGES,\n TALISMAN_VERSION,\n VERSION_LOG_PATH\n} from './config'\n\nconst { DEBUG } = process.env\n\nconst runInstaller = async () => {\n console.log('husky-talisman >', ACCEPTABLE_INPUT.INSTALL)\n\n try {\n await install(TALISMAN_VERSION)\n await matchChecksum()\n await makeExecutable()\n await writeFile(VERSION_LOG_PATH, TALISMAN_VERSION)\n } catch (e) {\n if (DEBUG) { console.trace(e) }\n\n console.log('husky-talisman >', MESSAGES.INSTALL_ERROR)\n\n process.exit(1)\n }\n}\n\n/**\n * Will be called by the CLI wrapper provided by @pika/plugin-simple-bin\n */\nexport async function run (args) {\n const argument = args[2]\n try {\n const isAlreadyInstalled = await installCheck(VERSION_LOG_PATH)\n\n if (!isAlreadyInstalled) {\n await runInstaller(argument)\n }\n\n switch (argument) {\n case ACCEPTABLE_INPUT.PRE_COMMIT:\n console.log('husky-talisman >', ACCEPTABLE_INPUT.PRE_COMMIT)\n await runner(argument)\n\n break\n\n case ACCEPTABLE_INPUT.PRE_PUSH:\n console.log('husky-talisman >', ACCEPTABLE_INPUT.PRE_PUSH)\n await runner(argument)\n\n break\n\n case ACCEPTABLE_INPUT.INSTALL:\n await runInstaller(argument)\n break\n\n default:\n console.log(MESSAGES.BAD_ARGUMENT)\n Object.values(ACCEPTABLE_INPUT)\n .map(i => console.log(i))\n }\n } catch (e) {\n if (DEBUG) { console.trace(e) }\n\n if (!e.exitCode) {\n console.log('husky-talisman >', MESSAGES.FAILED)\n }\n\n process.exit(1)\n }\n\n process.exit(0)\n}", "dangerousExampleEn": "1. \nLine 3: A debug code is remaining.", "safeExampleEn": "1. \nLine 3: Remove the code used for debugging.", "contexts": [{"lineNo": 26, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "26"}}, {"lineNo": 26, "eventType": "sink", "messageKey": "jschk.LEFTOVER_DEBUG_CODE.TOBE.JS.defect", "params": {}}]}} {"id": "47af9fafcff21e3fefbc4b43c8a5bcfccd3f859f9c612aa72c4a08fda11c62c8", "license": {"spdx": ["MIT"], "repo": "radiantmediaplayer/outstream-ads-gallery", "path": "in-article/js/in-article.js", "repo_head_hexsha": "2bffa83ce3fb2d77d525a5d21b3adbb3382c130c", "stack_hexsha": "7ae1e6cb32e6f14c8a12a31e37278f8aeb482960", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Leftover debug code", "issueDescriptionEn": "The Leftover debug code checker finds debug code that remains not removed.\nDebug code may contain parts that output sensitive information or allow control over the system. If the program is deployed with debug code remaining, attackers may bypass an authentication process or access restricted information.\nRemove all debug code before deploying the application.", "issueLineNumber": 45, "entireCode": "/**\n * @license Copyright (c) 2015-2021 Radiant Media Player \n * outstream-ads-gallery | https://github.com/radiantmediaplayer/outstream-ads-gallery\n */\n\n(function () {\n\n 'use strict';\n\n var elementID = 'rmpPlayer';\n var container = document.getElementById(elementID);\n\n if (!container) {\n return;\n }\n\n var settings = {\n licenseKey: 'your-license-key',\n width: 640,\n height: 360,\n skin: 'outstream',\n backgroundColor: 'DDDDDD',\n ads: true,\n // by default we use Google IMA but we can also use rmp-vast for outstream ads\n // adParser: 'rmp-vast',\n // when player comes into view, it will autoplay ...\n // also player is automatically played/paused when it becomes in/out of view with this option\n viewablePlayPause: true,\n // ... well muted autoplay to avoid Chrome/Safari to block autoplay with sound \n // and to comply with the coalition for better ads\n muted: true,\n adOutStream: true,\n adTagUrl: 'https://www.radiantmediaplayer.com/vast/tags/inline-linear.xml',\n // we use client-side waterfalling in this case (optional)\n adTagWaterfall: [\n 'https://www.radiantmediaplayer.com/vast/tags/inline-linear-1.xml'\n ]\n };\n\n // new player instance\n var rmp = new RadiantMP(elementID);\n\n var _trace = function (input) {\n if (window.console.trace && input) {\n window.console.trace(input);\n }\n };\n\n // when destroy method finishes we clear listeners and remove player from DOM\n var _onDestroyCompleted = function () {\n container.removeEventListener('destroycompleted', _onDestroyCompleted);\n var parent = container.parentNode;\n if (parent) {\n try {\n parent.removeChild(container);\n } catch (e) {\n _trace(e);\n }\n }\n };\n\n // player needs be removed from page \n // first we need to destroy it\n var _removePlayer = function () {\n container.removeEventListener('autoplayfailure', _removePlayer);\n container.addEventListener('destroycompleted', _onDestroyCompleted);\n rmp.destroy();\n };\n\n // if Google IMA has been blocked by an ad-blocker or failed to load\n // we need to remove the player from DOM\n container.addEventListener('ready', function () {\n if (rmp.getAdParserBlocked()) {\n _removePlayer();\n return;\n }\n });\n\n // on autoplay failure we remove player from DOM\n container.addEventListener('autoplayfailure', _removePlayer);\n\n // init player after wiring events\n rmp.init(settings);\n\n})();", "dangerousExampleEn": "1. \nLine 3: A debug code is remaining.", "safeExampleEn": "1. \nLine 3: Remove the code used for debugging.", "contexts": [{"lineNo": 44, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "44"}}, {"lineNo": 45, "eventType": "sink", "messageKey": "jschk.LEFTOVER_DEBUG_CODE.TOBE.JS.defect", "params": {}}]}} {"id": "a53177bccbddd6606d723adcab3c2fbb2b6c9f728c689645174bb15b9b9f485f", "license": {"spdx": ["BSD-2-Clause"], "repo": "bollig/tributary", "path": "static/tributary.js", "repo_head_hexsha": "a0659243fbf3396eb5aa52312e7cf22ebea8c1ee", "stack_hexsha": "b3b3443dee5cf7cb0701c5e543a29a3b45aebee7", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Leftover debug code", "issueDescriptionEn": "The Leftover debug code checker finds debug code that remains not removed.\nDebug code may contain parts that output sensitive information or allow control over the system. If the program is deployed with debug code remaining, attackers may bypass an authentication process or access restricted information.\nRemove all debug code before deploying the application.", "issueLineNumber": 19, "entireCode": "tributary.Tributary = Backbone.Model.extend({\n defaults: {\n code: \"\",\n coffee: false,\n filename: \"inlet.js\",\n endpoint: \"tributary\"\n },\n binder: function() {\n this.on(\"code\", this.newcode);\n this.on(\"execute\", this.execute);\n this.on(\"error\", this.handle_error);\n },\n initialize: function() {\n this.binder();\n },\n handle_error: function(e) {\n if(tributary.trace) {\n console.log(e);\n console.trace();\n }\n },\n handle_coffee: function() {\n //This checks if coffeescript is being used\n //and returns compiled javascript\n var js = this.get(\"code\");\n if(this.get(\"coffee\")) {\n //compile the coffee\n js = CoffeeScript.compile(js, {\"bare\":true});\n }\n return js;\n },\n execute: function() { \n var js = this.handle_coffee();\n try {\n svg = d3.select(\"svg\");\n //wrap the code in a closure\n var code = \"tributary.initialize = function(g) {\";\n code += js;\n code += \"};\";\n eval(code);\n //trib = window.trib #access global trib object\n //trib_options = window.trib_options #access global trib object\n //tributary.initialize(d3.select(\"svg.tributary_svg\"))\n } catch (e) {\n this.trigger(\"error\", e);\n return false;\n }\n \n //we don't want it to nuke the svg if there is an error\n try {\n //for the datGUI stuff\n window.trib = {}; //reset global trib object\n window.trib_options = {}; //reset global trib_options object\n trib = window.trib;\n trib_options = window.trib_options;\n $(\"svg.tributary_svg\").empty();\n tributary.initialize(d3.select(\"svg.tributary_svg\"));\n } catch (er) {\n this.trigger(\"error\", er);\n return false;\n }\n this.trigger(\"noerror\");\n\n return true;\n },\n newcode: function(code) {\n //save the code in the model\n this.set({code:code});\n this.execute();\n //TODO: store code in local storage\n\n return true;\n }\n});\n\ntributary.Config = Backbone.Model.extend({\n defaults: {\n editor_editor: {\n coffee: false,\n vim: false,\n emacs: false,\n width: 600,\n height: 300,\n hide: false\n }\n },\n});\n\ntributary.JSON = Backbone.Model.extend({\n //JSON model is like the base tributary class, but its for json\n //we use \"code\" to store and catch events to match with the tributary\n //class so we don't need to separate logic for the editors (same functionality anyway)\n //hmm.. wonder if it should just extend Tributary...\n defaults: {\n name: \"config.json\",\n code: \"{}\",\n },\n binder: function() {\n this.on(\"code\", this.newjson);\n this.on(\"execute\", this.execute);\n this.on(\"error\", this.handle_error);\n },\n initialize: function() {\n this.binder();\n },\n handle_error: function(e) {\n if(tributary.trace) {\n console.log(e);\n console.trace();\n }\n },\n\n execute: function() { \n try {\n var json = JSON.parse(this.get(\"code\"));\n tributary[this.get(\"name\")] = json;\n } catch (e) {\n this.trigger(\"error\", e);\n return false;\n }\n this.trigger(\"noerror\");\n\n return true;\n },\n newjson: function(json) {\n //save the code in the model\n this.set({code:json});\n this.execute();\n //TODO: store code in local storage\n\n return true;\n }\n\n});\n\n\ntributary.TributaryView = Backbone.View.extend({\n check_date: true,\n initialize: function() {\n this.endpoint = this.options.endpoint || \"tributary\";\n this.model.set(\"endpoint\", this.endpoint);\n //TODO: this should all be in render() \n //but we assume that the #editor div is present when this class is\n //instanciated. move it once the code is on more solid ground\n\n //we will be using \"that\" a lot. it would have been fun to use \"dat\" instead.\n var that = this;\n\n\n //we will manage several editors\n this.editor = {};\n this.editor_handle = {};\n //we keep an array of json models\n this.jsons = [];\n \n /////////////////////////////////////\n //Here we setup all the model stuff\n //really this should go in the initialization... and all the gui should follow\n /////////////////////////\n var cachebust = \"?cachebust=\" + Math.random() * 4242424242424242;\n if(this.model.get(\"gist\") && this.model.get(\"gist\") !== \"None\") {\n //setup ui related to the gist\n d3.json('https://api.github.com/gists/' + this.model.get(\"gist\") + cachebust, function(data) {\n //console.log(\"GIST!\", data);\n if(data.user === null || data.user === undefined) {\n data.user = {\n login: \"anon\",\n url: \"\",\n userid: -1\n };\n that.loggedin = false;\n } else {\n that.loggedin = true;\n }\n that.gist = data;\n\n /*\n //load markdown files here\n // _.md\n var markdown;\n try {\n markdown = data.files[\"_.md\"];\n } catch (e) {\n markdown = false;\n }\n if(markdown) {\n //console.log(\"yay! fix the URL\", markdown, that.gist, window.location.host)\n try {\n that.markdown = \"
    [See Previous Inlet](http://\" + window.location.host + \"/\" + that.endpoint + \"/\" + that.gist.id + \")\"\n + \" [ [Gist](\" + that.gist.html_url + \") ]\"\n\n } catch (e){\n that.markdown = \"Unknown Error Recovering Gist History\"\n }\n } else {\n that.markdown = \"No Previous Gist\"\n }\n */ \n\n //load optional files here\n //config.json\n var config;\n try {\n config = data.files[\"config.json\"];\n } catch (e) {\n config = false;\n }\n if(config) {\n //console.log(\"yay!\", config)\n try {\n that.config = new tributary.Config(JSON.parse(config.content))\n } catch (e){\n that.config = new tributary.Config();\n }\n } else {\n that.config = new tributary.Config();\n }\n\n //TODO: do this cleaner? config should save what endpoint generated\n that.config.set(\"endpoint\", that.model.get(\"endpoint\"));\n\n //\n //json files\n var files = _.keys(data.files);\n //console.log(\"files\", files)\n var fsplit, json, i = 0, jsonid;\n files.forEach(function(f) {\n fsplit = f.split(\".\"); \n if(fsplit[fsplit.length-1] === \"json\" && f !== \"config.json\") {\n //found us a ripe json file!\n //setup the JSON model to store it\n //json = new tributary.JSON({\"name\":fsplit[0], \"code\":data.files[f].content})\n json = new tributary.JSON({\"filename\":f,\"name\":fsplit[0], \"code\":data.files[f].content})\n //keep track of this json\n that.jsons.push(json);\n \n jsonid = \"json\" + i;\n //this seems weird that we have to set up the config manually\n if(!that.config.get(\"editor_\" + jsonid)) {\n that.config.set(\"editor_\" + jsonid, {\n vim: that.config.get(\"editor_editor\").vim,\n emacs: that.config.get(\"editor_editor\").emacs,\n width: 600,\n height: 300,\n hide: false\n });\n }\n\n that.setup_editor(jsonid, json, {coffee_checkbox: false});\n json.execute();\n json.on(\"noerror\", function() {\n that.model.execute();\n });\n i++;\n }\n });\n\n\n //set the code\n var code_file = data.files[that.model.get(\"filename\")];\n if(code_file)\n {\n that.model.set(\"code\", code_file.content)\n }\n\n that.init_gui();\n //for the code we setup special code editor still\n that.code_editor = that.setup_editor(\"editor\", that.model);\n //it hooks up to dat gui\n that.make_datgui();\n\n //yay all done, lets run the code we loaded in\n that.model.execute();\n that.model.trigger(\"gotcode\");\n\n });\n } else {\n //setup empty config\n that.config = new tributary.Config();\n // that.markdown = \"No parent Inlet\"\n \n that.init_gui();\n that.setup_editor(\"editor\", this.model);\n this.model.execute();\n this.model.trigger(\"gotcode\");\n }\n\n\n //datgui things \n this.controls = {};\n //keep track of whether or not datGui is being used\n this.dating = false;\n this.gui = new dat.GUI();\n\n $('div.dg').toggle(false);\n $('div.dg').css(\"z-index\", 1);\n $('div.dg').attr(\"id\", \"datgui\"); //don't know why i can't style dg with classes...\n this.make_datgui = function() {\n if(_.keys(trib).length === 0) {\n //we don't have anything to show in datgui, lets hide it\n $('div.dg').toggle(false);\n } else {\n $('div.dg').toggle(true);\n }\n //we only need to remake the ui if we are not using it\n if(!that.dating) {\n //reset everything\n that.gui.destroy();\n that.gui = new dat.GUI();\n var key;\n _.each(_.keys(trib), function(key) {\n if(that.controls[key] !== undefined) {\n delete that.controls[key];\n }\n //console.log(key, trib[key])\n\n if(trib_options !== undefined && trib_options[key] !== undefined) {\n that.controls[key] = that.gui.add(trib, key, trib_options[key].min, trib_options[key].max);\n } else {\n //automatically make the range for the slider since its not provided\n val = trib[key];\n if(typeof(val) === \"number\") {\n var min, max, slider_min, slider_max;\n if(val === 0) {\n min = -100;\n max = 100;\n } else {\n min = -10 * val;\n max = 10 * val;\n slider_min = _.min([min, max]);\n slider_max = _.max([min, max]);\n }\n //console.log(\"min max\", slider_min, slider_max)\n that.controls[key] = that.gui.add(trib, key, slider_min, slider_max);\n }\n }\n\n that.controls[key].onChange(function(key) {\n return function(value) {\n //console.log(\"args\", arguments)\n that.dating = true;\n //search for this in the code and replace\n //number regex taken from d3 source\n //var txt = new RegExp(\"trib\\.\" + key + \"\\\\s*=(\\\\s*)[-+]?(?:\\\\d+\\\\.?\\\\d*|\\\\.?\\\\d+)(?:[eE][-+]?\\\\d+)?\");\n var txt = new RegExp(\"trib.\" + key + \"\\\\s*=(\\\\s*)[-+]?(?:\\\\d+\\\\.?\\\\d*|\\\\.?\\\\d+)(?:[eE][-+]?\\\\d+)?\");\n //console.log(\"TXT\", txt)\n var cursor = that.code_editor.getSearchCursor(txt);\n if(cursor.findNext()) {\n var newtxt = \"trib.\" + key + \" = \" + value;\n cursor.replace(newtxt);\n }\n };\n }(key));\n });\n }\n };\n \n\n //TODO: make these work for each of the editors rather than just the code editor\n\n //------------------------------------\n //Drop file functions\n //------------------------------------\n var _loadFile = function() {\n var reader = new FileReader();\n // register an onload callback that gets fired after the reader has finished reading the file\n if(!that.check_date || that.file.lastModifiedDate > that.code_last_modified) {\n console.log(\"read file!\");\n reader.onload = function() {\n //@executeCode({reader: reader})\n that.code_editor.setValue(reader.result);\n };\n that.code_last_modified = that.file.lastModifiedDate;\n reader.readAsText(that.file);\n }\n };\n var _dragOver = function(ev) {\n //Called when a user drags a file over the #drop_file div\n ev.stopPropagation();\n ev.preventDefault();\n ev.dataTransfer.dropEffect = 'copy';\n //$('#drop_file').addClass('drop_file_active');\n };\n var _fileDrop = function(ev) {\n ev.stopPropagation();\n ev.preventDefault();\n that.file = ev.dataTransfer.files[0];\n that.code_last_modified = new Date(0,0,0);\n _loadFile();\n };\n\n\n //Hook up drag and drop for code file\n $('body')[0].addEventListener('dragover', _dragOver, false);\n $('body')[0].addEventListener('drop', _fileDrop, false);\n\n //Setup loop to check for file date\n this.code_last_modified = new Date(0,0,0);\n this.past = new Date();\n that = this;\n d3.timer(function() {\n if(new Date() - that.past > 300) {\n if(that.file !== undefined) {\n _loadFile();\n }\n that.past = new Date();\n }\n return false;\n });\n\n this.model.on(\"noerror\", function() {\n that.make_datgui();\n //ugh, need to make sure datgui doesn't \"overwrite\" itself\n setTimeout(function() {\n that.dating = false;\n }, 100);\n });\n\n },\n init_gui: function() {\n var that = this;\n //Setup the gui elements for this page\n //Setup tweet link\n /*\n $('#tweet_this').append(\"tweet this\");\n $('#tweetPanel').on(\"click\", function(e) {\n that.save_gist(function(newurl, newgist) {\n var tweetlink = \"http://twitter.com/home/?status=See my latest %23tributary here \"+\"http://mainstem.org\" + newurl;\n window.location = tweetlink;\n //window.open(tweetlink, 'twitte')\n });\n });\n */\n\n //Setup the save panel\n $('#savePanel').on('click', function(e) {\n d3.select(\"#syncing\").style(\"display\", \"block\");\n that.save_gist(\"save\", function(newurl, newgist) {\n window.location = newurl;\n });\n });\n $('#forkPanel').on('click', function(e) {\n d3.select(\"#syncing\").style(\"display\", \"block\");\n that.save_gist(\"fork\", function(newurl, newgist) {\n window.location = newurl;\n });\n });\n //Setup the login button\n $('#loginPanel').on('click', function(e) {\n that.login_gist(tributary.loggedin, function(newurl, newgist) {\n window.location = newurl;\n }); \n /* This has no effect. Need to find the source of bug that enables Save button after logging in once. \n if (tributary.loggedin) {\n $('#savePanel').attr(\"disabled\",\"true\");\n $(\"#savePanel\").attr(\"class\", \"minimal_off\");\n }*/\n });\n\n if(this.gist) {\n var gist_uid = this.gist.user.userid;\n /* TODO: setup editing of description as well as a save button\n if(gist_uid === tributary.userid) {\n //the loggedin user owns this gist\n }\n */\n //make the description and attribution\n var info_string = '\"' + this.gist.description + '\" by ';\n if(this.gist.user.url === \"\") {\n info_string += this.gist.user.login;\n } else {\n info_string += '' + this.gist.user.login + '';\n }\n\n $('#gist_info').html(info_string);\n\n if(this.gist.user.id !== tributary.userid) {\n $(\"#savePanel\").attr(\"disabled\", \"true\");\n $(\"#savePanel\").attr(\"class\", \"off\");\n }\n }\n\t \n //if the user is not logged in, disable save\n if(isNaN(tributary.userid)) {\n $(\"#savePanel\").attr(\"disabled\", \"true\");\n $(\"#savePanel\").attr(\"class\", \"off\");\n //$(\"#forkPanel\").attr(\"disabled\", \"true\");\n //$(\"#forkPanel\").attr(\"class\", \"minimal_off\");\n }\n },\n\n setup_editor: function(editor_id, model, options) {\n var that = this;\n\n if(!options) {\n options = {\"coffee_checkbox\": true};\n }\n var coffee_checkbox = options.coffee_checkbox;\n\n\n //config id, how we reference this editor in the config\n var cid = \"editor_\" + editor_id;\n\n //this could probably be done better with templating\n //add the editor element to the page\n var editor_sel = d3.select(\"#page\")\n .append(\"div\")\n .classed(\"editor\", true)\n .attr(\"id\", editor_id);\n var topbar = editor_sel.append(\"div\")\n .classed(\"editor-topbar\", true)\n\n topbar.append(\"button\")\n .text(\"Hide\")\n .classed(\"button_on\", true)\n .classed(\"hidebutton\", true)\n\n //CoffeeScript\n if(coffee_checkbox) {\n topbar.append(\"input\")\n .attr(\"type\", \"checkbox\")\n .attr(\"class\", \"coffee_check\");\n topbar.append(\"span\")\n .text(\"CoffeeScript\");\n }\n //setup the vim and emacs checkboxs\n topbar.append(\"input\")\n .attr(\"type\", \"checkbox\")\n .attr(\"class\", \"vim_check\");\n topbar.append(\"span\")\n .text(\"vim\");\n topbar.append(\"input\")\n .attr(\"type\", \"checkbox\")\n .attr(\"class\", \"emacs_check\");\n topbar.append(\"span\")\n .text(\"emacs\");\n\n\n //some stuff we have to do to make sure we don't get into infinite change loops\n //with slider and color picker\n editor_sel.on(\"click\", function() {\n that.sliding = false;\n that.picking = false;\n });\n editor_sel.select(\".CodeMirror\").on(\"click\", function() {\n that.sliding = false;\n that.picking = false;\n });\n\n //CODE SPECIFIC\n var code_editor = CodeMirror(editor_sel.node(), {\n //value: \"function myScript(){return 100;}\\n\",\n mode: \"javascript\",\n theme: \"lesser-dark\",\n lineNumbers: true,\n onChange: function() {\n thisCode = code_editor.getValue();\n model.trigger(\"code\", thisCode);\n }\n });\n\n this.inlet = Inlet(code_editor);\n var code = model.get(\"code\");\n //check if we already have the code\n if(code !== undefined && code !== \"\") {\n code_editor.setValue(code);\n }\n\n /////////////////////////////////////////////////\n\n //Setup editor controls\n //This is like the windowing system for the code editor\n //the configuration for each editor is stored in the this.editor object\n //which gets saved to the config\n var editor_el = $(\"#\" + editor_id);\n this.editor[editor_id] = this.config.get(cid);\n var editor = this.editor[editor_id];\n\n editor_el.css('width', editor.width);\n editor_el.css('height', editor.height);\n editor_el.find('.CodeMirror-scroll').css('height', editor.height + \"px\");\n editor_el.find('.CodeMirror-gutter').css('height', editor.height + \"px\");\n\n //we store the current width and height in these variables\n //to be able to calculate the resize position from the original w/h\n var ew = editor.width;\n var eh = editor.height;\n\n var handle_offset = {x: -25, y: 20};\n\n var editor_drag = d3.behavior.drag()\n .on(\"drag\", function(d,i) {\n var dx = d3.event.dx;\n var dy = d3.event.dy;\n d.x -= dx;\n d.y -= dy;\n //don't use latest editor w/h in calculation\n var neww = ew + d.x;\n var newh = eh + d.y;\n editor_handle.style(\"right\", handle_offset.x + neww + \"px\");\n editor_handle.style(\"bottom\", handle_offset.y + newh + \"px\");\n\n editor_el.css('width', neww + \"px\");\n editor_el.css('height', newh + \"px\");\n editor_el.find('.CodeMirror-scroll').css('height', newh + \"px\");\n editor_el.find('.CodeMirror-gutter').css('height', newh + \"px\");\n \n //we store the width height only for future config use\n editor.width = neww;\n editor.height = newh;\n\n that.config.set(cid, editor);\n });\n \n var handle_data = {\n x: 0,\n y: 0\n };\n\n //TODO: update editor handle\n //this editor handle is both indicator and drags around the editor\n //should make the draggin part be something invisible over the gutter (line numbers)\n //and have the indicator somewhere else\n this.editor_handle[editor_id] = d3.select(\"body\").append(\"div\")\n .attr(\"id\", \"editor_handle_\" + editor_id)\n .data([handle_data])\n .style(\"position\", \"fixed\")\n .style(\"display\", \"block\")\n .style(\"float\", \"left\")\n .style(\"right\", handle_offset.x + editor.width + \"px\")\n .style(\"bottom\", handle_offset.y + editor.height + \"px\")\n .style(\"width\", \"20px\")\n .style(\"height\", \"20px\")\n .style(\"background-color\", \"rgba(50, 50, 50, .4)\")\n .style(\"z-index\", 999)\n .call(editor_drag);\n var editor_handle = this.editor_handle[editor_id];\n\n model.on(\"error\", function() {\n editor_handle.style(\"background-color\", \"rgba(250, 50, 50, .7)\");\n });\n model.on(\"noerror\", function() {\n editor_handle.style(\"background-color\", \"rgba(50, 250, 50, .4)\");\n \n });\n\n //Setup Hide the editor button\n var h_id = \"hideEditor_\" + editor_id\n //setup hide button\n var he = topbar.select(\".hidebutton\");\n //setup show button\n d3.select(\"#hideEditors\").append(\"div\").attr(\"id\", h_id)\n .classed(\"show_editor\", true)\n .text(\"Show \" + model.get(\"filename\"));\n\n var se = $('#' + h_id);\n\n var hide = editor.hide;\n showhide();\n\n\n \n function showhide() {\n editor_el.toggle(!hide);\n $(\"#editor_handle_\" + editor_id).toggle(!hide);\n se.toggle(hide);\n\n /*\n if(hide) {\n he.html(\"Show\");\n } else {\n he.html(\"Hide\");\n }\n */\n }\n \n he.on(\"click\", function(e) {\n hide = !hide;\n editor.hide = hide;\n that.config.set(cid, editor);\n showhide();\n });\n se.on(\"click\", function(e) {\n hide = !hide;\n editor.hide = hide;\n that.config.set(cid, editor);\n showhide();\n });\n\n\n\n\n //TODO: clean up this checkbox related code. lots of redundant\n //checks... \n //setup the coffeescript checkbox (if we want it)\n if(coffee_checkbox) {\n var cs = editor_el.find('.coffee_check');\n\n //set the use of coffeescript depending on the config\n model.set({\"coffee\": editor.coffee});\n cs.attr(\"checked\", editor.coffee);\n\n if(editor.coffee) {\n code_editor.setOption(\"mode\", \"coffeescript\");\n } else {\n code_editor.setOption(\"mode\", \"javascript\");\n }\n\n cs.on(\"change\", function(e) {\n var coffee_on = cs.is(\":checked\");\n model.set({\"coffee\": coffee_on});\n editor.coffee = coffee_on;\n that.config.set(cid, editor);\n if(coffee_on) {\n code_editor.setOption(\"mode\", \"coffeescript\");\n } else {\n code_editor.setOption(\"mode\", \"javascript\");\n }\n model.execute();\n });\n }\n \n var vs = editor_el.find('.vim_check');\n var es = editor_el.find('.emacs_check');\n\n vs.attr(\"checked\", editor.vim);\n es.attr(\"checked\", editor.emacs);\n\n if(editor.vim) {\n code_editor.setOption(\"keyMap\", \"vim\");\n } else if (editor.emacs) {\n code_editor.setOption(\"keyMap\", \"emacs\");\n } else {\n code_editor.setOption(\"keyMap\", \"default\");\n }\n\n vs.on(\"change\", function(e) {\n var vim_on = vs.is(\":checked\");\n editor.vim = vim_on;\n //if vim is turned off, turn off emacs!\n if(vim_on) {\n editor.emacs = !vim_on;\n es.attr(\"checked\", !vim_on);\n }\n that.config.set(cid, editor);\n if(vim_on) {\n code_editor.setOption(\"keyMap\", \"vim\");\n } else {\n code_editor.setOption(\"keyMap\", \"default\");\n }\n });\n //setup the emacs checkbox\n es.on(\"change\", function(e) {\n var emacs_on = es.is(\":checked\");\n editor.emacs = emacs_on;\n //if emacs is turned on, turn off vim!\n if(emacs_on) {\n editor.vim = !emacs_on;\n vs.attr(\"checked\", !emacs_on);\n }\n that.config.set(cid, editor);\n if(emacs_on) {\n code_editor.setOption(\"keyMap\", \"emacs\");\n } else {\n code_editor.setOption(\"keyMap\", \"default\");\n }\n });\n\n\n return code_editor;\n\n },\n save_gist: function(saveorfork, callback) {\n //console.log(\"ENDPOINT\", @endpoint)\n //Save the current code to a public gist\n var oldgist = parseInt(this.model.get(\"gist\"), 10);\n\n //We now assume all tributaries will be saved as inlet.js\n //so this code is a bit redundant, but it might be useful in the future\n //filename = this.model.get(\"filename\");\n //if(filename === \"\"){\n filename = \"inlet.js\";\n //}\n var gist = {\n description: 'just another inlet to tributary',\n public: true,\n files: {}\n };\n\n//console.log(\"code\", this.model, oldgist)\n\n gist.files[filename] = {\n content: this.model.get(\"code\")\n };\n\n this.jsons.forEach(function(j) {\n //gist.files[j.get(\"name\") + \".json\"] = {\n gist.files[j.get(\"filename\")] = {\n content: j.get(\"code\")\n };\n });\n\n// this.mds.forEach(function(j) {\n// gist.files[j.get(\"name\") + \".md\"] = {\n// content: j.get(\"code\")\n // };\n // });\n\n //save config\n gist.files[\"config.json\"] = {\n content: JSON.stringify(this.config.toJSON())\n };\n\n /*\n //save markdown\n gist.files[\"_.md\"] = {\n content: this.markdown\n };\n */\n\n //serialize the current svg and save it to gist\n var node = d3.select(\"svg\").node();\n var svgxml = (new XMLSerializer()).serializeToString(node);\n\n if($.browser.webkit){ \n svgxml = svgxml.replace(/ xlink/g, ' xmlns:xlink');\n svgxml = svgxml.replace(/ href/g, ' xlink:href');\n }\n gist.files[\"inlet.svg\"] = {\n content: svgxml\n };\n\n\n var url;\n if(saveorfork === \"save\") {\n //turn the save button into a saving animation\n /*\n d3.select(\"#saveButton\").style(\"background-image\", \"url(/static/img/ajax-loader.gif)\");\n d3.select(\"#saveButton\").style(\"background-repeat\", \"no-repeat\");\n d3.select(\"#saveButton\").style(\"top\", \"0px\");\n */\n d3.select(\"#savePanel img\").attr(\"src\", \"/static/img/ajax-loader.gif\");\n\n url = '/tributary/save';\n\n } else if(saveorfork === \"fork\") {\n\n /*\n d3.select(\"#forkButton\").style(\"background-image\", \"url(/static/img/ajax-loader.gif)\");\n d3.select(\"#forkButton\").style(\"background-repeat\", \"no-repeat\");\n d3.select(\"#forkButton\").style(\"top\", \"0px\");\n */\n d3.select(\"#forkPanel img\").attr(\"src\", \"/static/img/ajax-loader.gif\");\n\n url = '/tributary/fork';\n \n }\n\n //check if we have an existing gist number\n if(oldgist > 0) {\n url += '/' + oldgist;\n }\n //console.log(\"url\", url)\n // console.log(\"JSON\", JSON.stringify(gist))\n\n var that = this;\n $.post(url, {\"gist\":JSON.stringify(gist)}, function(data) {\n if(typeof(data) === \"string\") {\n //console.log(\"SUP\", data)\n data = JSON.parse(data);\n }\n var newgist = data.id;\n var newurl = \"/\" + that.endpoint + \"/\" + newgist;// + \"/\" + filename;\n callback(newurl, newgist);\n //window.location = newurl;\n });\n }, \n login_gist: function(loginorout, callback) {\n\n var url;\n if(loginorout) {\n \n url = '/github-logout';\n\n } else {\n\n \n url = '/github-login';\n \n }\n url+= '/' + this.endpoint\n if (this.gist)\n if (this.gist.id)\n url+= '/' + this.gist.id\n\n //console.log(loginorout)\n //console.log(\"url\", url)\n\n var that = this;\n window.location = url\n\n }\n});\n\n", "dangerousExampleEn": "1. \nLine 3: A debug code is remaining.", "safeExampleEn": "1. \nLine 3: Remove the code used for debugging.", "contexts": [{"lineNo": 17, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "17"}}, {"lineNo": 19, "eventType": "sink", "messageKey": "jschk.LEFTOVER_DEBUG_CODE.TOBE.JS.defect", "params": {}}]}} {"id": "b4fb08f5fa62f8ef3ffbd637c98f87a5ddec42887083e9c7992f0b52015d1770", "license": {"spdx": ["MIT"], "repo": "hightouch67/avalon", "path": "src/http.js", "repo_head_hexsha": "bef0670f0c710484e85d0bc94fc24474781f84cc", "stack_hexsha": "6528111cd66848efd1b8e72544e7c7fd67231f53", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Leftover debug code", "issueDescriptionEn": "The Leftover debug code checker finds debug code that remains not removed.\nDebug code may contain parts that output sensitive information or allow control over the system. If the program is deployed with debug code remaining, attackers may bypass an authentication process or access restricted information.\nRemove all debug code before deploying the application.", "issueLineNumber": 186, "entireCode": "var http_port = process.env.HTTP_PORT || 3001\nvar express = require('express')\nvar cors = require('cors')\nvar bodyParser = require('body-parser')\nconst YT = require('simple-youtube-api')\nconst yt_key = process.env.YT_API_KEY || 'NO_KEY'\nconst yt = new YT(yt_key)\nconst { extract } = require('oembed-parser')\nconst ogs = require('open-graph-scraper')\nconst series = require('run-series')\nconst transaction = require('./transaction.js')\nconst timeout_transact_async = 7500\n\nvar http = {\n init: () => {\n var app = express()\n app.use(cors())\n app.use(bodyParser.json())\n\n // fetch a single block\n app.get('/block/:number', (req, res) => {\n var blockNumber = parseInt(req.params.number)\n db.collection('blocks').findOne({ _id: blockNumber }, function (err, block) {\n if (err) throw err\n if (!block) {\n res.sendStatus(404)\n return\n }\n res.send(block)\n })\n })\n\n // count how many blocks are in the node\n app.get('/count', (req, res) => {\n db.collection('blocks').countDocuments(function (err, count) {\n if (err) throw err\n res.send({\n count: count\n })\n })\n })\n\n // check econ data\n app.get('/rewardPool', (req, res) => {\n if (eco.lastRewardPool)\n res.send(eco.lastRewardPool)\n else res.send({})\n })\n\n // get supply info\n app.get('/supply', (req, res) => {\n let executions = [\n (cb) => db.collection('accounts').aggregate([{ $group: { _id: 0, total: { $sum: \"$balance\" } } }]).toArray((e, r) => cb(e, r)),\n (cb) => db.collection('contents').aggregate([{ $unwind: \"$votes\" }, { $match: { \"votes.claimed\": { $exists: false } } }, { $group: { _id: 0, total: { $sum: \"$votes.claimable\" } } }]).toArray((e, r) => cb(e, r))\n ]\n\n series(executions, (e, r) => {\n if (e)\n return res.sendStatus(500)\n\n var reply = {\n circulating: r[0][0].total\n }\n if (r[1].length > 0) {\n reply.unclaimed = r[1][0].total\n reply.total = r[0][0].total + r[1][0].total\n }\n res.send(reply)\n })\n })\n\n // pending reward per user\n app.get('/rewards/pending/:name', (req, res) => {\n if (!req.params.name) {\n res.sendStatus(500)\n return\n }\n var claimableDate = new Date().getTime() - config.ecoClaimTime;\n db.collection('contents').aggregate([\n { $unwind: \"$votes\" },\n {\n $match: {\n \"votes.ts\": { $gte: claimableDate },\n \"votes.u\": req.params.name,\n \"votes.claimed\": { $exists: false }\n }\n }, { $group: { _id: 0, total: { $sum: {$floor: \"$votes.claimable\" } } } }\n ]).toArray(function (err, result) {\n if (err) {\n console.log(err)\n res.sendStatus(500)\n return\n } else {\n if (!result[0] || !result[0].total) {\n res.send({ total: 0 })\n return\n }\n res.send({ total: Math.round(1000 * result[0].total) / 1000 })\n }\n })\n })\n\n // claimable reward per user\n app.get('/rewards/claimable/:name', (req, res) => {\n if (!req.params.name) {\n res.sendStatus(500)\n return\n }\n var claimableDate = new Date().getTime() - config.ecoClaimTime;\n db.collection('contents').aggregate([\n { $unwind: \"$votes\" },\n {\n $match: {\n \"votes.ts\": { $lt: claimableDate },\n \"votes.u\": req.params.name,\n \"votes.claimed\": { $exists: false }\n }\n }, { $group: { _id: 0, total: { $sum: {$floor: \"$votes.claimable\" } } } }\n ]).toArray(function (err, result) {\n if (err) {\n console.log(err)\n res.sendStatus(500)\n return\n } else {\n if (!result[0] || !result[0].total) {\n res.send({ total: 0 })\n return\n }\n res.send({ total: Math.round(1000 * result[0].total) / 1000 })\n }\n })\n })\n // claimed reward per user\n app.get('/rewards/claimed/:name', (req, res) => {\n if (!req.params.name) {\n res.sendStatus(500)\n return\n }\n db.collection('contents').aggregate([\n { $unwind: \"$votes\" },\n {\n $match: {\n \"votes.u\": req.params.name,\n \"votes.claimed\": { $exists: true }\n }\n }, { $group: { _id: 0, total: { $sum: {$floor: \"$votes.claimable\" } } } }\n ]).toArray(function (err, result) {\n if (err) {\n console.log(err)\n res.sendStatus(500)\n return\n } else {\n if (!result[0] || !result[0].total) {\n res.send({ total: 0 })\n return\n }\n res.send({ total: Math.round(1000 * result[0].total) / 1000 })\n }\n })\n })\n\n // generate a new key pair\n app.get('/newKeyPair', (req, res) => {\n res.send(chain.getNewKeyPair())\n })\n\n // this suggests the node to produce a block and submit it\n app.get('/mineBlock', (req, res) => {\n delete p2p.recovering\n res.send(chain.getLatestBlock()._id.toString())\n chain.mineBlock(function (error, finalBlock) {\n if (error)\n logr.error('ERROR refused block', finalBlock)\n })\n })\n\n // add data to the upcoming transactions pool\n app.post('/transact', (req, res) => {\n var tx = req.body\n if (!tx) {\n res.sendStatus(500)\n return\n }\n transaction.isValid(tx, new Date().getTime(), function (isValid, errorMessage) {\n if (!isValid) {\n logr.trace('invalid http tx: ', errorMessage, tx)\n res.status(500).send({ error: errorMessage })\n } else {\n p2p.broadcast({ t: 5, d: tx })\n transaction.addToPool([tx])\n res.send(chain.getLatestBlock()._id.toString())\n }\n })\n })\n\n // add data to the upcoming transactions pool\n // and return only when the transaction is in a finalized block\n app.post('/transactWaitConfirm', (req, res) => {\n var tx = req.body\n if (!tx) {\n res.sendStatus(500)\n return\n }\n transaction.isValid(tx, new Date().getTime(), function (isValid, errorMessage) {\n if (!isValid) {\n logr.trace('invalid http tx: ', errorMessage, tx)\n res.status(500).send({ error: errorMessage })\n } else {\n p2p.broadcast({ t: 5, d: tx })\n transaction.addToPool([tx])\n\n var transactTimeout = setTimeout(function () {\n transaction.eventConfirmation.removeListener(tx.hash, () => { })\n res.status(408).send({ error: 'transaction timeout' })\n }, timeout_transact_async)\n\n transaction.eventConfirmation.addListener(tx.hash, function () {\n clearTimeout(transactTimeout)\n res.send(chain.getLatestBlock()._id.toString())\n })\n }\n })\n })\n\n // list connected peers\n app.get('/peers', (req, res) => {\n var peers = []\n for (let i = 0; i < p2p.sockets.length; i++) {\n var peer = {\n ip: p2p.sockets[i]._socket.remoteAddress,\n port: p2p.sockets[i]._socket.remotePort,\n }\n if (p2p.sockets[i].node_status)\n peer.node_status = p2p.sockets[i].node_status\n if (p2p.sockets[i].sentUs)\n peer.sentUs = p2p.sockets[i].sentUs\n\n peers.push(peer)\n }\n res.send(peers)\n })\n\n // connect to a new peer\n app.post('/addPeer', (req, res) => {\n p2p.connect([req.body.peer])\n res.send()\n })\n\n // look at the miner schedule\n app.get('/schedule', (req, res) => {\n res.send(chain.schedule)\n })\n\n // get full list of ranked miners\n app.get('/allminers', (req, res) => {\n db.collection('accounts').find({ node_appr: { $gt: 0 } }, {\n sort: { node_appr: -1 }\n }).toArray(function (err, accounts) {\n if (err) throw err\n res.send(accounts)\n })\n })\n\n // get in-memory data (intensive)\n app.get('/debug', (req, res) => {\n res.send({\n mempool: transaction.pool,\n consensus: {\n possBlocks: consensus.possBlocks,\n processed: consensus.processed,\n validating: consensus.validating,\n },\n p2p: {\n recoveringBlocks: p2p.recoveringBlocks,\n // recoveredBlocks: p2p.recoveredBlocks\n },\n chain: {\n recentBlocks: chain.recentBlocks,\n recentTxs: chain.recentTxs\n }\n })\n })\n\n // get hot\n app.get('/hot', (req, res) => {\n res.send(rankings.contents.hot.slice(0, 50))\n })\n app.get('/hot/:author/:link', (req, res) => {\n var filteredContents = []\n var isPastRelativeContent = false\n var added = 0\n for (let i = 0; i < rankings.contents.hot.length; i++) {\n if (isPastRelativeContent) {\n filteredContents.push(rankings.contents.hot[i])\n added++\n }\n if (added >= 50) break\n if (rankings.contents.hot[i].author === req.params.author\n && rankings.contents.hot[i].link === req.params.link)\n isPastRelativeContent = true\n }\n res.send(filteredContents)\n })\n\n // get trending\n app.get('/trending', (req, res) => {\n res.send(rankings.contents.trending.slice(0, 50))\n })\n app.get('/trending/:author/:link', (req, res) => {\n var filteredContents = []\n var isPastRelativeContent = false\n var added = 0\n for (let i = 0; i < rankings.contents.trending.length; i++) {\n if (isPastRelativeContent) {\n filteredContents.push(rankings.contents.trending[i])\n added++\n }\n if (added >= 50) break\n if (rankings.contents.trending[i].author === req.params.author\n && rankings.contents.trending[i].link === req.params.link)\n isPastRelativeContent = true\n }\n res.send(filteredContents)\n })\n\n // get new contents\n app.get('/new', (req, res) => {\n db.collection('contents').find({ pa: null }, { sort: { ts: -1 }, limit: 50 }).toArray(function (err, contents) {\n res.send(contents)\n })\n })\n app.get('/new/:author/:link', (req, res) => {\n db.collection('contents').findOne({\n $and: [\n { author: req.params.author },\n { link: req.params.link }\n ]\n }, function (err, content) {\n if (!content) {\n res.sendStatus(404)\n return\n }\n db.collection('contents').find({\n $and: [\n { pa: null },\n { ts: { $lte: content.ts } }\n ]\n }, { sort: { ts: -1 }, limit: 50 }).toArray(function (err, contents) {\n res.send(contents)\n })\n })\n })\n\n // get feed contents\n app.get('/feed/:username', (req, res) => {\n db.collection('accounts').findOne({ name: req.params.username }, function (err, account) {\n if (!account || !account.follows)\n res.send([])\n else\n db.collection('contents').find({\n $and: [\n { author: { $in: account.follows } },\n { pa: null }\n ]\n }, { sort: { ts: -1 }, limit: 50 }).toArray(function (err, contents) {\n res.send(contents)\n })\n\n })\n })\n app.get('/feed/:username/:author/:link', (req, res) => {\n db.collection('contents').findOne({\n $and: [\n { author: req.params.author },\n { link: req.params.link }\n ]\n }, function (err, content) {\n db.collection('accounts').findOne({ name: req.params.username }, function (err, account) {\n if (!account.follows)\n res.send([])\n else\n db.collection('contents').find({\n $and: [\n { author: { $in: account.follows } },\n { pa: null },\n { ts: { $lte: content.ts } }\n ]\n }, { sort: { ts: -1 }, limit: 50 }).toArray(function (err, contents) {\n res.send(contents)\n })\n\n })\n })\n })\n\n // get blog of user\n app.get('/blog/:username', (req, res) => {\n var username = req.params.username\n db.collection('contents').find({ pa: null, author: username }, { sort: { ts: -1 }, limit: 50 }).toArray(function (err, contents) {\n res.send(contents)\n })\n })\n app.get('/blog/:username/:author/:link', (req, res) => {\n db.collection('contents').findOne({\n $and: [\n { author: req.params.author },\n { link: req.params.link }\n ]\n }, function (err, content) {\n if (err || !content) {\n res.send([])\n return\n }\n var username = req.params.username\n db.collection('contents').find({\n $and: [\n { pa: null },\n { author: username },\n { ts: { $lte: content.ts } }\n ]\n }, { sort: { ts: -1 }, limit: 50 }).toArray(function (err, contents) {\n res.send(contents)\n })\n })\n })\n\n // account history api\n app.get('/history/:author/:lastBlock', (req, res) => {\n var lastBlock = parseInt(req.params.lastBlock)\n var author = req.params.author\n var query = {\n $and: [\n {\n $or: [\n { 'txs.sender': author },\n { 'txs.data.target': author },\n { 'txs.data.receiver': author },\n { 'txs.data.pa': author },\n { 'txs.data.author': author }\n ]\n }\n ]\n }\n if (lastBlock > 0)\n query['$and'].push({ _id: { $lt: lastBlock } })\n\n db.collection('blocks').find(query, { sort: { _id: -1 }, limit: 50 }).toArray(function (err, blocks) {\n for (let b = 0; b < blocks.length; b++) {\n var newTxs = []\n for (let t = 0; t < blocks[b].txs.length; t++)\n if (blocks[b].txs[t].sender === author\n || blocks[b].txs[t].data.target === author\n || blocks[b].txs[t].data.receiver === author\n || blocks[b].txs[t].data.pa === author\n || blocks[b].txs[t].data.author === author)\n newTxs.push(blocks[b].txs[t])\n blocks[b].txs = newTxs\n }\n res.send(blocks)\n })\n })\n\n // get votes history of a user\n app.get('/votes/all/:voter/:lastTs', (req, res) => {\n var voter = req.params.voter\n var query = {\n $and: [{\n 'votes.u': voter,\n }]\n }\n var lastTs = parseInt(req.params.lastTs)\n if (lastTs > 0)\n query['$and'].push({ ts: { $lt: lastTs } })\n\n db.collection('contents').find(query, { sort: { ts: -1 }, limit: 50 }).toArray(function (err, contents) {\n if (err) throw err\n var votes = []\n for (let i = 0; i < contents.length; i++) {\n for (let y = 0; y < contents[i].votes.length; y++) {\n if (contents[i].votes[y].u === voter)\n votes.push({\n author: contents[i].author,\n link: contents[i].link,\n claimable: contents[i].votes[y].claimable,\n claimed: contents[i].votes[y].claimed,\n vt: contents[i].votes[y].vt,\n ts: contents[i].votes[y].ts,\n contentTs: contents[i].ts,\n burn: contents[i].votes[y].burn\n })\n }\n }\n res.send(votes)\n })\n })\n // adding back this one for compatibility purpose\n // to remove in future\n app.get('/votes/:voter/:lastTs', (req, res) => {\n var voter = req.params.voter\n var query = {\n $and: [{\n 'votes.u': voter,\n }]\n }\n var lastTs = parseInt(req.params.lastTs)\n if (lastTs > 0)\n query['$and'].push({ ts: { $lt: lastTs } })\n\n db.collection('contents').find(query, { sort: { ts: -1 }, limit: 50 }).toArray(function (err, contents) {\n if (err) throw err\n var votes = []\n for (let i = 0; i < contents.length; i++) {\n for (let y = 0; y < contents[i].votes.length; y++) {\n if (contents[i].votes[y].u === voter)\n votes.push({\n author: contents[i].author,\n link: contents[i].link,\n claimable: contents[i].votes[y].claimable,\n claimed: contents[i].votes[y].claimed,\n vt: contents[i].votes[y].vt,\n ts: contents[i].votes[y].ts,\n contentTs: contents[i].ts,\n burn: contents[i].votes[y].burn\n })\n }\n }\n res.send(votes)\n })\n })\n\n // get pending votes history of a user\n app.get('/votes/pending/:voter/:lastTs', (req, res) => {\n var voter = req.params.voter\n var claimableDate = new Date().getTime() - config.ecoClaimTime;\n var query =\n {\n $and: [{}],\n votes:\n {\n $elemMatch: {\n u: voter,\n ts: { $gt: claimableDate }\n }\n }\n }\n var lastTs = parseInt(req.params.lastTs)\n if (lastTs > 0)\n query['$and'].push({ ts: { $lt: lastTs } })\n\n db.collection('contents').find(query, { sort: { ts: -1 }, limit: 50 }).toArray(function (err, contents) {\n if (err) throw err\n var votes = []\n for (let i = 0; i < contents.length; i++) {\n for (let y = 0; y < contents[i].votes.length; y++) {\n if (contents[i].votes[y].u === voter)\n votes.push({\n author: contents[i].author,\n link: contents[i].link,\n claimable: contents[i].votes[y].claimable,\n claimed: contents[i].votes[y].claimed,\n vt: contents[i].votes[y].vt,\n ts: contents[i].votes[y].ts,\n contentTs: contents[i].ts,\n burn: contents[i].votes[y].burn\n })\n }\n }\n res.send(votes)\n })\n })\n\n // get claimable votes history of a user\n app.get('/votes/claimable/:voter/:lastTs', (req, res) => {\n var voter = req.params.voter\n var claimableDate = new Date().getTime() - config.ecoClaimTime;\n var query =\n {\n $and: [{}],\n votes:\n {\n $elemMatch: {\n u: voter,\n claimable: { $gte: 1 },\n claimed: { $exists: false },\n ts: { $lt: claimableDate }\n }\n }\n }\n var lastTs = parseInt(req.params.lastTs)\n if (lastTs > 0)\n query['$and'].push({ ts: { $lt: lastTs } })\n db.collection('contents').find(query, { sort: { ts: -1 }, limit: 50 }).toArray(function (err, contents) {\n if (err) throw err\n var votes = []\n for (let i = 0; i < contents.length; i++) {\n for (let y = 0; y < contents[i].votes.length; y++) {\n if (contents[i].votes[y].u === voter)\n votes.push({\n author: contents[i].author,\n link: contents[i].link,\n claimable: contents[i].votes[y].claimable,\n claimed: contents[i].votes[y].claimed,\n vt: contents[i].votes[y].vt,\n ts: contents[i].votes[y].ts,\n contentTs: contents[i].ts,\n burn: contents[i].votes[y].burn\n })\n }\n }\n res.send(votes)\n })\n })\n\n // get claimed votes history of a user\n app.get('/votes/claimed/:voter/:lastTs', (req, res) => {\n var voter = req.params.voter\n var query =\n {\n $and: [{}],\n votes:\n {\n $elemMatch: {\n u: voter,\n claimable: { $gte: 1 },\n claimed: { $exists: true }\n }\n }\n }\n var lastTs = parseInt(req.params.lastTs)\n if (lastTs > 0)\n query['$and'].push({ ts: { $lt: lastTs } })\n db.collection('contents').find(query, { sort: { ts: -1 }, limit: 50 }).toArray(function (err, contents) {\n if (err) throw err\n var votes = []\n for (let i = 0; i < contents.length; i++) {\n for (let y = 0; y < contents[i].votes.length; y++) {\n if (contents[i].votes[y].u === voter)\n votes.push({\n author: contents[i].author,\n link: contents[i].link,\n claimable: contents[i].votes[y].claimable,\n claimed: contents[i].votes[y].claimed,\n vt: contents[i].votes[y].vt,\n ts: contents[i].votes[y].ts,\n contentTs: contents[i].ts,\n burn: contents[i].votes[y].burn\n })\n }\n }\n res.send(votes)\n })\n })\n\n // get new contents\n app.get('/content/:author/:link', (req, res) => {\n if (!req.params.author || typeof req.params.link !== 'string') {\n res.sendStatus(500)\n return\n }\n db.collection('contents').findOne({\n author: req.params.author,\n link: req.params.link\n }, function (err, post) {\n if (!post) {\n res.sendStatus(404)\n return\n }\n if (!post.child || post.child.length === 0) {\n res.send(post)\n return\n }\n post.comments = {}\n function fillComments(posts, cb) {\n if (!posts || posts.length === 0) {\n cb()\n return\n }\n var executions = []\n for (let i = 0; i < posts.length; i++)\n executions.push(function (callback) {\n db.collection('contents').find({\n pa: posts[i].author,\n pp: posts[i].link\n }).toArray(function (err, comments) {\n for (let y = 0; y < comments.length; y++)\n post.comments[comments[y].author + '/' + comments[y].link] = comments[y]\n fillComments(comments, function () {\n callback(null, true)\n })\n })\n i++\n })\n\n series(executions, function (err, results) {\n if (err) throw err\n cb(null, results)\n })\n }\n fillComments([post], function () {\n res.send(post)\n })\n })\n })\n\n // get current chain config\n app.get('/config', (req, res) => {\n res.send(config)\n })\n\n // get username price\n app.get('/accountPrice/:name', (req, res) => {\n if (!req.params.name) {\n res.sendStatus(500)\n return\n }\n db.collection('accounts').findOne({ name: req.params.name }, function (err, account) {\n if (account) res.send('Not Available')\n else res.send(String(eco.accountPrice(req.params.name)))\n })\n })\n\n // get account info\n app.get('/account/:name', (req, res) => {\n if (!req.params.name) {\n res.sendStatus(500)\n return\n }\n db.collection('accounts').findOne({ name: req.params.name }, function (err, account) {\n if (!account) res.sendStatus(404)\n else res.send(account)\n })\n })\n\n // get accounts info\n app.get('/accounts/:names', (req, res) => {\n if (!req.params.names || typeof req.params.names !== 'string') {\n res.sendStatus(500)\n return\n }\n var names = req.params.names.split(',', 100)\n db.collection('accounts').find({ name: { $in: names } }).toArray(function (err, accounts) {\n if (!accounts) res.sendStatus(404)\n else {\n for (let i = 0; i < accounts.length; i++) {\n accounts[i].followsCount = (accounts[i].follows ? accounts[i].follows.length : 0)\n accounts[i].followersCount = (accounts[i].followers ? accounts[i].followers.length : 0)\n delete accounts[i].follows\n delete accounts[i].followers\n }\n res.send(accounts)\n }\n })\n })\n\n // get follows\n app.get('/follows/:name', (req, res) => {\n if (!req.params.name) {\n res.sendStatus(500)\n return\n }\n db.collection('accounts').findOne({ name: req.params.name }, function (err, account) {\n if (!account) res.sendStatus(404)\n else\n if (account.follows)\n res.send(account.follows)\n else\n res.send([])\n\n })\n })\n\n // get followers\n app.get('/followers/:name', (req, res) => {\n if (!req.params.name) {\n res.sendStatus(500)\n return\n }\n db.collection('accounts').findOne({ name: req.params.name }, function (err, account) {\n if (!account) res.sendStatus(404)\n else\n if (account.followers)\n res.send(account.followers)\n else\n res.send([])\n\n })\n })\n\n // get notifications for a user\n app.get('/notifications/:name', (req, res) => {\n if (!req.params.name) {\n res.sendStatus(500)\n return\n }\n db.collection('notifications').find({ u: req.params.name }, { sort: { ts: -1 }, limit: 200 }).toArray(function (err, notifs) {\n if (!notifs) res.sendStatus(404)\n else res.send(notifs)\n })\n })\n\n // get distributions for a user\n app.get('/distributed/:name', (req, res) => {\n if (!req.params.name) {\n res.sendStatus(500)\n return\n }\n db.collection('distributed').find({ name: req.params.name }, { sort: { ts: -1 }, limit: 200 }).toArray(function (err, distributions) {\n if (!distributions) res.sendStatus(404)\n else res.send(distributions)\n })\n })\n\n // 3rd party video embed data\n // get youtube info\n app.get('/youtube/:videoId', (req, res) => {\n if (!req.params.videoId) {\n res.sendStatus(500)\n return\n }\n yt.getVideoByID(req.params.videoId).then(function (video) {\n video.duration = video.durationSeconds\n res.send(video)\n }).catch(function (err) {\n logr.warn('YouTube API error', err)\n res.sendStatus(500)\n })\n })\n\n // get oembed for any url\n app.get('/oembed/:url', (req, res) => {\n if (!req.params.url) {\n res.sendStatus(500)\n return\n }\n extract(req.params.url).then((data) => {\n res.send(data)\n }).catch(() => {\n res.sendStatus(404)\n })\n })\n\n // get open graph data for any url\n app.get('/opengraph/:url', (req, res) => {\n if (!req.params.url) {\n res.sendStatus(500)\n return\n }\n ogs({ url: req.params.url, headers: { 'user-agent': 'facebookexternalhit/1.1 (+https://d.tube)' } }, function (error, results) {\n if (error) res.sendStatus(404)\n else res.send(results)\n })\n })\n\n app.listen(http_port, () => logr.info('Listening http on port: ' + http_port))\n }\n}\n\nmodule.exports = http", "dangerousExampleEn": "1. \nLine 3: A debug code is remaining.", "safeExampleEn": "1. \nLine 3: Remove the code used for debugging.", "contexts": [{"lineNo": 185, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "185"}}, {"lineNo": 186, "eventType": "sink", "messageKey": "jschk.LEFTOVER_DEBUG_CODE.TOBE.JS.defect", "params": {}}]}} {"id": "19c6480c8b9ae913679527d4417e065f003cb67eb77d0283b6b83c2e7a1ac6a3", "license": {"spdx": ["MIT"], "repo": "polarityio/hyas-insight", "path": "integration.js", "repo_head_hexsha": "92cc8a264cabf307ee263958b70c216c3442f024", "stack_hexsha": "b95103b53b3f36bff4bebf5aa83e729f56bc6a73", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Leftover debug code", "issueDescriptionEn": "The Leftover debug code checker finds debug code that remains not removed.\nDebug code may contain parts that output sensitive information or allow control over the system. If the program is deployed with debug code remaining, attackers may bypass an authentication process or access restricted information.\nRemove all debug code before deploying the application.", "issueLineNumber": 96, "entireCode": "'use strict';\n\nconst request = require('request');\nconst _ = require('lodash');\nconst fp = require('lodash/fp');\nconst config = require('./config/config');\nconst async = require('async');\nconst fs = require('fs');\nconst PNF = require('google-libphonenumber').PhoneNumberFormat;\n\n// Get an instance of `PhoneNumberUtil`.\nconst phoneUtil = require('google-libphonenumber').PhoneNumberUtil.getInstance();\n\nlet Logger;\nlet requestWithDefaults;\nlet previousDomainRegexAsString = '';\nlet previousIpRegexAsString = '';\nlet domainBlocklistRegex = null;\nlet ipBlocklistRegex = null;\n\nconst MAX_DOMAIN_LABEL_LENGTH = 63;\nconst MAX_ENTITY_LENGTH = 100;\nconst MAX_PARALLEL_LOOKUPS = 10;\nconst PAGE_SIZE = 5;\nconst IGNORED_IPS = new Set(['127.0.0.1', '255.255.255.255', '0.0.0.0']);\nconst url = 'https://insight.hyas.com/api/ext';\nconst uiurl = 'https://apps.hyas.com';\n/**\n *\n * @param entities\n * @param options\n * @param cb\n */\nfunction startup(logger) {\n Logger = logger;\n let defaults = {};\n\n if (typeof config.request.cert === 'string' && config.request.cert.length > 0) {\n defaults.cert = fs.readFileSync(config.request.cert);\n }\n\n if (typeof config.request.key === 'string' && config.request.key.length > 0) {\n defaults.key = fs.readFileSync(config.request.key);\n }\n\n if (\n typeof config.request.passphrase === 'string' &&\n config.request.passphrase.length > 0\n ) {\n defaults.passphrase = config.request.passphrase;\n }\n\n if (typeof config.request.ca === 'string' && config.request.ca.length > 0) {\n defaults.ca = fs.readFileSync(config.request.ca);\n }\n\n if (typeof config.request.proxy === 'string' && config.request.proxy.length > 0) {\n defaults.proxy = config.request.proxy;\n }\n\n if (typeof config.request.rejectUnauthorized === 'boolean') {\n defaults.rejectUnauthorized = config.request.rejectUnauthorized;\n }\n\n defaults.json = true;\n requestWithDefaults = request.defaults(defaults);\n}\n\nfunction doLookup(entities, options, cb) {\n let lookupResults = [];\n let tasks = [];\n\n _setupRegexBlocklists(options);\n\n Logger.debug(entities);\n\n entities.forEach((entity) => {\n if (entity.isIPv4) {\n if (!_isInvalidEntity(entity) && !_isEntityBlocklisted(entity, options)) {\n //do the lookup\n let requestOptions = {\n json: true,\n uri: url + '/passivedns',\n method: 'POST',\n headers: {\n 'X-API-Key': options.apiKey,\n 'Content-Type': 'application/json'\n },\n body: {\n applied_filters: {\n ipv4: entity.value\n }\n }\n };\n\n Logger.trace({ options: requestOptions }, 'Request URI');\n\n tasks.push(function (done) {\n requestWithDefaults(requestOptions, function (error, res, body) {\n body = body && _.isArray(body) && body.splice(0, PAGE_SIZE);\n let processedResult = handleRestError(error, entity, res, body);\n\n if (processedResult.error) {\n done(processedResult);\n return;\n }\n\n done(null, {\n ...processedResult,\n link: `${uiurl}/static/details?ip=${entity.value}`\n });\n });\n });\n }\n }\n if (entity.isIPv6) {\n if (!_isInvalidEntity(entity) && !_isEntityBlocklisted(entity, options)) {\n //do the lookup\n let requestOptions = {\n json: true,\n uri: url + '/passivedns',\n method: 'POST',\n headers: {\n 'X-API-Key': options.apiKey,\n 'Content-Type': 'application/json'\n },\n body: {\n applied_filters: {\n ipv6: entity.value\n }\n }\n };\n\n Logger.trace({ options: requestOptions }, 'Request URI');\n\n tasks.push(function (done) {\n requestWithDefaults(requestOptions, function (error, res, body) {\n body = body && _.isArray(body) && body.splice(0, PAGE_SIZE);\n let processedResult = handleRestError(error, entity, res, body);\n\n if (processedResult.error) {\n done(processedResult);\n return;\n }\n\n done(null, {\n ...processedResult,\n link: `${uiurl}/static/details?ip=${entity.value}`\n });\n });\n });\n }\n } else if (entity.isDomain) {\n if (!_isInvalidEntity(entity) && !_isEntityBlocklisted(entity, options)) {\n //do the lookup\n let requestOptions = {\n uri: url + '/whois',\n method: 'POST',\n headers: {\n 'X-API-Key': options.apiKey,\n 'Content-Type': 'application/json'\n },\n body: {\n applied_filters: {\n domain: entity.value\n }\n },\n json: true\n };\n\n Logger.trace({ options: requestOptions }, 'Request URI');\n\n tasks.push(function (done) {\n requestWithDefaults(requestOptions, function (error, res, body) {\n body = body && _.isArray(body) && body.splice(0, PAGE_SIZE);\n let processedResult = handleRestError(error, entity, res, body);\n if (processedResult.error) {\n done(processedResult);\n return;\n }\n\n done(null, {\n ...processedResult,\n link: `${uiurl}/static/details?domain=${entity.value}`\n });\n });\n });\n }\n } else if (entity.type === 'custom') {\n if (!_isInvalidEntity(entity) && !_isEntityBlocklisted(entity, options)) {\n //do the lookup\n const phone = phoneUtil.format(\n phoneUtil.parseAndKeepRawInput(entity.value, 'US'),\n PNF.E164\n );\n let requestOptions = {\n uri: url + '/whois',\n method: 'POST',\n headers: {\n 'X-API-Key': options.apiKey,\n 'Content-Type': 'application/json'\n },\n body: {\n applied_filters: { phone }\n },\n json: true\n };\n\n Logger.trace({ options: requestOptions }, 'Request URI');\n\n tasks.push(function (done) {\n requestWithDefaults(requestOptions, function (error, res, body) {\n body = body && _.isArray(body) && body.splice(0, PAGE_SIZE);\n let processedResult = handleRestError(error, entity, res, body);\n if (processedResult.error) {\n done(processedResult);\n return;\n }\n\n done(null, {\n ...processedResult,\n link: `${uiurl}/static/details?phone=${phone}`\n });\n });\n });\n }\n } else if (entity.isEmail) {\n if (!_isInvalidEntity(entity) && !_isEntityBlocklisted(entity, options)) {\n //do the lookup\n let requestOptions = {\n uri: url + '/whois',\n method: 'POST',\n headers: {\n 'X-API-Key': options.apiKey,\n 'Content-Type': 'application/json'\n },\n body: {\n applied_filters: {\n email: entity.value\n }\n },\n json: true\n };\n\n Logger.trace({ options: requestOptions }, 'Request URI');\n\n tasks.push(function (done) {\n requestWithDefaults(requestOptions, function (error, res, body) {\n body = body && _.isArray(body) && body.splice(0, PAGE_SIZE);\n let processedResult = handleRestError(error, entity, res, body);\n if (processedResult.error) {\n done(processedResult);\n return;\n }\n\n done(null, {\n ...processedResult,\n link: `${uiurl}/static/details?email=${entity.value}`\n });\n });\n });\n }\n } else if (entity.isMD5 || entity.isSHA256) {\n //do the lookup\n let requestOptions = {\n uri: url + '/sample/information',\n method: 'POST',\n headers: {\n 'X-API-Key': options.apiKey,\n 'Content-Type': 'application/json'\n },\n body: {\n applied_filters: {\n hash: entity.value\n }\n },\n json: true\n };\n\n Logger.trace({ options: requestOptions }, 'Request URI');\n\n tasks.push(function (done) {\n requestWithDefaults(requestOptions, function (error, res, body) {\n let processedResult = handleRestError(error, entity, res, body);\n if (processedResult.error) {\n done(processedResult);\n return;\n }\n\n done(null, {\n ...processedResult,\n link: `${uiurl}/static/details?${\n entity.isMD5 ? 'md5' : entity.isSHA256 ? 'sha256' : 'q'\n }=${entity.value}`\n });\n });\n });\n }\n });\n\n async.parallelLimit(tasks, MAX_PARALLEL_LOOKUPS, (err, results) => {\n if (err) {\n Logger.error({ err: err }, 'Error');\n cb(err);\n return;\n }\n\n results.forEach((result) => {\n if (result.body === null || _isMiss(result.body) || _.isEmpty(result.body)) {\n lookupResults.push({\n entity: result.entity,\n data: null\n });\n } else {\n const resultWithFormatedPhoneNumber = getResultWithFormatedPhoneNumber(result);\n\n lookupResults.push({\n entity: result.entity,\n data: {\n summary: [],\n details: {\n result: resultWithFormatedPhoneNumber,\n link: result.link,\n pageSize: PAGE_SIZE\n }\n }\n });\n }\n });\n Logger.trace({ lookupResults }, 'Results');\n cb(null, lookupResults);\n });\n}\n\nconst getResultWithFormatedPhoneNumber = fp.flow(\n fp.getOr([], 'body'),\n fp.map((detail) => ({\n ...detail,\n ...(detail.phone &&\n detail.phone.length && {\n phone: fp.map(\n ({ phone }) => ({\n link: `${uiurl}/static/details?phone=%2B${phone.slice(1)}`,\n number: phone\n }),\n detail.phone\n )\n })\n }))\n);\n\nfunction _setupRegexBlocklists(options) {\n if (\n options.domainBlocklistRegex !== previousDomainRegexAsString &&\n options.domainBlocklistRegex.length === 0\n ) {\n Logger.debug('Removing Domain Blocklist Regex Filtering');\n previousDomainRegexAsString = '';\n domainBlocklistRegex = null;\n } else {\n if (options.domainBlocklistRegex !== previousDomainRegexAsString) {\n previousDomainRegexAsString = options.domainBlocklistRegex;\n Logger.debug(\n { domainBlocklistRegex: previousDomainRegexAsString },\n 'Modifying Domain Blocklist Regex'\n );\n domainBlocklistRegex = new RegExp(options.domainBlocklistRegex, 'i');\n }\n }\n\n if (\n options.ipBlocklistRegex !== previousIpRegexAsString &&\n options.ipBlocklistRegex.length === 0\n ) {\n Logger.debug('Removing IP Blocklist Regex Filtering');\n previousIpRegexAsString = '';\n ipBlocklistRegex = null;\n } else {\n if (options.ipBlocklistRegex !== previousIpRegexAsString) {\n previousIpRegexAsString = options.ipBlocklistRegex;\n Logger.debug(\n { ipBlocklistRegex: previousIpRegexAsString },\n 'Modifying IP Blocklist Regex'\n );\n ipBlocklistRegex = new RegExp(options.ipBlocklistRegex, 'i');\n }\n }\n}\n\nfunction doDeviceGeoIpLookup(entity, options) {\n return function (done) {\n if (entity.isIPv4) {\n let requestOptions = {\n uri: url + '/device_geo',\n method: 'POST',\n headers: {\n 'X-API-Key': options.apiKey,\n 'Content-Type': 'application/json'\n },\n body: {\n applied_filters: {\n ipv4: entity.value\n }\n },\n json: true\n };\n\n requestWithDefaults(requestOptions, (error, response, body) => {\n body = body && _.isArray(body) && body.splice(0, PAGE_SIZE);\n let processedResult = handleRestError(error, entity, response, body);\n if (processedResult.error) return done(processedResult);\n done(null, processedResult.body);\n });\n } else {\n done(null, null);\n }\n };\n}\n\nfunction doDomainPassiveLookup(entity, options) {\n return function (done) {\n if (entity.isDomain) {\n let requestOptions = {\n uri: url + '/passivedns',\n method: 'POST',\n headers: {\n 'X-API-Key': options.apiKey,\n 'Content-Type': 'application/json'\n },\n body: {\n applied_filters: {\n domain: entity.value\n },\n paging: { order: 'desc', sort: 'datetime', page_number: 0, page_size: 10 }\n },\n json: true\n };\n\n requestWithDefaults(requestOptions, (error, response, body) => {\n body = body && _.isArray(body) && body.splice(0, PAGE_SIZE);\n let processedResult = handleRestError(error, entity, response, body);\n if (processedResult.error) return done(processedResult);\n done(null, processedResult.body);\n });\n } else {\n done(null, null);\n }\n };\n}\n\nfunction doIpSampleLookup(entity, options) {\n return function (done) {\n if (entity.isIPv4) {\n let requestOptions = {\n uri: url + '/sample',\n method: 'POST',\n headers: {\n 'X-API-Key': options.apiKey,\n 'Content-Type': 'application/json'\n },\n body: {\n applied_filters: {\n ipv4: entity.value\n }\n },\n json: true\n };\n\n requestWithDefaults(requestOptions, (error, response, body) => {\n body = body && _.isArray(body) && body.splice(0, PAGE_SIZE);\n let processedResult = handleRestError(error, entity, response, body);\n if (processedResult.error) return done(processedResult);\n done(null, processedResult.body);\n });\n } else {\n done(null, null);\n }\n };\n}\n\nfunction doDomainSampleLookup(entity, options) {\n return function (done) {\n if (entity.isDomain) {\n let requestOptions = {\n uri: url + '/sample',\n method: 'POST',\n headers: {\n 'X-API-Key': options.apiKey,\n 'Content-Type': 'application/json'\n },\n body: {\n applied_filters: {\n domain: entity.value\n }\n },\n json: true\n };\n\n requestWithDefaults(requestOptions, (error, response, body) => {\n body = body && _.isArray(body) && body.splice(0, PAGE_SIZE);\n let processedResult = handleRestError(error, entity, response, body);\n if (processedResult.error) return done(processedResult);\n done(null, processedResult.body);\n });\n } else {\n done(null, null);\n }\n };\n}\n\nfunction doDomainSSlLookup(entity, options) {\n return function (done) {\n if (entity.isDomain) {\n let requestOptions = {\n uri: url + '/ssl_certificate',\n method: 'POST',\n headers: {\n 'X-API-Key': options.apiKey,\n 'Content-Type': 'application/json'\n },\n body: {\n applied_filters: {\n domain: entity.value\n }\n },\n json: true\n };\n\n requestWithDefaults(requestOptions, (error, response, body) => {\n body = body && _.isArray(body) && body.splice(0, PAGE_SIZE);\n let processedResult = handleRestError(error, entity, response, body);\n if (processedResult.error) return done(processedResult);\n done(null, processedResult.body);\n });\n } else {\n done(null, null);\n }\n };\n}\n\nfunction doDynamicDNSLookup(entity, options) {\n return function (done) {\n if (entity.isIPv4) {\n let requestOptions = {\n uri: url + '/dynamicdns',\n method: 'POST',\n headers: {\n 'X-API-Key': options.apiKey,\n 'Content-Type': 'application/json'\n },\n body: {\n applied_filters: {\n ip: entity.value\n }\n },\n json: true\n };\n\n requestWithDefaults(requestOptions, (error, response, body) => {\n body = body && _.isArray(body) && body.splice(0, PAGE_SIZE);\n let processedResult = handleRestError(error, entity, response, body);\n if (processedResult.error) return done(processedResult);\n done(null, processedResult.body);\n });\n } else {\n done(null, null);\n }\n };\n}\nfunction doDeviceGeoLookup(entity, options) {\n return function (done) {\n if (entity.type === 'custom') {\n let requestOptions = {\n json: true,\n uri: url + '/device_geo',\n method: 'POST',\n headers: {\n 'X-API-Key': options.apiKey,\n 'Content-Type': 'application/json'\n },\n body: {\n applied_filters: {\n phone: phoneUtil.format(\n phoneUtil.parseAndKeepRawInput(entity.value, 'US'),\n PNF.E164\n )\n }\n }\n };\n\n Logger.trace({ options: requestOptions }, 'Request URI');\n\n requestWithDefaults(requestOptions, (error, response, body) => {\n body = body && _.isArray(body) && body.splice(0, PAGE_SIZE);\n let processedResult = handleRestError(error, entity, response, body);\n if (processedResult.error) return done(processedResult);\n\n Logger.trace({ test: 8798789789, processedResult });\n done(null, processedResult.body);\n });\n } else {\n done(null, null);\n }\n };\n}\n\nfunction onDetails(lookupObject, options, cb) {\n async.parallel(\n {\n domainSsl: doDomainSSlLookup(lookupObject.entity, options),\n domainPassive: doDomainPassiveLookup(lookupObject.entity, options),\n ipDynamic: doDynamicDNSLookup(lookupObject.entity, options),\n ipSample: doIpSampleLookup(lookupObject.entity, options),\n domainSample: doDomainSampleLookup(lookupObject.entity, options),\n deviceGeo: doDeviceGeoLookup(lookupObject.entity, options),\n deviceGeoIp: doDeviceGeoIpLookup(lookupObject.entity, options)\n },\n (err, results) => {\n if (err) {\n Logger.error(err, 'Error in On Details');\n return cb(err);\n }\n const {\n domainSsl,\n domainPassive,\n ipDynamic,\n ipSample,\n domainSample,\n deviceGeo,\n deviceGeoIp\n } = results;\n\n //store the results into the details object so we can access them in our template\n lookupObject.data.details = lookupObject.data.details || {};\n lookupObject.data.details.domainSsl = domainSsl;\n lookupObject.data.details.domainPassive = domainPassive;\n lookupObject.data.details.ipDynamic = ipDynamic;\n lookupObject.data.details.ipSample = ipSample;\n lookupObject.data.details.domainSample = domainSample;\n lookupObject.data.details.deviceGeo = deviceGeo;\n lookupObject.data.details.deviceGeoIp = deviceGeoIp;\n\n Logger.trace(\n { lookup: lookupObject.data },\n 'Looking at the data after on details.'\n );\n\n cb(null, lookupObject.data);\n }\n );\n}\n\nfunction handleRestError(error, entity, res, body) {\n let result;\n\n if (error) {\n return {\n error: error,\n detail: 'HTTP Request Error'\n };\n }\n if (res.statusCode === 200) {\n // we got data!\n result = {\n entity: entity,\n body: body || null\n };\n } else if (res.statusCode === 404) {\n // no result found\n result = {\n entity: entity,\n body: null\n };\n } else if (res.statusCode === 202) {\n // no result found\n result = {\n entity: entity,\n body: null\n };\n } else {\n // unexpected status code\n result = {\n error: body,\n detail: `${body.error}: ${body.message}`\n };\n }\n return result;\n}\n\nfunction _isInvalidEntity(entity) {\n // Domains should not be over 100 characters long so if we get any of those we don't look them up\n if (entity.value.length > MAX_ENTITY_LENGTH) {\n return true;\n }\n\n // Domain labels (the parts in between the periods, must be 63 characters or less\n if (entity.isDomain) {\n const invalidLabel = entity.value.split('.').find((label) => {\n return label.length > MAX_DOMAIN_LABEL_LENGTH;\n });\n\n if (typeof invalidLabel !== 'undefined') {\n return true;\n }\n }\n\n if (entity.isIPv4 && IGNORED_IPS.has(entity.value)) {\n return true;\n }\n\n return false;\n}\n\nfunction _isEntityBlocklisted(entity, options) {\n const blocklist = options.blocklist;\n\n Logger.trace({ blocklist: blocklist }, 'checking to see what blocklist looks like');\n\n if (_.includes(blocklist, entity.value.toLowerCase())) {\n return true;\n }\n\n if (entity.isIP && !entity.isPrivateIP) {\n if (ipBlocklistRegex !== null) {\n if (ipBlocklistRegex.test(entity.value)) {\n Logger.debug({ ip: entity.value }, 'Blocked BlockListed IP Lookup');\n return true;\n }\n }\n }\n\n if (entity.isDomain) {\n if (domainBlocklistRegex !== null) {\n if (domainBlocklistRegex.test(entity.value)) {\n Logger.debug({ domain: entity.value }, 'Blocked BlockListed Domain Lookup');\n return true;\n }\n }\n }\n\n return false;\n}\n\nfunction _isMiss(body) {\n if (!body) {\n return true;\n }\n}\n\nfunction validateOptions(userOptions, cb) {\n let errors = [];\n if (\n typeof userOptions.apiKey.value !== 'string' ||\n (typeof userOptions.apiKey.value === 'string' &&\n userOptions.apiKey.value.length === 0)\n ) {\n errors.push({\n key: 'apiKey',\n message: 'You must provide a PassiveTotal API key'\n });\n }\n cb(null, errors);\n}\n\nmodule.exports = {\n doLookup: doLookup,\n onDetails: onDetails,\n startup: startup,\n validateOptions: validateOptions\n};", "dangerousExampleEn": "1. \nLine 3: A debug code is remaining.", "safeExampleEn": "1. \nLine 3: Remove the code used for debugging.", "contexts": [{"lineNo": 79, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "79"}}, {"lineNo": 96, "eventType": "sink", "messageKey": "jschk.LEFTOVER_DEBUG_CODE.TOBE.JS.defect", "params": {}}]}} {"id": "5525e2447fcc191b8cd2e0697f122e6e14c12b4cf43363999c57b27e3dc7fef2", "license": {"spdx": ["MIT"], "repo": "invisible-college/tightrope", "path": "lib/logger.js", "repo_head_hexsha": "f0c96dd6702e9d4b730cffac70829b56f76077b6", "stack_hexsha": "400f6d13611c4b8a7fb38d88c69c0c847fa7e7c8", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Leftover debug code", "issueDescriptionEn": "The Leftover debug code checker finds debug code that remains not removed.\nDebug code may contain parts that output sensitive information or allow control over the system. If the program is deployed with debug code remaining, attackers may bypass an authentication process or access restricted information.\nRemove all debug code before deploying the application.", "issueLineNumber": 6, "entireCode": "// Class for flexible, namespaced logging\n// With possible future extension to write output to a file.\n\nLogger = function(prefix, enabled) {\n \n if (this.prefix) { console.trace(); throw `prefix predefined to ${this.prefix}` }\n\n this.prefix = prefix\n if (typeof(enabled) !== 'object') {\n console.error(\"enabled param should be a list of strings indicating which log levels.\");\n //throw \"error\";\n }\n\n this.debug = (msg, _namespace) => {\n let namespace = (typeof(_namespace) == 'string') ? \"[\"+_namespace+\"]\" : \"\";\n \n if (enabled.indexOf('debug') !== -1) {\n console.log(`[{this.prefix}]{namespace} {msg}`)\n }\n }\n\n this.info = (msg, namespace) => {\n if (enabled.indexOf('info') !== -1) {\n console.log(\"[\"+this.prefix+\"] \" + msg)\n }\n }\n \n // Always print errors for now\n this.error = (msg) => { console.error(\"[\"+this.prefix+\"] \" + msg) }\n\n}\n\nmodule.exports = Logger", "dangerousExampleEn": "1. \nLine 3: A debug code is remaining.", "safeExampleEn": "1. \nLine 3: Remove the code used for debugging.", "contexts": [{"lineNo": 6, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "6"}}, {"lineNo": 6, "eventType": "sink", "messageKey": "jschk.LEFTOVER_DEBUG_CODE.TOBE.JS.defect", "params": {}}]}} {"id": "9679abb2f77581913b0c3b3c4dcf7265e660e1d17943b674525ad14ddb6ec852", "license": {"spdx": ["0BSD"], "repo": "benc-uk/hivematic", "path": "device/monitor.js", "repo_head_hexsha": "3a2cd3dc4ed6a0a306da01c5291ed6b9b618e4f0", "stack_hexsha": "15af6ea36b8ed73aee9a2cc7f0525603422ab353", "match": "repo_path"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Leftover debug code", "issueDescriptionEn": "The Leftover debug code checker finds debug code that remains not removed.\nDebug code may contain parts that output sensitive information or allow control over the system. If the program is deployed with debug code remaining, attackers may bypass an authentication process or access restricted information.\nRemove all debug code before deploying the application.", "issueLineNumber": 153, "entireCode": "//\n// HiveAlive RaspberryPi IOT monitoring\n// , 2018\n//\n\n// Get params\nif(process.argv.length < 3) { console.error(\"### No config filename provided. Exiting\"); process.exit(1); }\n\n// Load config\nvar config = JSON.parse(require('fs').readFileSync(process.argv[2]));\n\n// Static config values\nconst WAV_PATH = \"/tmp/hive-sound.wav\";\nconst LOGS = \"./logs\";\nconst BME680_SCRIPT = \"./py/bme680-collect.py\";\nconst GAS_BASELINE = 250000.0;\nconst HUMID_BASELINE = 20.0;\nconst HUMID_WEIGHT = 0.25;\n\n// IoT connection stuff\nvar clientFromConnectionString = require('azure-iot-device-mqtt').clientFromConnectionString;\nvar Message = require('azure-iot-device').Message;\nvar connectionString = `HostName=${config.iotEndpoint};DeviceId=${config.iotDeviceId};SharedAccessKey=${config.iotDeviceKey}`;\nvar client = clientFromConnectionString(connectionString);\n\n// OS and general Node things\nconst exec = require('child_process').exec;\nvar uuid = require('uuid/v4');\nconst utils = require('./utils');\nconst log = require('simple-node-logger').createSimpleLogger(`${LOGS}/${config.iotDeviceId}.log`);\nlog.setLevel('info');\n\n//\n// Callback when device connected, sets up the message sending loop\n//\nvar connect = function (err) {\n if (err) {\n log.error(`Could not connect: ${err}`);\n } else {\n log.info(`Device connected`);\n\n if(config.simulator) {\n tempPrev = 25;\n humPrev = 50;\n aqPrev = 50;\n soundPrev = -40;\n pressPrev = 1000;\n // Call the fake collector function every interval, loops forever\n setInterval(collectSimulatedData, config.pollInterval * 1000);\n collectSimulatedData();\n } else {\n // Call the real collector function every interval, loops forever\n setInterval(collectData, config.pollInterval * 1000);\n collectData();\n }\n }\n};\n\n//\n// Collect data and send to IOT hub\n//\nasync function collectData() {\n let temperature = NaN;\n let humidity = NaN;\n let airQuality = 23.601;\n let soundDb = NaN;\n let collectError = false\n\n log.info(`Starting data collection...`);\n\n // Start sound capture using arecord\n try {\n log.info(`Capturing ${config.soundLength} seconds of audio...`);\n let out = await utils.executeCommand(`arecord -D ${config.soundDev} -d ${config.soundLength} -f ${config.soundFormat} -r ${config.soundRate} ${WAV_PATH}`);\n } catch (error) {\n collectError = true;\n log.error(error);\n } \n\n utils.sleep(300); // Small delay helps prevent errors, file not closed, etc\n\n // Analyse sound using ffmpeg command, finding peak level\n try {\n let out = await utils.executeCommand(`ffmpeg -i ${WAV_PATH} -af astats=metadata=1:reset=1,ametadata=print:key=lavfi.astats.Overall.RMS_level -f null -`);\n let m = out.stderr.match(/RMS peak dB:\\s(.*?)\\n/i);\n \n soundDb = parseFloat(m[1]);\n\n // Filter outlier values\n if(soundDb < -100.0 || soundDb > 0) soundDb = NaN;\n } catch (error) {\n collectError = true;\n log.error(error);\n }\n\n // Call the BME680 sensor to get temperature, humidity, pressure and air quality\n try {\n let out = await utils.executeCommand(`python ${BME680_SCRIPT} ${config.bmeTime}`);\n let dhtValues = out.stdout.split(',');\n\n log.info('Got data from BME680 sensor');\n temperature = parseFloat(dhtValues[0].trim());\n pressure = parseFloat(dhtValues[1].trim());\n humidity = parseFloat(dhtValues[2].trim());\n gasResist = parseFloat(dhtValues[3].trim());\n\n var humidOffset = humidity - HUMID_BASELINE;\n var humidScore;\n if(humidOffset > 0) {\n humidScore = (100 - HUMID_BASELINE - humidOffset) / (100 - HUMID_BASELINE) * (HUMID_WEIGHT * 100);\n } else {\n humidScore = (HUMID_BASELINE + humidOffset) / HUMID_BASELINE * (HUMID_WEIGHT * 100);\n }\n\n var gasOffset = GAS_BASELINE - gasResist;\n var gasScore;\n if (gasOffset > 0) {\n gasScore = (gasResist / GAS_BASELINE) * (100 - (HUMID_WEIGHT * 100));\n } else {\n gasScore = 100 - (HUMID_WEIGHT * 100);\n }\n airQuality = humidScore + gasScore;\n\n // Filter outlier values\n if(humidity > 100) humidity = NaN;\n if(temperature < -10 || temperature > 60) temperature = NaN; \n } catch (error) {\n collectError = true;\n log.error(error);\n }\n\n // Format message object\n var msg = JSON.stringify({\n deviceId: config.iotDeviceId,\n uuid: uuid(),\n data: { \n temperature: temperature,\n humidity: humidity,\n airQuality: airQuality,\n soundDb: soundDb,\n pressure: pressure\n }\n });\n\n // Now send message to Azure\n var message = new Message(msg);\n if(!collectError) {\n log.info(`Sending message to Azure: ${message.getData()}`);\n client.sendEvent(message, (err, res) => {\n if(err) {\n log.error(`IOT HUB ERROR ${JSON.stringify(err)}`)\n } else {\n log.trace(`IOT RESULT ${JSON.stringify(res)}`);\n }\n });\n } else {\n log.error(`Skipping message sending due to error`); \n }\n}\n\nfunction collectSimulatedData() {\n let temperature = tempPrev + (Math.random() * 4) - 2; \n temperature = utils.clamp(temperature, 5, 50); \n tempPrev = temperature;\n let humidity = humPrev + (Math.random() * 8) - 4; \n humidity = utils.clamp(humidity, 0, 100);\n humPrev = humidity;\n let airQuality = aqPrev + (Math.random() * 8) - 4; \n airQuality = utils.clamp(airQuality, 0, 100);\n aqPrev = airQuality;\n let soundDb = soundPrev + (Math.random() * 4) - 2; \n soundDb = utils.clamp(soundDb, -100, 0);\n soundPrev = soundDb;\n let pressure = pressPrev + (Math.random() * 16) - 8; \n pressure = utils.clamp(pressure, 200, 1500);\n pressPrev = pressure; \n let collectError = false\n\n log.info(`Starting data collection...`);\n\n // Format message object\n var msg = JSON.stringify({\n deviceId: config.iotDeviceId,\n uuid: uuid(),\n data: { \n temperature: temperature,\n humidity: humidity,\n airQuality: airQuality,\n soundDb: soundDb,\n pressure: pressure\n }\n });\n\n // Now send message to Azure\n var message = new Message(msg);\n if(!collectError) {\n log.info(`Sending message to Azure: ${message.getData()}`);\n client.sendEvent(message, (err, res) => {\n if(err) {\n log.error(`IOT HUB ERROR ${JSON.stringify(err)}`)\n } else {\n log.trace(`IOT RESULT ${JSON.stringify(res)}`);\n }\n });\n } else {\n log.error(`Skipping message sending due to error`); \n }\n}\n\n//\n// Entry point\n//\nlog.info(`Device started with config: ${JSON.stringify(config)}`);\nclient.open(connect);", "dangerousExampleEn": "1. \nLine 3: A debug code is remaining.", "safeExampleEn": "1. \nLine 3: Remove the code used for debugging.", "contexts": [{"lineNo": 150, "eventType": "source", "messageKey": "synz.COMMON.branch.false.assumed", "params": {"arg0": "152"}}, {"lineNo": 153, "eventType": "sink", "messageKey": "jschk.LEFTOVER_DEBUG_CODE.TOBE.JS.defect", "params": {}}]}} {"id": "f4d62dc6ba3af484d207527c06091e4a9acf541f0005fcd4b4b706d989a5670a", "license": {"spdx": ["BSD-2-Clause"], "repo": "apankrat/note-detector", "path": "note-detector.js", "repo_head_hexsha": "6f02f29386190b84806115c06cccbf3ad2c27af7", "stack_hexsha": "ab12ed43b46ebc3c301ddc840d34ce5278270769", "match": "repo_path"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Leftover debug code", "issueDescriptionEn": "The Leftover debug code checker finds debug code that remains not removed.\nDebug code may contain parts that output sensitive information or allow control over the system. If the program is deployed with debug code remaining, attackers may bypass an authentication process or access restricted information.\nRemove all debug code before deploying the application.", "issueLineNumber": 379, "entireCode": "/*\n *\tCopyright (c) 2020 , <>\n *\thttps://swapped.ch/note-detector\n */\n\n/*\n *\tDistributed under the terms of the 2-clause BSD license. \n *\thttps://www.opensource.org/licenses/bsd-license.php\n */\n\nconst OnePi = 1 * Math.PI;\nconst TwoPi = 2 * Math.PI;\nconst FourPi = 4 * Math.PI;\n\nfunction sinc(x) { return x ? Math.sin(OnePi * x) / (OnePi * x) : 1; }\n\n/*\n *\n */\nconst tapers =\n{\n\t'raw' : null,\n\t'hann' : function(x) { return 1/2 - 1/2 * Math.cos(TwoPi * x); },\n\t'hamming' : function(x) { return 25/46 - 21/46 * Math.cos(TwoPi * x); },\n\t'blackman' : function(x) { return 0.42 - 0.50 * Math.cos(TwoPi * x) + 0.08 * Math.cos(FourPi * x); },\n\t'lanczos' : function(x) { return sinc(2 * x - 1); }\n}\n\nfunction applyWindow(arr, out, func)\n{\n\tif (arr.length != out.length)\n\t\tthrow 'Wrong in/out lengths';\n\n\tif (! func)\n\t\tfor (let i=0, n=arr.length; i 0) pos++;\n\n\t// skip until above zero again\n\twhile (pos < data.length && data[pos] <= 0) pos++;\n\n\twhile (pos < data.length)\n\t{\n\t\tlet pos_max = -1;\n\n\t\t// while above zero\n\t\twhile (pos < data.length && data[pos] > 0)\n\t\t{\n\t\t\tif (pos_max < 0 || data[pos] > data[pos_max])\n\t\t\t\tpos_max = pos;\n\t\t\tpos++;\n\t\t}\n\n\t\tif (pos_max != -1 && data[pos_max] >= threshold)\n\t\t\tpeaks.push(pos_max);\n\n\t\t// while below zero or zero\n\t\twhile (pos < data.length && data[pos] <= 0)\n\t\t\tpos++;\n\t}\n\n\treturn peaks;\n}\n\nfunction findMcLeodPeak(data, threshold, cutoff)\n{\n\t// as per \"A Smarter Way to Find Pitch\", see below\n\n\tvar peaks_x;\n\tvar peaks_q;\n\tvar peak_max;\n\tvar cutoff;\n\tvar i;\n\n\t// find peak positions\n\n\tpeaks_x = findPeaks(data, threshold);\n\tif (! peaks_x.length)\n\t\treturn -1;\n\n\t// refine them\n\n\tpeaks_q = [];\n\tpeak_max = -1;\n\tfor (i = 0; i < peaks_x.length; i++)\n\t{\n\t\tlet peak;\n\n\t\tpeak = getQuadraticPeak(data, peaks_x[i]);\n\t\tpeaks_q.push(peak);\n\t\tpeak_max = Math.max(peak_max, peak.y);\n\t}\n\n\t// find first large-enough peak\n\n\tcutoff = peak_max * cutoff;\n\tfor (i = 0; i < peaks_q.length; i++)\n\t\tif (peaks_q[i].y >= cutoff)\n\t\t\tbreak;\n\n\t// i < peaks_q.length\n\n\treturn peaks_q[i].x;\n}\n\n/*\n *\thttps://github.com/aubio/aubio/blob/master/src/pitch/pitchyin.c\n *\t+ minor changes\n */\nfunction Detector_yin(dataSize, sampleRate)\n{\n\tthis.conf =\n\t{\n\t\tthreshold: 0.20\n\t};\n\n\tthis.sampleRate = sampleRate;\n\tthis.tmp = new Float32Array(dataSize/2);\n\n\tthis.process = function(buf)\n\t{\n\t\tif (this.tmp.length != buf.length/2)\n\t\t\tthrow 'Wrong buf.length';\n\n\t\tvar yin = this.tmp;\n\t\tvar sum = 0;\n\t\tvar peak_pos = -1;\n\t\tvar min_pos = 0;\n\n\t\tyin[0] = 1.0;\n\n\t\tfor (let tau = 1; tau < yin.length; tau++)\n\t\t{\n\t\t\tyin[tau] = 0;\n\t\t\tfor (var j = 0; j < yin.length; j++)\n\t\t\t{\n\t\t\t\tvar diff = buf[j] - buf[j + tau];\n\t\t\t\tyin[tau] += diff * diff;\n\t\t\t}\n\n\t\t\tsum += yin[tau];\n\n\t\t\tif (sum) yin[tau] *= tau / sum;\n\t\t\telse yin[tau] = 1.;\n\n\t\t\tif (yin[tau] < yin[min_pos])\n\t\t\t\tmin_pos = tau;\n\n\t\t\tvar period = tau - 3;\n \n\t\t\tif (tau > 4 && \n\t\t\t yin[period] < this.conf.threshold &&\n\t\t\t yin[period] < yin[period + 1])\n\t\t\t{\n\t\t\t\tpeak_pos = period;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (peak_pos == -1)\n\t\t{\n\t\t\tpeak_pos = min_pos;\n\t\t\tif (yin[peak_pos] >= this.conf.threshold)\n\t\t\t\treturn -1;\n\t\t}\n\n\t\tvar t0 = getQuadraticPeak(yin, peak_pos).x;\n\t\tvar hz = t0 ? this.sampleRate / t0 : -1;\n\n\t\treturn hz;\n\t}\n}\n\n/*\n *\thttp://www.cs.otago.ac.nz/tartini/papers/A_Smarter_Way_to_Find_Pitch.pdf\n */\nfunction Detector_mpm(dataSize, sampleRate)\n{\n\tthis.conf =\n\t{\n\t\tpeak_ignore: 0.25, // ignore peaks smaller than this fraction of max\n\t\tpeak_cutoff: 0.93, // pick first peak that's larger than this fraction of max\n\t\tpitch_min: 80 // if we arrive at hz less than this, then fail detection\n\t};\n\n\tthis.sampleRate = sampleRate;\n\tthis.tmp = new Float32Array(dataSize);\n\n\tthis.process = function(buf)\n\t{\n\t\tif (this.tmp.length != buf.length)\n\t\t\tthrow 'Wrong buf.length';\n\n\t\tvar nsdf = this.tmp;\n\t\tvar peak;\n\t\tvar hz;\n\n\t\tnsdf.fill(0);\n\n\t\tfor (let tau = 0; tau < buf.length/2; tau++)\n\t\t{\n\t\t\tlet acf = 0;\n\t\t\tlet div = 0;\n\n\t\t\tfor (let i = 0; i+tau < buf.length; i++)\n\t\t\t{\n\t\t\t\tacf += buf[i] * buf[i+tau];\n\t\t\t\tdiv += buf[i] * buf[i] + buf[i + tau] * buf[i + tau];\n\t\t\t}\n\n\t\t\tnsdf[tau] = div ? 2 * acf / div : 0;\n\t\t}\n\n\t\tpeak = findMcLeodPeak(nsdf, this.conf.peak_ignore, this.conf.peak_cutoff);\n\t\thz = (peak > 0) ? this.sampleRate / peak : -1;\n\n\t\t// fail if an estimate is too low\n\n\t\treturn (hz < this.conf.pitch_min) ? -1 : hz;\n\t}\n};\n\n/*\n *\tBasic auto-correlation with MPM peak detection\n */\nfunction Detector_acx(dataSize, sampleRate) // acf2+\n{\n\tthis.conf =\n\t{\n\t\tvolume_min: 0.005,\n\t\tpeak_ignore: 0.00, // ignore peaks smaller than this fraction of max\n\t\tpeak_cutoff: 0.93, // pick first peak that's larger than this fraction of max\n\t};\n\n\tthis.sampleRate = sampleRate;\n\tthis.tmp = new Float32Array(dataSize);\n\n\tthis.process = function(buf)\n\t{\n\t\tif (this.tmp.length != buf.length)\n\t\t\tthrow 'Wrong buf.length';\n\n\t\tvar acfv = this.tmp;\n\t\tvar peak;\n\t\tvar hz;\n\n\t\tacfv.fill(0);\n\n\t\tfor (var tau = 0; tau < buf.length/2; tau++)\n\t\t{\n\t\t\tlet acf = 0;\n\t\t\tlet div = buf.length - tau;\n\n\t\t\tfor (var i=0; i+tau < buf.length; i++)\n\t\t\t\tacf += buf[i] * buf[i+tau];\n\n\t\t\tacfv[tau] = acf / div;\n\n\t\t\tif (tau == 0)\n\t\t\t{\n\t\t\t\tlet vol = Math.sqrt(acfv[0]);\n\t\t\t\tif (vol < this.conf.volume_min)\n\t\t\t\t\treturn -1;\n\t\t\t}\n\t\t}\n\n\t\tpeak = findMcLeodPeak(acfv, this.conf.peak_ignore, this.conf.peak_cutoff);\n\t\thz = (peak > 0) ? this.sampleRate / peak : -1;\n\n\t\treturn hz;\n\t}\n}\n\n/*\n *\n */\nfunction NoteDetector(dataSize, sampleRate, windowType)\n{\n\tthis.conf =\n\t{\n\t\tclose_threshold : 0.05, // 5%\n\n\t\ttrack_lone_ms : 100, // X ms of sustained lone estimate\n\t\ttrack_cons_ms : 50, // X ms of sustained consensus estimate\n\n\t\tdetrack_min_volume : 0.005,\n\t\tdetrack_est_none_ms : 500, // X ms of no estimates\n\t\tdetrack_est_some_ms : 250, // X ms of some estimates with no consensus\n\n\t\tstable_note_ms : 50,\n\t}\n\n\t//\n\tthis.trace = function(x) { }; // diagnostic trace\n\tthis.taper = tapers[windowType];\n\n\tthis.candidate = null;\n\tthis.tracking = null;\n\n\tthis.detectors =\n\t[\n\t\tnew Detector_acx(dataSize, sampleRate),\n\t\tnew Detector_yin(dataSize, sampleRate),\n\t\tnew Detector_mpm(dataSize, sampleRate)\n\t];\n\n\tthis.buf = new Float32Array(dataSize);\n\tthis.est = new Float32Array( this.detectors.length );\n\n\t//\n\tthis.update = function(data)\n\t{\n\t\tapplyWindow(data, this.buf, this.taper);\n\n\t\tvar est = this.est;\n\t\t\n\t\tfor (let i=0; i this.conf.track_cons_ms && ! this.candidate.lone)\n\t\t\t{\n\t\t\t\tthis.trace('** TRACKING by consensus');\n\t\t\t\tthis.startTracking_(this.candidate.freq, this.candidate.start);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (ms > this.conf.track_lone_ms && this.candidate.lone)\n\t\t\t{\n\t\t\t\tthis.trace('** TRACKING by lone estimate');\n\t\t\t\tthis.startTracking_(this.candidate.freq, this.candidate.start);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// still priming\n\t\t}\n\t}\n\n\tthis.getNote = function()\n\t{\n\t\tif (! this.tracking)\n\t\t\treturn null;\n\n\t\tlet ms = performance.now() - this.tracking.start;\n\t\treturn { freq: this.tracking.freq, stable: ms >= this.conf.stable_note_ms };\n\t}\n\n\t/*\n\t *\tinternals\n\t */\n\tthis.isClose_ = function(a, b)\n\t{\n\t\treturn Math.abs(a-b) < Math.abs(a+b) * 0.5 * this.conf.close_threshold;\n\t}\n\n\tthis.getConsensus_ = function(est)\n\t{\n\t\tlet res = { cons: 0, lone: 0 };\n\t\tlet num = 0;\n\n\t\tfor (let i=0; i+1 < est.length; i++)\n\t\t{\n\t\t\tif (est[i] <= 0)\n\t\t\t\tcontinue;\n\n\t\t\tif (res.lone == 0) res.lone = est[i];\n\t\t\telse res.lone = -1;\n\n\t\t\tfor (let j=i+1; i+j < est.length; j++)\n\t\t\t{\n\t\t\t\tif (est[j] <= 0)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tif (this.isClose_(est[i], est[j]))\n\t\t\t\t{\n\t\t\t\t\tres.cons += (est[i] + est[j])/2;\n\t\t\t\t\tnum++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (num)\n\t\t\tres.cons /= num;\n\n\t\t/*\n\t\t *\tif there's a consensus (2 out of 3 or 3 out of 3) -> ( res.cons > 0 && res.lone < 0 )\n\t\t *\tif there's no consensus and more than one estimate -> ( res.cons = 0 && res.lone < 0 )\n\t\t *\tif there's no consensus and exactly one estimate -> ( res.cons = 0 && res.lone > 0 )\n\t\t *\tif there are no estimates at all -> ( res.cons = 0 && res.lone = 0 )\n\t\t */\n\n\t\tif (res.cons || res.lone)\n\t\t{\n\t\t\tfunction v6(v) { return v.toFixed(0).toString().padStart(6); }\n\n\t\t\tlet x = '';\n\t\t\tfor (let i=0; i\nLine 3: A debug code is remaining.", "safeExampleEn": "1. \nLine 3: Remove the code used for debugging.", "contexts": [{"lineNo": 377, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "378"}}, {"lineNo": 379, "eventType": "sink", "messageKey": "jschk.LEFTOVER_DEBUG_CODE.TOBE.JS.defect", "params": {}}]}} {"id": "8906e855332345bfdc2c9dc97199789bca9ea2f7720c7acda20f274b8a18e188", "license": {"spdx": ["MIT"], "repo": "bebraw/schema2object", "path": "index.js", "repo_head_hexsha": "b41f536e95a1cb91e9a8120a73890cbf333550f0", "stack_hexsha": "9fec732452ee675d22ec0717f8314e9103d957c0", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Leftover debug code", "issueDescriptionEn": "The Leftover debug code checker finds debug code that remains not removed.\nDebug code may contain parts that output sensitive information or allow control over the system. If the program is deployed with debug code remaining, attackers may bypass an authentication process or access restricted information.\nRemove all debug code before deploying the application.", "issueLineNumber": 12, "entireCode": "'use strict';\n\nvar camelCase = require('camel-case');\nvar fp = require('annofp');\nvar math = require('annomath');\n\n\nexports.getRequiredProperties = function(definition) {\n var required = definition.required;\n\n if(!required) {\n return console.trace('missing required properties');\n }\n\n return fp.filter(function(k) {\n return required.indexOf(k) >= 0;\n }, definition.properties);\n};\n\nexports.properties2object = properties2object;\nfunction properties2object(o) {\n var generators = o.generators || {};\n var fieldGenerators = o.fieldGenerators || {};\n var properties = o.properties;\n var definitions = o.definitions;\n\n if(!properties) {\n return console.trace('missing properties');\n }\n\n definitions = definitions || {};\n properties = resolveRefs(properties, definitions);\n\n return fp.map(function(k, v) {\n if(v.enum) {\n return math.pick(v.enum);\n }\n\n if(v.type) {\n if(v.type === 'array') {\n var name = getReferenceName(v.items && v.items.$ref);\n var def = definitions[name];\n var generator;\n\n if(def) {\n generator = function() {\n return properties2object({\n generators: generators,\n fieldGenerators: fieldGenerators,\n properties: def.properties,\n definitions: definitions\n });\n };\n }\n\n return generators.array([v.minItems, v.maxItems], generator);\n }\n\n if(v.type === 'string' && v.format) {\n return generators[camelCase(v.format)]();\n }\n\n if(fieldGenerators[k]) {\n return fieldGenerators[k]();\n }\n\n return generators[v.type]();\n }\n\n console.warn('missing enum or type for', v);\n }, properties);\n}\n\nfunction resolveRefs(properties, definitions) {\n if(!definitions) {\n return properties;\n }\n\n return fp.map(function(k, v) {\n if(v.$ref) {\n var name = getReferenceName(v.$ref);\n var def = definitions[name];\n\n if(def) {\n return def;\n }\n\n return console.warn('missing reference for', name);\n }\n\n return v;\n }, properties);\n}\n\nfunction getReferenceName(ref) {\n if(ref) {\n return ref.split('/').slice(-1)[0];\n }\n}", "dangerousExampleEn": "1. \nLine 3: A debug code is remaining.", "safeExampleEn": "1. \nLine 3: Remove the code used for debugging.", "contexts": [{"lineNo": 11, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "11"}}, {"lineNo": 12, "eventType": "sink", "messageKey": "jschk.LEFTOVER_DEBUG_CODE.TOBE.JS.defect", "params": {}}]}} {"id": "b2bda94cb2fbca841841c2d91bbffac9d94894921a240abe4b51bb5f16ebdbe1", "license": {"spdx": ["MIT"], "repo": "bipbopme/search", "path": "lib/search.js", "repo_head_hexsha": "a0c80d1c8d98e55869e58d5d6101b324fa18a8d4", "stack_hexsha": "a83bce6d2721387f07db72087859c1114ed73f03", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of weak cryptographic algorithm", "issueDescriptionEn": "A hash function is a one-way function that receives data of different lengths and maps it to random data of a fixed length. It is commonly used to store user passwords because it always produces the same output for a given input.\nBecause hash can be calculated very quickly, the hash functions, such as MD5 and SHA, may give the illusion of high performance. However they are vulnerable to random brute-force attacks. If you use the hash functions on simple data, they can be saved in the rainbow table, making it insecure. In addition, RC2, RC3, RC4, RC5, RC6, MD4, and DES are also known to be vulnerable.\nThere are many functions used to overcome the disadvantages of MD5 and SHA.\nIn Node.js, bcrypt is one of the functions that is commonly used with outstanding performance and easily replace them. The latest hash algorithms, such as Argon2, PBKDF2, and Scrypt, are also good alternatives. Make sure to add a salt to the hash in SHA-2 i.e. SHA-224, SHA-256, SHA-384, SHA-512.", "issueLineNumber": 30, "entireCode": "import _ from 'lodash';\nimport bing from './bing';\nimport { enhanceResponse } from './enhancements';\nimport { sha1, delay } from './utils';\nimport { memoize } from './redis';\nimport { captureException } from './exceptions';\n\nconst MAX_RESPONSE_MS = 1800;\nconst DEFAULT_SEARCH_PARAMS = { count: 20 };\n\nasync function searchBingAndTransform(params) {\n const bingResponse = await bing.search(params);\n const response = {};\n\n response.queryContext = bingResponse.queryContext;\n response.stats = { totalEstimatedMatches: bingResponse.webPages?.totalEstimatedMatches || 0 };\n response.results =\n bingResponse.webPages?.value?.map(item => {\n // Pick primary attributes\n const result = _.pick(item, ['name', 'url', 'displayUrl', 'snippet', 'isNavigational']);\n\n // Pick primary attributes for deepLinks if included. Only include 4.\n if (item.deepLinks) {\n result.deepLinks = item.deepLinks\n .slice(0, 4)\n .map(deepLink => _.pick(deepLink, ['name', 'url', 'snippet']));\n }\n\n return {\n id: sha1(result.url),\n type: 'webPage',\n ...result\n };\n }) || [];\n\n return response;\n}\n\nconst searchBingAndTransformCached = memoize(searchBingAndTransform);\n\nexport async function precache(params) {\n searchBingAndTransform({ ...DEFAULT_SEARCH_PARAMS, ...params });\n}\n\nfunction getBestQuery(query, queryContext) {\n let cleanQuery = queryContext?.alteredQuery || queryContext?.originalQuery || query || '';\n\n cleanQuery = cleanQuery.toLowerCase();\n\n return cleanQuery;\n}\n\nexport async function search(params, geo) {\n const startTime = Date.now();\n\n const query = params.q;\n const response = await searchBingAndTransformCached({ ...DEFAULT_SEARCH_PARAMS, ...params });\n const bestQuery = getBestQuery(query, response.queryContext);\n\n const searchEndTime = Date.now();\n const searchElaspedTime = searchEndTime - startTime;\n const timeRemaining = MAX_RESPONSE_MS - searchElaspedTime;\n\n try {\n if (timeRemaining > 0) {\n await Promise.race([delay(timeRemaining), enhanceResponse(bestQuery, response, geo)]);\n }\n } catch (e) {\n captureException(e);\n }\n\n const endTime = Date.now();\n const totalTime = endTime - startTime;\n\n console.log('------------------------------------');\n console.log('Search:', `${searchElaspedTime}ms`);\n console.log('Remaining:', `${timeRemaining}ms`);\n console.log('Enhancements:', `${endTime - searchEndTime}ms`);\n console.log('Total:', `${totalTime}ms`);\n console.log('------------------------------------');\n\n response.stats.totalTime = totalTime;\n\n return response;\n}", "dangerousExampleEn": "1. var md5 = require('md5');\n2. \n3. console.log(md5('password'));\nLine 3: This is weak for the brute-force attack because it uses md5, a weak hash function.", "safeExampleEn": "1. var bcrypt = require('bcrypt');\n2. \n3. bcrypt.hash(\"password\", 13, function(err, hash) {\n4. console.log(hash);\n5. });\nLine 3: This is safe from the brute-force attack because bcrypt is used to create hash data.", "contexts": [{"lineNo": 30, "eventType": "sink", "messageKey": "jschk.FORBIDDEN.WEAK_ALGORITHM.JS.defect", "params": {"arg0": "sha1"}}]}} {"id": "121310da59b137e3b89ff1fff2f3069c10b4f85bb6aa680ad1fdcff8c258714b", "license": {"spdx": ["Unlicense", "MIT"], "repo": "RyanGladstone/screenshot-as-a-service", "path": "routes/index.js", "repo_head_hexsha": "eb7ad99884721f6eb049a227012e0d703f8a8aa0", "stack_hexsha": "c1f0bfc3d8866d3cd9ce6e1dc8dcfe394858c47c", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of weak cryptographic algorithm", "issueDescriptionEn": "A hash function is a one-way function that receives data of different lengths and maps it to random data of a fixed length. It is commonly used to store user passwords because it always produces the same output for a given input.\nBecause hash can be calculated very quickly, the hash functions, such as MD5 and SHA, may give the illusion of high performance. However they are vulnerable to random brute-force attacks. If you use the hash functions on simple data, they can be saved in the rainbow table, making it insecure. In addition, RC2, RC3, RC4, RC5, RC6, MD4, and DES are also known to be vulnerable.\nThere are many functions used to overcome the disadvantages of MD5 and SHA.\nIn Node.js, bcrypt is one of the functions that is commonly used with outstanding performance and easily replace them. The latest hash algorithms, such as Argon2, PBKDF2, and Scrypt, are also good alternatives. Make sure to add a salt to the hash in SHA-2 i.e. SHA-224, SHA-256, SHA-384, SHA-512.", "issueLineNumber": 27, "entireCode": "var utils = require('../lib/utils');\nvar join = require('path').join;\nvar fs = require('fs');\nvar path = require('path');\nvar request = require('request');\n\nmodule.exports = function(app, useCors) {\n var rasterizerService = app.settings.rasterizerService;\n var fileCleanerService = app.settings.fileCleanerService;\n\n // routes\n app.get('/', function(req, res, next) {\n if (!req.param('url', false)) {\n return res.redirect('/usage.html');\n }\n\n var url = utils.url(req.param('url'));\n // required options\n var options = {\n uri: 'http://localhost:' + rasterizerService.getPort() + '/',\n headers: { url: url }\n };\n ['width', 'height', 'clipRect', 'javascriptEnabled', 'loadImages', 'localToRemoteUrlAccessEnabled', 'userAgent', 'userName', 'password', 'delay'].forEach(function(name) {\n if (req.param(name, false)) options.headers[name] = req.param(name);\n });\n\n var filename = 'screenshot_' + utils.md5(url + JSON.stringify(options)) + '.png';\n options.headers.filename = filename;\n\n var filePath = join(rasterizerService.getPath(), filename);\n\n var callbackUrl = req.param('callback', false) ? utils.url(req.param('callback')) : false;\n\n if (fs.existsSync(filePath)) {\n console.log('Request for %s - Found in cache', url);\n processImageUsingCache(filePath, res, callbackUrl, function(err) { if (err) next(err); });\n return;\n }\n console.log('Request for %s - Rasterizing it', url);\n processImageUsingRasterizer(options, filePath, res, callbackUrl, function(err) { if(err) next(err); });\n });\n\n app.get('*', function(req, res, next) {\n // for backwards compatibility, try redirecting to the main route if the request looks like /www.google.com\n res.redirect('/?url=' + req.url.substring(1));\n });\n\n // bits of logic\n var processImageUsingCache = function(filePath, res, url, callback) {\n if (url) {\n // asynchronous\n res.send('Will post screenshot to ' + url + ' when processed');\n postImageToUrl(filePath, url, callback);\n } else {\n // synchronous\n sendImageInResponse(filePath, res, callback);\n }\n }\n\n var processImageUsingRasterizer = function(rasterizerOptions, filePath, res, url, callback) {\n if (url) {\n // asynchronous\n res.send('Will post screenshot to ' + url + ' when processed');\n callRasterizer(rasterizerOptions, function(error) {\n if (error) return callback(error);\n postImageToUrl(filePath, url, callback);\n });\n } else {\n // synchronous\n callRasterizer(rasterizerOptions, function(error) {\n if (error) return callback(error);\n sendImageInResponse(filePath, res, callback);\n });\n }\n }\n\n var callRasterizer = function(rasterizerOptions, callback) {\n request.get(rasterizerOptions, function(error, response, body) {\n if (error || response.statusCode != 200) {\n console.log('Error while requesting the rasterizer: %s', error.message);\n rasterizerService.restartService();\n return callback(new Error(body));\n }\n else if (body.indexOf('Error: ') == 0) {\n var errmsg = body.substring(7);\n console.log('Error while requesting the rasterizer: %s', errmsg);\n return callback(new Error(errmsg));\n }\n callback(null);\n });\n }\n\n var postImageToUrl = function(imagePath, url, callback) {\n console.log('Streaming image to %s', url);\n var fileStream = fs.createReadStream(imagePath);\n fileStream.on('end', function() {\n fileCleanerService.addFile(imagePath);\n });\n fileStream.on('error', function(err){\n console.log('Error while reading file: %s', err.message);\n callback(err);\n });\n fileStream.pipe(request.post(url, function(err) {\n if (err) console.log('Error while streaming screenshot: %s', err);\n callback(err);\n }));\n }\n\n var sendImageInResponse = function(imagePath, res, callback) {\n console.log('Sending image in response');\n if (useCors) {\n res.setHeader(\"Access-Control-Allow-Origin\", \"*\");\n res.setHeader(\"Access-Control-Expose-Headers\", \"Content-Type\");\n }\n res.sendfile(imagePath, function(err) {\n fileCleanerService.addFile(imagePath);\n callback(err);\n });\n }\n\n};", "dangerousExampleEn": "1. var md5 = require('md5');\n2. \n3. console.log(md5('password'));\nLine 3: This is weak for the brute-force attack because it uses md5, a weak hash function.", "safeExampleEn": "1. var bcrypt = require('bcrypt');\n2. \n3. bcrypt.hash(\"password\", 13, function(err, hash) {\n4. console.log(hash);\n5. });\nLine 3: This is safe from the brute-force attack because bcrypt is used to create hash data.", "contexts": [{"lineNo": 27, "eventType": "sink", "messageKey": "jschk.FORBIDDEN.WEAK_ALGORITHM.JS.defect", "params": {"arg0": "md5"}}]}} {"id": "5efe206da087d401eddbbf4c0c088f6cf75af029f0bafeeea4a45d92a6e1f9a8", "license": {"spdx": ["MIT"], "repo": "leizongmin/node-doc-cn", "path": "tool/format_content.js", "repo_head_hexsha": "d522babe95c1a90b6d2f8c5010c4f155daede921", "stack_hexsha": "7314e679ab459f1515a898ffaaa60c3451416b67", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of weak cryptographic algorithm", "issueDescriptionEn": "A hash function is a one-way function that receives data of different lengths and maps it to random data of a fixed length. It is commonly used to store user passwords because it always produces the same output for a given input.\nBecause hash can be calculated very quickly, the hash functions, such as MD5 and SHA, may give the illusion of high performance. However they are vulnerable to random brute-force attacks. If you use the hash functions on simple data, they can be saved in the rainbow table, making it insecure. In addition, RC2, RC3, RC4, RC5, RC6, MD4, and DES are also known to be vulnerable.\nThere are many functions used to overcome the disadvantages of MD5 and SHA.\nIn Node.js, bcrypt is one of the functions that is commonly used with outstanding performance and easily replace them. The latest hash algorithms, such as Argon2, PBKDF2, and Scrypt, are also good alternatives. Make sure to add a salt to the hash in SHA-2 i.e. SHA-224, SHA-256, SHA-384, SHA-512.", "issueLineNumber": 27, "entireCode": "/**\n * 格式化英文内容,统一换行符,去掉首行的空行,重新生成hash值\n */\n\nvar async = require('async');\nvar config = require('../config');\nvar utils = require('./utils');\nvar db = config.mysql;\n\n\nconsole.log('查询出所有记录...');\ndb.select('origin_api', '*', '1', function (err, list) {\n if (err) throw err;\n\n console.log(' 共%d条数据', list.length);\n\n async.eachSeries(list, function (item, next) {\n\n // 统一换行符\n var content = utils.standardLineBreak(item.content);\n var lines = content.split(/\\n/);\n if (lines[0].trim() === '') {\n lines.shift();\n content = lines.join('\\n');\n }\n\n var hash = utils.md5(content).toLowerCase();\n if (hash === item.hash) return next();\n\n console.log('更新:[%d] %s => %s', item.id, item.hash, hash);\n\n db.update('origin_api', '`id`=' + item.id, {hash: hash, content: content}, function (err) {\n if (err) return next(err);\n\n db.update('translate_api', '`origin_hash`=' + db.escape(item.hash), {origin_hash: hash}, function (err, info) {\n if (err) return next(err);\n\n console.log(' 更新了%d条翻译', info.affectedRows);\n next();\n });\n });\n\n }, function (err) {\n if (err) throw err;\n\n console.log('完成');\n process.exit();\n });\n});", "dangerousExampleEn": "1. var md5 = require('md5');\n2. \n3. console.log(md5('password'));\nLine 3: This is weak for the brute-force attack because it uses md5, a weak hash function.", "safeExampleEn": "1. var bcrypt = require('bcrypt');\n2. \n3. bcrypt.hash(\"password\", 13, function(err, hash) {\n4. console.log(hash);\n5. });\nLine 3: This is safe from the brute-force attack because bcrypt is used to create hash data.", "contexts": [{"lineNo": 27, "eventType": "sink", "messageKey": "jschk.FORBIDDEN.WEAK_ALGORITHM.JS.defect", "params": {"arg0": "md5"}}]}} {"id": "f63db3654a1303469d940ad2bbcc5f21b807df6d5c10e38ffea6bc7dfa28a33b", "license": {"spdx": ["MIT"], "repo": "hezurong/int", "path": "client/Peer/account_node.js", "repo_head_hexsha": "500ad8141486b5fcb9985b8164c4e1101e43da9f", "stack_hexsha": "ab13eb02dc9f380806be09548ab5e950aeead5e4", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of weak cryptographic algorithm", "issueDescriptionEn": "A hash function is a one-way function that receives data of different lengths and maps it to random data of a fixed length. It is commonly used to store user passwords because it always produces the same output for a given input.\nBecause hash can be calculated very quickly, the hash functions, such as MD5 and SHA, may give the illusion of high performance. However they are vulnerable to random brute-force attacks. If you use the hash functions on simple data, they can be saved in the rainbow table, making it insecure. In addition, RC2, RC3, RC4, RC5, RC6, MD4, and DES are also known to be vulnerable.\nThere are many functions used to overcome the disadvantages of MD5 and SHA.\nIn Node.js, bcrypt is one of the functions that is commonly used with outstanding performance and easily replace them. The latest hash algorithms, such as Argon2, PBKDF2, and Scrypt, are also good alternatives. Make sure to add a salt to the hash in SHA-2 i.e. SHA-224, SHA-256, SHA-384, SHA-512.", "issueLineNumber": 247, "entireCode": "//account_node是一种必须绑定有效的Account才能工作的Node,由BlockNode派生,派生出SuperNode和MinerNode\nconst BlockNode = require('./block_node');\nconst KeyRing = require('../../chainlib/Account/keyring');\nconst assert = require('assert');\nconst DPackage = require('./package');\nconst digest = require('../../chainlib/Crypto/digest');\nconst LockSimple = require('../../chainlib/Utils/LockSimple');\n\nclass AccountNode extends BlockNode {\n constructor(params) {\n assert(params.accountWif);\n const account = KeyRing.fromSecret(params.accountWif);\n assert(account, 'MUST input valid acountWIF!');\n const address = account.getAddress();\n // generate peerid from account when peerid is null\n if (!params.protocolConfig.peerid) {\n params.protocolConfig.peerid = address.toString();\n }\n\n super(params.protocolConfig);\n\n this.m_account = account;\n this.m_address = address;\n\n this.dBFTingEx = new Map();\n this.deletedBFTing = []; //已经处于删除状态的了\n this.dBFTingFilter = {};\n this.locklist = new Map();\n this.dBFingPeerids = [];\n\n setInterval(() => {\n while (true) {\n if (this.deletedBFTing.length === 0) {\n break;\n }\n //删除后5s在清理,防止有些延迟返回\n if (Date.now() >= this.deletedBFTing[0].deleteTime + 10*1000) {\n this.dBFTingEx.delete(this.deletedBFTing[0].key);\n this.deletedBFTing.shift();\n } else {\n break;\n }\n }\n }, 3000);\n }\n\n //根据拜占庭共识的类型来确定需要过滤的节点\n _setFilterByBftType(type, filter) {\n if (filter) {\n this.dBFTingFilter[type.toString()] = filter;\n }\n }\n\n updateBFTingPeerids(peerids) {\n this.dBFingPeerids = []\n this.dBFingPeerids = this.dBFingPeerids.concat(peerids);\n }\n\n deleteBFTing(key) {\n if (!this.dBFTingEx.has(key)) {\n return;\n }\n\n let info = this.dBFTingEx.get(key);\n if (info.delete === 1) {\n return ;\n }\n if (info['timerid'] && info['timerid'] !== 0) {\n clearTimeout(info['timerid']);\n info['timerid'] = 0;\n }\n\n info.delete = 1;\n this.deletedBFTing.push({key: key, deleteTime: Date.now()});\n }\n\n getLock(_type) {\n if (this.locklist.has(_type)) {\n return this.locklist.get(_type);\n }\n\n let lock = new LockSimple();\n this.locklist.set(_type,lock);\n return lock;\n }\n\n addConsensus(key, data, type,peerid,selfpeerid) {\n if (this.dBFTingEx.has(key)) {\n return;\n }\n\n let info = {selfpeerid: selfpeerid,noagreeCount: 0, agreeCount: 0,peerid:peerid,totalCount:0,data:data,type:type,key:key,peerids: new Map()};\n info.timerid = setTimeout(async () => {\n console.log('[account_node addConsensus] timeout,'+ this.m_address.toString() + ' finish,type='+info.type.toString()+' reulst=false key='+info.key.toString());\n this.deleteBFTing(key);\n await this._onBFTFinishEx(info.type, info.data,false);\n }, 3*1000);\n this.dBFTingEx.set(key, info);\n this.updatePeerlist(key, this.dBFingPeerids);\n }\n\n hasConsensus(key) {\n return this.dBFTingEx.has(key);\n }\n\n isSended(key) {\n return this.dBFTingEx.get(key).sended;\n }\n\n setSended(key) {\n this.dBFTingEx.get(key).sended = true;\n }\n\n acceptConsensus(key, peerid) {\n let info = this.dBFTingEx.get(key);\n if (peerid === info.selfpeerid && !info.peerids.has(peerid)) {\n info.peerids.set(peerid,'-1');\n }\n if (!info.peerids.has(peerid) || info.peerids.get(peerid) !== '-1'){\n return ;\n }\n info.peerids.set(peerid,'1');\n info.agreeCount++;\n }\n\n rejectConsensus(key, peerid) {\n let info = this.dBFTingEx.get(key);\n if (peerid === info.selfpeerid && !info.peerids.has(peerid)) {\n info.peerids.set(peerid,'-1');\n }\n if (!info.peerids.has(peerid) || info.peerids.get(peerid) !== '-1'){\n return ;\n }\n info.peerids.set(peerid,'0');\n info.noagreeCount++;\n }\n\n isDeletedConsensus(key) {\n let info = this.dBFTingEx.get(key);\n if (!info) {\n return true;\n }\n\n if (info.delete && info.delete === 1) {\n return true;\n }\n\n return false;\n }\n\n getOpinion(key,peerid) {\n let info = this.dBFTingEx.get(key);\n if (!info) {\n //console.log(`[account_node getOpinion] 1 key=${key},peerid=${peerid}`);\n return false;\n }\n\n if (!info.peerids.has(peerid) || info.peerids.get(peerid) === '-1'){\n //console.log(`[account_node getOpinion] 2 key=${key},peerid=${peerid}`);\n return false;\n }\n\n if (info.peerids.get(peerid) === '1') {\n //console.log(`[account_node getOpinion] 3 key=${key},peerid=${peerid}`);\n return true;\n }\n //console.log(`[account_node getOpinion] 4 key=${key},peerid=${peerid}`);\n return false;\n }\n\n /*return:[bFinish,bResult]\n bFinish:协商是否结束\n bResult:结果是否通过\n */\n checkConsensus(key) {\n let info = this.dBFTingEx.get(key);\n if (!info) {\n //console.log(`[account_node,checkConsensus] 1 key=${key}`);\n return [false,false];\n }\n\n if (info.totalCount === 0) {\n //表明已经删除了超时发来的\n return [true, false];\n }\n\n if (this.isDeletedConsensus(key)) {\n //console.log(`[account_node,checkConsensus] 2 key=${key}`);\n return [true,false];\n }\n\n let n = Math.ceil(info.totalCount*2/3); //三分之二\n if (info.agreeCount >= n) {\n //console.log(`[account_node,checkConsensus] 3 key=${key} total=${info.totalCount} agree=${info.agreeCount},noagree=${info.noagreeCount}`);\n return [true,true]\n }\n\n if (info.noagreeCount >= n) {\n console.log(`[account_node,checkConsensus] 4 key=${key} total=${info.totalCount} agree=${info.agreeCount},noagree=${info.noagreeCount}`);\n return [true,false];\n }\n\n if (info.totalCount === info.agreeCount + info.noagreeCount) {\n console.log(`[account_node,checkConsensus] 5 key=${key} total=${info.totalCount} agree=${info.agreeCount},noagree=${info.noagreeCount}`);\n return [true,false];\n }\n //console.log(`[account_node,checkConsensus] 6 key=${key} total=${info.totalCount} agree=${info.agreeCount},noagree=${info.noagreeCount}`);\n\n return [false,false];\n }\n\n updatePeerlist(key, peerlist) {\n let info = this.dBFTingEx.get(key);\n info.totalCount = peerlist.length;\n for (let peerid of peerlist) {\n if (!info.peerids.has(peerid)) {\n info.peerids.set(peerid,'-1');\n }\n }\n }\n\n getConsensusData(key) {\n let info = this.dBFTingEx.get(key);\n if (!info) {\n return null;\n }\n return info.data;\n }\n\n\n\n /*\n type:进行拜占庭共识的类型\n sig:内容的标识\n peerid:发起共识的节点,如果为空或者null,表示自己\n data:共识的数据\n */\n async _beginBFTEx(type, sig, peerid, data) {\n if (!peerid || peerid === \"\") {\n peerid = this.m_address.toString();\n }\n let selfAgree = true;\n if (peerid === this.peerid) {\n let [bRet, resp] = await this._onDBFTEx(type, data, this.peerid);\n selfAgree = bRet;\n }\n let key = digest.md5(sig).toString('hex') + peerid;\n console.log(`[account_node _beginBFTEx] key=${key}`);\n if (!this.dBFTingEx.has(key)) {\n this.addConsensus(key, data,type,peerid,this.peerid);\n }\n if (this.isSended(key)) {\n return;\n }\n this.setSended(key);\n\n let info = this.dBFTingEx.get(key);\n\n let filter = null;\n if (type.toString() in this.dBFTingFilter) {\n filter = this.dBFTingFilter[type.toString()];\n }\n\n let newFilter = (conn) => {\n if (filter && !filter(conn)) {\n //console.log(this.m_address.toString()+\" not send to \"+conn.remote.peerid.toString());\n return false;\n }\n\n if (!info.peerids.has(conn.remote.peerid)) {\n return false;\n }\n //不广播给发送者\n // if (conn.remote.peerid === peerid) {\n // //console.log(this.m_address.toString()+\" not send to=== \"+conn.remote.peerid.toString()+\" faqi peerid=\"+peerid.toString());\n // return false;\n // }\n\n // console.log('[account_node _beginBFTEx]'+this.m_address.toString()+\" send to \"+conn.remote.peerid.toString()+' key='+key);\n\n return true\n };\n\n this._broadcast(DPackage.createStreamWriter({ cmdType: DPackage.CMD_TYPE.dbft }, { type: type, sig: sig, peerid: peerid}, data.length).writeData(data), -1\n , newFilter, null);\n if (selfAgree) {\n this.acceptConsensus(key, this.peerid);\n } else {\n this.rejectConsensus(key,this.peerid);\n }\n if (this.dBFingPeerids.length === 1) {\n this.deleteBFTing(key);\n console.log('[account_node _beginBFTEx]' + this.m_address.toString() + ' finish,type='+type.toString()+' reulst='+selfAgree.toString()+' key='+key.toString());\n await this._onBFTFinishEx(type, data,selfAgree);\n }\n }\n\n async _onPkg(conn, pkg) {\n let lock = this.getLock(pkg.body.type)\n await lock.enter();\n let data = pkg.data[0];\n let remotePeerid = conn.remote.peerid;\n if (pkg.header.cmdType === DPackage.CMD_TYPE.dbft) {\n let key = digest.md5(pkg.body.sig).toString('hex') + pkg.body.peerid;\n console.log('[account_node _onPkg DPackage.CMD_TYPE.dbft]' +this.m_address.toString()+' receive from '+remotePeerid.toString()+',type='+pkg.body.type.toString()+' key='+key);\n if (!this.hasConsensus(key)) {\n let [bRet, resp] = await this._onDBFTEx(pkg.body.type, data, remotePeerid);\n this.addConsensus(key, data, pkg.body.type, pkg.body.peerid,this.peerid);\n if (bRet) {\n this.acceptConsensus(key,this.peerid);\n } else {\n this.rejectConsensus(key,this.peerid);\n }\n }\n if (remotePeerid === pkg.body.peerid) {\n //只广播\"将军\"的消息\n await this._beginBFTEx(pkg.body.type, pkg.body.sig, pkg.body.peerid, data);\n }\n\n //回复conn.remote.peerid\n let bAgree = this.getOpinion(key,this.peerid);\n //console.log('[account_node _onPkg DPackage.CMD_TYPE.dbft]' +this.m_address.toString()+',ansert '+remotePeerid.toString()+',type='+pkg.body.type.toString()+',reulst='+bAgree.toString()+',key='+key);\n DPackage.createStreamWriter({ cmdType: DPackage.CMD_TYPE.dbftResp }, { type: pkg.body.type, sig: pkg.body.sig, peerid: pkg.body.peerid,result: bAgree?'1':'0'}, 0).bind(conn);\n }\n else if (pkg.header.cmdType === DPackage.CMD_TYPE.dbftResp) {\n let key = digest.md5(pkg.body.sig).toString('hex') + pkg.body.peerid;\n console.log('[account_node _onPkg DPackage.CMD_TYPE.dbftResp]' + this.m_address.toString() + ' receive from '+remotePeerid.toString()+',type='+pkg.body.type.toString()+',reulst='+pkg.body.result.toString()+',key='+key.toString());\n if (!this.hasConsensus(key) || this.isDeletedConsensus(key)) {\n await lock.leave();\n return;\n }\n assert(this.hasConsensus(key));\n if (pkg.body.result === '1') {\n this.acceptConsensus(key, remotePeerid);\n } else {\n this.rejectConsensus(key, remotePeerid);\n }\n let [bFinish,bResult] = this.checkConsensus(key);\n if (bFinish) {\n let data = this.getConsensusData(key);\n this.deleteBFTing(key);\n console.log('[account_node _onPkg DPackage.CMD_TYPE.dbftResp]' + this.m_address.toString() + ' finish,type='+pkg.body.type.toString()+' reulst='+bResult.toString()+' key='+key.toString());\n await this._onBFTFinishEx(pkg.body.type, data,bResult);\n }\n } else {\n //super._onPkg(conn, pkg);\n }\n await lock.leave();\n }\n\n //返回true or false 表示同意协商的结果|不同意\n async _onDBFTEx(type,data,fromPeerid) { }\n async _onDBFTRespEx(type,data) { }\n async _onBFTFinishEx(type,data,bSucc) { }\n}\n\nmodule.exports = AccountNode;", "dangerousExampleEn": "1. var md5 = require('md5');\n2. \n3. console.log(md5('password'));\nLine 3: This is weak for the brute-force attack because it uses md5, a weak hash function.", "safeExampleEn": "1. var bcrypt = require('bcrypt');\n2. \n3. bcrypt.hash(\"password\", 13, function(err, hash) {\n4. console.log(hash);\n5. });\nLine 3: This is safe from the brute-force attack because bcrypt is used to create hash data.", "contexts": [{"lineNo": 247, "eventType": "sink", "messageKey": "jschk.FORBIDDEN.WEAK_ALGORITHM.JS.defect", "params": {"arg0": "md5"}}]}} {"id": "49f503109fb97525b352b0b77016fd169f1ebc2638982f29d6c8d84514ad34e7", "license": {"spdx": ["Apache-2.0"], "repo": "botdio/botd", "path": "shell/stack.js", "repo_head_hexsha": "4e0be8057a1070b3199bf1681f609c95e0f50404", "stack_hexsha": "b534ba050e79aa60b61477947f6c6b14cca83a01", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of weak cryptographic algorithm", "issueDescriptionEn": "A hash function is a one-way function that receives data of different lengths and maps it to random data of a fixed length. It is commonly used to store user passwords because it always produces the same output for a given input.\nBecause hash can be calculated very quickly, the hash functions, such as MD5 and SHA, may give the illusion of high performance. However they are vulnerable to random brute-force attacks. If you use the hash functions on simple data, they can be saved in the rainbow table, making it insecure. In addition, RC2, RC3, RC4, RC5, RC6, MD4, and DES are also known to be vulnerable.\nThere are many functions used to overcome the disadvantages of MD5 and SHA.\nIn Node.js, bcrypt is one of the functions that is commonly used with outstanding performance and easily replace them. The latest hash algorithms, such as Argon2, PBKDF2, and Scrypt, are also good alternatives. Make sure to add a salt to the hash in SHA-2 i.e. SHA-224, SHA-256, SHA-384, SHA-512.", "issueLineNumber": 8, "entireCode": "'use strict';\nvar md5 = require('js-md5');\n\nclass Stack {\n constructor(code, db, ts) {\n this._code = code;\n this._ts = ts;\n this._hash = md5(code);\n this._old = JSON.stringify(db);\n }\n ts() {\n return this._ts;\n }\n code() {\n return this._code;\n }\n hash() {\n return this._hash;\n }\n oldDbStr() {\n return this._old;\n }\n oldDbSize() {\n return this._old.length;\n }\n}\n\nmodule.exports = Stack;", "dangerousExampleEn": "1. var md5 = require('md5');\n2. \n3. console.log(md5('password'));\nLine 3: This is weak for the brute-force attack because it uses md5, a weak hash function.", "safeExampleEn": "1. var bcrypt = require('bcrypt');\n2. \n3. bcrypt.hash(\"password\", 13, function(err, hash) {\n4. console.log(hash);\n5. });\nLine 3: This is safe from the brute-force attack because bcrypt is used to create hash data.", "contexts": [{"lineNo": 8, "eventType": "sink", "messageKey": "jschk.FORBIDDEN.WEAK_ALGORITHM.JS.defect", "params": {"arg0": "md5"}}]}} {"id": "cf4e3c0051797c50ebf009efaa87c22d2e112b1d60aa55a1a298aa175d4edaaa", "license": {"spdx": ["MIT"], "repo": "ShaneH12/PhotoSharingApp", "path": "photosharing/src/components/view/CreatePost.js", "repo_head_hexsha": "6ac9ec5552a2c6f33ac79a2f880420e7b678b7eb", "stack_hexsha": "97a4cd08eb69f0952e98af09cf1097cf453968b3", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of weak cryptographic algorithm", "issueDescriptionEn": "A hash function is a one-way function that receives data of different lengths and maps it to random data of a fixed length. It is commonly used to store user passwords because it always produces the same output for a given input.\nBecause hash can be calculated very quickly, the hash functions, such as MD5 and SHA, may give the illusion of high performance. However they are vulnerable to random brute-force attacks. If you use the hash functions on simple data, they can be saved in the rainbow table, making it insecure. In addition, RC2, RC3, RC4, RC5, RC6, MD4, and DES are also known to be vulnerable.\nThere are many functions used to overcome the disadvantages of MD5 and SHA.\nIn Node.js, bcrypt is one of the functions that is commonly used with outstanding performance and easily replace them. The latest hash algorithms, such as Argon2, PBKDF2, and Scrypt, are also good alternatives. Make sure to add a salt to the hash in SHA-2 i.e. SHA-224, SHA-256, SHA-384, SHA-512.", "issueLineNumber": 58, "entireCode": "import React, { Component } from 'react'\nimport Dropzone from 'react-dropzone'\nimport sha1 from 'sha1'\nimport { APIManager } from '../../utils'\n\nclass CreatePost extends Component {\n\n\tconstructor(){\n\t\tsuper()\n\t\tthis.state = {\n\t\t\tpost: {\n\t\t\t\timage: '',\n\t\t\t\tcaption: ''\n\t\t\t}\n\t\t}\n\t}\n\n\tupdatePost(event){\n\t\tevent.preventDefault()\n\t\tlet updated = Object.assign({}, this.state.post)\n\t\tupdated[event.target.id] = event.target.value\n\t\tthis.setState({\n\t\t\tpost: updated\n\t\t})\n\t}\n\n\tsubmitPost(event){\n\t\tevent.preventDefault()\n//\t\tconsole.log('subimtPost: '+JSON.stringify(this.state.post))\n\n\t\tif (this.state.post.image.length == 0){\n\t\t\talert('Add an image.')\n\t\t\treturn\n\t\t}\n\n\t\tif (this.state.post.caption.length == 0){\n\t\t\talert('Add a caption.')\n\t\t\treturn\n\t\t}\n\n\t\tlet updated = Object.assign({}, this.state.post)\n\t\tthis.props.onCreate(updated)\n\t}\n\n\t// Connecting uploads to Cloudinary account\n\timageSelected(files){\n\t\tconsole.log('imageSelected: ')\n\t\tconst image = files[0]\n\n\t\tconst cloudName = ''\n\t\tconst url = 'https://api.cloudinary.com/v1_1/'+cloudName+'/image/upload'\n\n\t\tconst timestamp = Date.now()/1000\n\t\tconst uploadPreset = ''\n\n\t\tconst paramsStr = 'timestamp='+timestamp+'&upload_preset='+uploadPreset+''\n\n\t\tconst signature = sha1(paramsStr)\n\t\tconst params = {\n\t\t\t'api_key': '',\n\t\t\t'timestamp': timestamp,\n\t\t\t'upload_preset': uploadPreset,\n\t\t\t'signature': signature\n\t\t}\n\n\t\tAPIManager.uploadFile(url, image, params)\n\t\t.then((uploaded) => {\n\t\t\tconsole.log('Upload Complete: '+JSON.stringify(uploaded))\n\t\t\tlet updated = Object.assign({}, this.state.post)\n\t\t\tupdated['image'] = uploaded['secure_url']\n\t\t\tthis.setState({\n\t\t\t\tpost: updated\n\t\t\t})\n\n\n\t\t})\n\t\t.catch((err) => {\n\t\t\talert(err)\n\t\t})\n\n\n\t}\n\n\trender(){\n\t\treturn (\n\t\t\t
    \n\t\t\t\t

    Submit Post

    \n\t\t\t\t\n\t\t\t\t
    \n\t\t\t\t\t
    \n\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t
    \n\t\t\t\t\t
    \n\t\t\t\t\t\t\n\t\t\t\t\t
    \n\t\t\t\t\t
    \n\t\t\t\t\t\t\n\t\t\t\t\t
    \n\t\t\t\t
    \n\n\t\t\t\t


    \n\t\t\t
    \n\t\t)\n\t}\n}\n\nexport default CreatePost", "dangerousExampleEn": "1. var md5 = require('md5');\n2. \n3. console.log(md5('password'));\nLine 3: This is weak for the brute-force attack because it uses md5, a weak hash function.", "safeExampleEn": "1. var bcrypt = require('bcrypt');\n2. \n3. bcrypt.hash(\"password\", 13, function(err, hash) {\n4. console.log(hash);\n5. });\nLine 3: This is safe from the brute-force attack because bcrypt is used to create hash data.", "contexts": [{"lineNo": 58, "eventType": "sink", "messageKey": "jschk.FORBIDDEN.WEAK_ALGORITHM.JS.defect", "params": {"arg0": "sha1"}}]}} {"id": "41ff63f292c49225220081882b0243298abdf2091a42b6ef559337e0b8b205ff", "license": {"spdx": ["MIT"], "repo": "InfoCompass/backend", "path": "public_api/translations.js", "repo_head_hexsha": "ea8f0cf20f951fbe8bdd692871404772668a8357", "stack_hexsha": "90969c406392a3d237a1cd7b3a6ef9087b191e95", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of weak cryptographic algorithm", "issueDescriptionEn": "A hash function is a one-way function that receives data of different lengths and maps it to random data of a fixed length. It is commonly used to store user passwords because it always produces the same output for a given input.\nBecause hash can be calculated very quickly, the hash functions, such as MD5 and SHA, may give the illusion of high performance. However they are vulnerable to random brute-force attacks. If you use the hash functions on simple data, they can be saved in the rainbow table, making it insecure. In addition, RC2, RC3, RC4, RC5, RC6, MD4, and DES are also known to be vulnerable.\nThere are many functions used to overcome the disadvantages of MD5 and SHA.\nIn Node.js, bcrypt is one of the functions that is commonly used with outstanding performance and easily replace them. The latest hash algorithms, such as Argon2, PBKDF2, and Scrypt, are also good alternatives. Make sure to add a salt to the hash in SHA-2 i.e. SHA-224, SHA-256, SHA-384, SHA-512.", "issueLineNumber": 29, "entireCode": "import\t{\tgetTranslation\t\t\t}\tfrom '../ic-utils.js'\n\nimport\t{\tproperties as icProperties\t}\tfrom './ic-item-config.cjs'\nimport\tcrypto\t\t\t\t\t\t\t\tfrom 'crypto'\t\n\n\nexport class Translator{\n\n\tconstructor(\n\t\tdb,\n\t\tkeys,\t\t\n\t){\n\n\t\tconst { googleTranslateApiKey, deepLApiKey} = keys\n\n\t\tthis.db \t\t\t= db\n\t\tthis.keys\t\t\t= { googleTranslateApiKey, deepLApiKey}\n\n\t}\n\n\tget collection(){\n\t\treturn this.db.collection('translations')\n\t}\n\n\n\n\n\thash(value){\n\t\tconst hash \t= \tcrypto\n\t\t\t\t\t\t.createHash('md5')\n\t\t\t\t\t\t.update(value)\n\t\t\t\t\t\t.digest('base64')\n\n\t\treturn \thash.length < value.length\n\t\t\t\t? hash\n\t\t\t\t: value\n\t}\n\n\n\n\tasync getStoredTranslations(hash, key){\n\n\t\tconst result = \tawait \tthis.collection\n\t\t\t\t\t\t\t\t.findOneAndUpdate(\n\t\t\t\t\t\t\t\t\t{ hash },\n\t\t\t\t\t\t\t\t\t{ \n\t\t\t\t\t\t\t\t\t\t$set:\t\t{ lastRequest: Date.now() }, \n\t\t\t\t\t\t\t\t\t\t$addToSet:\t{ tags: key } \n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t{ upsert:\tfalse }\n\t\t\t\t\t\t\t\t)\n\n\t\treturn result.value || {}\n\t}\n\n\n\n\n\tasync getNewTranslation(from, to, text, hash, key){\n\n\t\tconsole.log('Getting new translation for ', hash)\n\n\t\thash = hash || this.hash(text)\n\n\t\tconst translation \t= await getTranslation(from, to, text, this.keys)\n\t\tconst lastRequest\t= Date.now()\n\n\t\tthis.collection.updateOne(\n\t\t\t{ hash }, \n\t\t\t{ \n\t\t\t\t$set:\t\t{ hash, [to]: translation, lastRequest}, \n\t\t\t\t$addToSet: \t{ tags: key } \n\t\t\t}, \n\t\t\t{ upsert:true }\n\t\t)\n\n\t\treturn translation\n\t}\n\n\tasync translate(from_language, to_languages, text){\n\n\t\tto_languages = \tArray.isArray(to_languages)\n\t\t\t\t\t\t?\tto_languages\n\t\t\t\t\t\t:\t[to_languages]\n\n\t\tconst hash\t\t\t\t\t= await this.hash(text)\n\t\tconst stored_translations\t= await this.getStoredTranslations(hash)\n\t\tconst result\t\t\t\t= {}\n\n\n\t\treturn await\tPromise.all(to_languages.map( to_language => {\n\t\t\t\t\t\t\treturn \tPromise.resolve(\n\t\t\t\t\t\t\t\t\t\t\tstored_translations[to_language] \n\t\t\t\t\t\t\t\t\t\t|| \tthis.getNewTranslation(from_language, to_language, text, hash, key)\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t.then( translation => result[to_language] = translation)\n\t\t\t\t\t\t}))\n\t\t\t\t\t\t.then( () => result )\n\n\n\t}\n\n\tasync translateItem(item, from_language, to_languages, key){\n\n\t\tto_languages = \tArray.isArray(to_languages)\n\t\t\t\t\t\t?\tto_languages\n\t\t\t\t\t\t:\t[to_languages]\n\n\n\t\tconst translatables = \ticProperties\n\t\t\t\t\t\t\t\t.filter( \tproperty => property.translatable)\n\t\t\t\t\t\t\t\t.map( \t\tproperty => property.name)\n\n\t\t\t\t\n\n\n\t\tawait Promise.all(translatables.map( async (translatable) => {\n\n\t\t\tconst map \t\t\t= \titem\t&& item[translatable]\n\t\t\tconst value \t\t= \tmap\t\t&& map[from_language]\n\t\t\tconst trimmed_value\t=\tvalue\t&& value.trim()\n\n\n\t\t\tif(!trimmed_value) return null\n\n\t\t\tconst translations\t= \tawait \tthis.translate(\n\t\t\t\t\t\t\t\t\t\t\t\tfrom_language, \n\t\t\t\t\t\t\t\t\t\t\t\tto_languages.filter( lang => !item[translatable][lang] ), \n\t\t\t\t\t\t\t\t\t\t\t\ttrimmed_value,\n\t\t\t\t\t\t\t\t\t\t\t\tkey\n\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t.catch( reason => ({'translator': 'translation failed'}))\n\n\t\t\tObject.keys(translations).forEach( lang => {\n\n\t\t\t\tconst t = translations[lang]\n\n\t\t\t\tif(!t) return null\n\n\t\t\t\titem[translatable][lang] = `[${t.translator}:] ${t.text}`\n\n\t\t\t})\n\n\t\t}))\n\n\t\treturn item\n\n\t}\n\n}", "dangerousExampleEn": "1. var md5 = require('md5');\n2. \n3. console.log(md5('password'));\nLine 3: This is weak for the brute-force attack because it uses md5, a weak hash function.", "safeExampleEn": "1. var bcrypt = require('bcrypt');\n2. \n3. bcrypt.hash(\"password\", 13, function(err, hash) {\n4. console.log(hash);\n5. });\nLine 3: This is safe from the brute-force attack because bcrypt is used to create hash data.", "contexts": [{"lineNo": 29, "eventType": "sink", "messageKey": "jschk.FORBIDDEN.WEAK_ALGORITHM.JS.defect", "params": {"arg0": "md5"}}]}} {"id": "ce29aa6c605515247d7baaec2168ca12d63a2bf0240471a872b835b7d9076786", "license": {"spdx": ["MIT"], "repo": "aperez25/escapehatch", "path": "server/db/models/user.js", "repo_head_hexsha": "a9df8cf9bcf37b1aefcc41852a40b8d9db48aacb", "stack_hexsha": "bf3f1f740ac4c6abe662acfa842574b6bfa3eee0", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of weak cryptographic algorithm", "issueDescriptionEn": "A hash function is a one-way function that receives data of different lengths and maps it to random data of a fixed length. It is commonly used to store user passwords because it always produces the same output for a given input.\nBecause hash can be calculated very quickly, the hash functions, such as MD5 and SHA, may give the illusion of high performance. However they are vulnerable to random brute-force attacks. If you use the hash functions on simple data, they can be saved in the rainbow table, making it insecure. In addition, RC2, RC3, RC4, RC5, RC6, MD4, and DES are also known to be vulnerable.\nThere are many functions used to overcome the disadvantages of MD5 and SHA.\nIn Node.js, bcrypt is one of the functions that is commonly used with outstanding performance and easily replace them. The latest hash algorithms, such as Argon2, PBKDF2, and Scrypt, are also good alternatives. Make sure to add a salt to the hash in SHA-2 i.e. SHA-224, SHA-256, SHA-384, SHA-512.", "issueLineNumber": 50, "entireCode": "const crypto = require('crypto');\nconst Sequelize = require('sequelize');\nconst db = require('../db');\n\nconst setSaltAndPassword = user => {\n if (user.changed('password')) {\n user.salt = user.Model.generateSalt();\n user.password = user.Model.encryptPassword(user.password, user.salt);\n }\n};\n\nmodule.exports = db.define('user', {\n firstName: {\n type: Sequelize.STRING\n },\n lastName: {\n type: Sequelize.STRING\n },\n email: {\n type: Sequelize.STRING,\n unique: true,\n allowNull: true\n },\n password: {\n type: Sequelize.STRING\n },\n salt: {\n type: Sequelize.STRING\n },\n googleId: {\n type: Sequelize.STRING\n },\n githubId: {\n type: Sequelize.STRING\n },\n stackId: {\n type: Sequelize.STRING\n }\n}, {\n instanceMethods: {\n correctPassword (candidatePwd) {\n return this.Model.encryptPassword(candidatePwd, this.salt) === this.password;\n }\n },\n classMethods: {\n generateSalt () {\n return crypto.randomBytes(16).toString('base64');\n },\n encryptPassword (plainText, salt) {\n return crypto.createHash('sha1').update(plainText).update(salt).digest('hex');\n }\n },\n hooks: {\n beforeCreate: setSaltAndPassword,\n beforeUpdate: setSaltAndPassword\n }\n});\n", "dangerousExampleEn": "1. var md5 = require('md5');\n2. \n3. console.log(md5('password'));\nLine 3: This is weak for the brute-force attack because it uses md5, a weak hash function.", "safeExampleEn": "1. var bcrypt = require('bcrypt');\n2. \n3. bcrypt.hash(\"password\", 13, function(err, hash) {\n4. console.log(hash);\n5. });\nLine 3: This is safe from the brute-force attack because bcrypt is used to create hash data.", "contexts": [{"lineNo": 50, "eventType": "sink", "messageKey": "jschk.FORBIDDEN.WEAK_ALGORITHM.JS.defect", "params": {"arg0": "sha1"}}]}} {"id": "55d350975243449398b235d71ae56d95a9725d0b1f83982dfc908ff76d875bf6", "license": {"spdx": ["MIT"], "repo": "xiaojian007/furniture", "path": "furnitures-admin/src/store/actions.js", "repo_head_hexsha": "c38d6cc1e27add4cc16ea6ad61082fb7340c0c46", "stack_hexsha": "1b0edc87095e76802c277f6906366a8a5f4ac5c1", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of weak cryptographic algorithm", "issueDescriptionEn": "A hash function is a one-way function that receives data of different lengths and maps it to random data of a fixed length. It is commonly used to store user passwords because it always produces the same output for a given input.\nBecause hash can be calculated very quickly, the hash functions, such as MD5 and SHA, may give the illusion of high performance. However they are vulnerable to random brute-force attacks. If you use the hash functions on simple data, they can be saved in the rainbow table, making it insecure. In addition, RC2, RC3, RC4, RC5, RC6, MD4, and DES are also known to be vulnerable.\nThere are many functions used to overcome the disadvantages of MD5 and SHA.\nIn Node.js, bcrypt is one of the functions that is commonly used with outstanding performance and easily replace them. The latest hash algorithms, such as Argon2, PBKDF2, and Scrypt, are also good alternatives. Make sure to add a salt to the hash in SHA-2 i.e. SHA-224, SHA-256, SHA-384, SHA-512.", "issueLineNumber": 16, "entireCode": "/**\n * 全局actions\n * @author lijian\n * @since 2020-02-21\n * @version 1.0.0\n * @description 全局actions\n * @copyright lijian\n */\n\nimport Cookies from \"js-cookie\";\nimport { SET_TOKEN, SET_MENU_PERMISSIONS, SET_BTN_PERMISSIONS } from \"@store-m/auth/mutation-types\";\nimport { SET_USERINFO } from \"@store-m/user/mutation-types\";\nimport { SET_SUB_MENU } from \"@store-m/menu/mutation-types\";\nimport { SET_LATEST_VERSION } from \"@store-m/app/mutation-types\";\nimport { deBase64, enBase64, md5 } from \"@utils/crypto\";\nconst COOKIE_ID = md5(\"lijian\"); // 云印token\nconst USERINFO = \"pdp.lijian\"; // 用户信息+token\n/**\n * 设置最新版本\n * @param {Object} param0\n * @param {String} v 版本号\n */\nexport const setLatestVersion = ({ commit }, v = \"\") => {\n\tcommit(`app/${SET_LATEST_VERSION}`, v);\n\tlocalStorage.setItem(\"LATEST_VERSION\", v);\n};\n\n/**\n * 设置用户信息缓存\n * @param {Object} info 用户信息\n */\nconst setLocalStorage = function(info = null) {\n\tif (info && info.token) {\n\t\tlocalStorage.setItem(USERINFO, enBase64(JSON.stringify(info)));\n\t} else {\n\t\tlocalStorage.removeItem(USERINFO);\n\t}\n};\n\n/**\n * 获取登录信息\n * @param {Object} context\n */\nexport const getInfo = ({ commit }) => {\n\tlet cookieData = Cookies.get(COOKIE_ID);\n\tlet localData = localStorage.getItem(USERINFO); // 登录信息\n\tif (cookieData && localData) {\n\t\tcookieData = deBase64(cookieData);\n\t\tlocalData = JSON.parse(deBase64(localData));\n\t\tif (cookieData === localData.token) {\n\t\t\tcommit(`user/${SET_USERINFO}`, localData);\n\t\t\tcommit(`auth/${SET_TOKEN}`, localData.token);\n\t\t\tcommit(`auth/${SET_MENU_PERMISSIONS}`, localData.user.menuPermissionIds);\n\t\t\tcommit(`auth/${SET_BTN_PERMISSIONS}`, localData.user.btnPermissionIds);\n\t\t\tsetLocalStorage(localData);\n\t\t} else {\n\t\t\tconsole.log(\"cookie不一样\");\n\t\t}\n\t}\n};\n\n/**\n * 设置登录信息\n * @param {Object} context\n * @param {Object} info 登录信息\n * @returns {Promise} 返回promise\n */\nexport const setInfo = ({ commit }, info = {}) => {\n\treturn new Promise((resolve, reject) => {\n\t\ttry {\n\t\t\tif (info && info.token) {\n\t\t\t\t// 缓存时间 1天失效\n\t\t\t\tlet millisecond = new Date().getTime();\n\t\t\t\tlet expiresTime = new Date(millisecond + 60 * 1000 * 60 * 24);\n\t\t\t\tCookies.set(COOKIE_ID, enBase64(info.token), {\n\t\t\t\t\tpath: \"/\",\n\t\t\t\t\texpires: expiresTime\n\t\t\t\t});\n\t\t\t\tcommit(`user/${SET_USERINFO}`, info);\n\t\t\t\tcommit(`auth/${SET_TOKEN}`, info.token);\n\t\t\t\tsetLocalStorage(info);\n\t\t\t} else {\n\t\t\t\t// 退出登录\n\t\t\t\tsetLocalStorage();\n\t\t\t}\n\t\t\tresolve();\n\t\t} catch (error) {\n\t\t\treject(error);\n\t\t}\n\t});\n};\n\n/**\n * 设置子菜单\n * @param {Object} context\n * @param {Object} path 路径\n */\nexport const setSubMenu = ({ commit }, path) => {\n\tcommit(`menu/${SET_SUB_MENU}`, path);\n};", "dangerousExampleEn": "1. var md5 = require('md5');\n2. \n3. console.log(md5('password'));\nLine 3: This is weak for the brute-force attack because it uses md5, a weak hash function.", "safeExampleEn": "1. var bcrypt = require('bcrypt');\n2. \n3. bcrypt.hash(\"password\", 13, function(err, hash) {\n4. console.log(hash);\n5. });\nLine 3: This is safe from the brute-force attack because bcrypt is used to create hash data.", "contexts": [{"lineNo": 16, "eventType": "sink", "messageKey": "jschk.FORBIDDEN.WEAK_ALGORITHM.JS.defect", "params": {"arg0": "md5"}}]}} {"id": "de38ed40acbab9ee04bd108ac8588259f73c95d8eeb3e9d676117559497cd708", "license": {"spdx": ["Apache-2.0"], "repo": "ufna/store-ue4-sdk", "path": "Extras/WebhookDemo/routes/webhook.js", "repo_head_hexsha": "d32e9923921c8f0da9e79cf0cc75f8b448350ee3", "stack_hexsha": "893992803ff4daaf9795c8cfbc2fbf04fbf4dd52", "match": "repo_path"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of weak cryptographic algorithm", "issueDescriptionEn": "A hash function is a one-way function that receives data of different lengths and maps it to random data of a fixed length. It is commonly used to store user passwords because it always produces the same output for a given input.\nBecause hash can be calculated very quickly, the hash functions, such as MD5 and SHA, may give the illusion of high performance. However they are vulnerable to random brute-force attacks. If you use the hash functions on simple data, they can be saved in the rainbow table, making it insecure. In addition, RC2, RC3, RC4, RC5, RC6, MD4, and DES are also known to be vulnerable.\nThere are many functions used to overcome the disadvantages of MD5 and SHA.\nIn Node.js, bcrypt is one of the functions that is commonly used with outstanding performance and easily replace them. The latest hash algorithms, such as Argon2, PBKDF2, and Scrypt, are also good alternatives. Make sure to add a salt to the hash in SHA-2 i.e. SHA-224, SHA-256, SHA-384, SHA-512.", "issueLineNumber": 30, "entireCode": "// Copyright 2019 Xsolla Inc. All Rights Reserved.\n// @author <>\n\nlet express = require('express');\nlet router = express.Router();\nlet sha1 = require('sha1');\n\nlet jwt = require('jsonwebtoken');\n\nconst errorCodes = {\n INVALID_USER: 'INVALID_USER',\n INVALID_PARAMETER: 'INVALID_PARAMETER',\n INVALID_SIGNATURE: 'INVALID_SIGNATURE',\n INCORRECT_AMOUNT: 'INCORRECT_AMOUNT',\n INCORRECT_INVOICE: 'INCORRECT_INVOICE'\n}\n\nrouter.post('/', function(req, res, next) {\n // Force connection will be closed\n res.set({\n 'Connection': 'close'\n });\n\n try {\n let notification_type = req.body.notification_type;\n if(!notification_type) throw \"No notification_type data provided\";\n console.log(\"Processing: \" + notification_type + \", payload: \" + JSON.stringify(req.body));\n\n // Check request signature\n let serverSignature = \"Signature \" + sha1(JSON.stringify(req.body) + global.gConfig.store.secretKey);\n if(serverSignature != req.headers.authorization)\n {\n requestError(res, \"Invalid signature.\", errorCodes.INVALID_SIGNATURE);\n return;\n }\n\n // Route request to desired notification handler\n switch (notification_type) {\n case \"user_validation\":\n if(global.gConfig.store.validateUser) {\n global.db.users.findOne({ id: req.body.user.id }, function (err, doc) {\n if(err)\n requestError(res, err);\n else if(!doc)\n requestError(res, \"No user \" + req.body.user.id + \" found in test db\", errorCodes.INVALID_USER);\n else {\n console.log(doc);\n endRequest(res);\n }\n });\n }\n else {\n console.log(\"Don't validate user and trust him: \" + req.body.user.id);\n endRequest(res);\n }\n break;\n\n case \"payment\":\n global.db.purchases.insert({transaction: req.body.transaction.id, user: req.body.user.id, seen: false}, function (err, newDoc) {\n if(err)\n requestError(res, err);\n else {\n console.log(newDoc);\n endRequest(res);\n }\n });\n break;\n\n case \"refund\":\n // Just say \"all is okay\" for demo purposes\n endRequest(res);\n break;\n\n default:\n throw \"Unsupported notification_type\";\n }\n\n } catch(err) {\n requestError(res, err);\n }\n});\n\n// Provide status code and finish request processing\nendRequest = function (res) {\n res.statusCode = 204;\n res.contentType(\"text/plain\");\n res.end();\n}\n\nrequestError = function (res, err, errorCode = errorCodes.INVALID_PARAMETER) {\n console.log(err);\n\n res.statusCode = 400;\n res.contentType(\"application/json\");\n res.write('{\"error\":{\"code\":\"' + errorCode + '\",\"description\":\"');\n res.write(err.toString());\n res.write('\"}}');\n res.end();\n}\n\nmodule.exports = router;", "dangerousExampleEn": "1. var md5 = require('md5');\n2. \n3. console.log(md5('password'));\nLine 3: This is weak for the brute-force attack because it uses md5, a weak hash function.", "safeExampleEn": "1. var bcrypt = require('bcrypt');\n2. \n3. bcrypt.hash(\"password\", 13, function(err, hash) {\n4. console.log(hash);\n5. });\nLine 3: This is safe from the brute-force attack because bcrypt is used to create hash data.", "contexts": [{"lineNo": 30, "eventType": "sink", "messageKey": "jschk.FORBIDDEN.WEAK_ALGORITHM.JS.defect", "params": {"arg0": "sha1"}}]}} {"id": "c00c317999523a61ed3b38db259c119f62e5b0bf1d9d7e7803c5c0a5964f49ad", "license": {"spdx": ["BSD-3-Clause"], "repo": "glayzzle/php-runtime", "path": "src/cache.js", "repo_head_hexsha": "9d951c5d45210c9916e89c18a257290a8831a650", "stack_hexsha": "14630dde0b89b7c18d55c1b4acb332dfdbaa5c0a", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of weak cryptographic algorithm", "issueDescriptionEn": "A hash function is a one-way function that receives data of different lengths and maps it to random data of a fixed length. It is commonly used to store user passwords because it always produces the same output for a given input.\nBecause hash can be calculated very quickly, the hash functions, such as MD5 and SHA, may give the illusion of high performance. However they are vulnerable to random brute-force attacks. If you use the hash functions on simple data, they can be saved in the rainbow table, making it insecure. In addition, RC2, RC3, RC4, RC5, RC6, MD4, and DES are also known to be vulnerable.\nThere are many functions used to overcome the disadvantages of MD5 and SHA.\nIn Node.js, bcrypt is one of the functions that is commonly used with outstanding performance and easily replace them. The latest hash algorithms, such as Argon2, PBKDF2, and Scrypt, are also good alternatives. Make sure to add a salt to the hash in SHA-2 i.e. SHA-224, SHA-256, SHA-384, SHA-512.", "issueLineNumber": 8, "entireCode": "/*!\n * Copyright (C) 2017 Glayzzle (BSD3 License)\n * @authors https://github.com/glayzzle/php-transpiler/graphs/contributors\n * @url http://glayzzle.com\n */\n'use strict';\n\nvar md5 = require('crypto').createHash('md5');\nvar version = require('../package.json').version;\n\nvar Cache = function(path) {\n this.evals = {};\n this.scripts = {};\n this.stat = {\n resolves: {},\n items: {}\n };\n this.path = path;\n};\n\n/**\n * Resolves a cache filename\n */\nCache.prototype.resolve = function(key) {\n var fPos = key.lastIndexOf('/');\n if (fPos === -1) {\n fPos = key.lastIndexOf('\\\\');\n }\n var prefix = version + '-' + md5.update(key).digest('hex');\n if (fPos > 0) {\n return prefix + '-' + key.substring(fPos + 1) + '.js';\n } else {\n return prefix + '.js';\n }\n};\n\n/**\n * Gets the evaluation callback\n */\nCache.prototype.getEval = function(code) {\n if (code in this.evals) {\n return this.evals[code];\n }\n};\n\n/**\n * Stores an evaluation callback\n */\nCache.prototype.setEval = function(code, fn) {\n this.evals[code] = fn;\n};\n\n/**\n * Resolves a script\n */\nCache.prototype.getScript = function(filename) {\n if (filename in this.scripts) {\n return this.scripts[filename];\n }\n if (this.path) {\n // retrieve the file from cache (if exists)\n }\n};\n\n/**\n * Stores a script\n */\nCache.prototype.setScript = function(filename, fn) {\n this.scripts[filename] = fn;\n if (this.path) {\n // stores the file to cache\n }\n};\n\n// exports the cache module\nmodule.exports = Cache;", "dangerousExampleEn": "1. var md5 = require('md5');\n2. \n3. console.log(md5('password'));\nLine 3: This is weak for the brute-force attack because it uses md5, a weak hash function.", "safeExampleEn": "1. var bcrypt = require('bcrypt');\n2. \n3. bcrypt.hash(\"password\", 13, function(err, hash) {\n4. console.log(hash);\n5. });\nLine 3: This is safe from the brute-force attack because bcrypt is used to create hash data.", "contexts": [{"lineNo": 8, "eventType": "sink", "messageKey": "jschk.FORBIDDEN.WEAK_ALGORITHM.JS.defect", "params": {"arg0": "md5"}}]}} {"id": "4ae9ca266580cb0b554e17e660f1d740a8019d07dde1a91138deba47beeb9a0c", "license": {"spdx": ["MIT"], "repo": "Zenedith/vehicle-history-api", "path": "lib/plugin/etag.js", "repo_head_hexsha": "946e40ede37124f6f4acaea19d73ab3c9d5074d9", "stack_hexsha": "f720932a8c309fc6b131064bddc82ec63dfebd98", "match": "repo_path"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of weak cryptographic algorithm", "issueDescriptionEn": "A hash function is a one-way function that receives data of different lengths and maps it to random data of a fixed length. It is commonly used to store user passwords because it always produces the same output for a given input.\nBecause hash can be calculated very quickly, the hash functions, such as MD5 and SHA, may give the illusion of high performance. However they are vulnerable to random brute-force attacks. If you use the hash functions on simple data, they can be saved in the rainbow table, making it insecure. In addition, RC2, RC3, RC4, RC5, RC6, MD4, and DES are also known to be vulnerable.\nThere are many functions used to overcome the disadvantages of MD5 and SHA.\nIn Node.js, bcrypt is one of the functions that is commonly used with outstanding performance and easily replace them. The latest hash algorithms, such as Argon2, PBKDF2, and Scrypt, are also good alternatives. Make sure to add a salt to the hash in SHA-2 i.e. SHA-224, SHA-256, SHA-384, SHA-512.", "issueLineNumber": 18, "entireCode": "'use strict';\n\n// Copyright 2015 , \n// etagify (https://github.com/lloyd/connect-etagify)\n\nvar assert = require('assert-plus');\nvar crypto = require('crypto');\n\nvar etag = function etag(options) {\n assert.optionalObject(options, 'options');\n\n // path to etag mapping\n var etags = {};\n\n // given a request, and a set of vary headers, generate a hash representing\n // the headers.\n function hashVaryHeaders(vary, req) {\n var hash = crypto.createHash('md5');\n\n vary.forEach(function (header) {\n if (req.headers[header]) {\n hash.update(req.headers[header]);\n }\n });\n\n return hash.digest(); // yes sir, we are using binary keys.\n }\n\n // given a request, see if we have an etag for it\n function getETag(r) {\n var tag;\n\n if (etags.hasOwnProperty(r.url)) {\n if (etags[r.url].vary) {\n var hash = hashVaryHeaders(etags[r.url].vary, r);\n tag = etags[r.url].md5s[hash];\n } else {\n tag = etags[r.url].md5;\n }\n }\n\n return tag;\n }\n\n function etagResponse(req, res, next) {\n\n // if there's an ETag already on the response, do nothing\n if (res.header('ETag')) {\n next();\n return;\n }\n\n var tag = getETag(req);\n if (tag) {\n res.setHeader('ETag', tag);\n next();\n return;\n }\n\n var origWrite = res.write;\n var origEnd = res.end;\n\n // otherwise, eavsedrop on the outbound response and generate a\n // content-based hash.\n var hash = crypto.createHash('md5');\n\n res.write = function (chunk) {\n hash.update(chunk);\n origWrite.call(res, chunk);\n };\n\n res.end = function (body) {\n if (body) {\n hash.update(body);\n }\n\n var vary = res.getHeader('vary');\n\n if (vary) {\n\n if (!etags[req.url]) {\n\n etags[req.url] = {\n vary: vary.split(',').map(function (x) {\n return x.trim().toLowerCase();\n }),\n md5s: {}\n };\n }\n\n var hdrhash = hashVaryHeaders(etags[req.url].vary, req);\n etags[req.url].md5s[hdrhash] = hash.digest('hex');\n } else {\n etags[req.url] = {md5: hash.digest('hex')};\n }\n origEnd.apply(res, arguments);\n };\n\n next();\n }\n\n return etagResponse;\n};\n\nmodule.exports.etag = etag;", "dangerousExampleEn": "1. var md5 = require('md5');\n2. \n3. console.log(md5('password'));\nLine 3: This is weak for the brute-force attack because it uses md5, a weak hash function.", "safeExampleEn": "1. var bcrypt = require('bcrypt');\n2. \n3. bcrypt.hash(\"password\", 13, function(err, hash) {\n4. console.log(hash);\n5. });\nLine 3: This is safe from the brute-force attack because bcrypt is used to create hash data.", "contexts": [{"lineNo": 18, "eventType": "sink", "messageKey": "jschk.FORBIDDEN.WEAK_ALGORITHM.JS.defect", "params": {"arg0": "md5"}}]}} {"id": "cc6f20cd5fee8a34fac0dc8ec5a03924ae70be8c0aac39a2eb0576cc03d4b8ec", "license": {"spdx": ["MIT"], "repo": "tmptrash/JSQuest", "path": "lib/js/Helper.js", "repo_head_hexsha": "49e78aebf8e872c54853f70b068f1d83ce64d4b3", "stack_hexsha": "af9d2436cb5c7f2fea8ffc2155740bb8a3e8ec00", "match": "repo_path"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of weak cryptographic algorithm", "issueDescriptionEn": "A hash function is a one-way function that receives data of different lengths and maps it to random data of a fixed length. It is commonly used to store user passwords because it always produces the same output for a given input.\nBecause hash can be calculated very quickly, the hash functions, such as MD5 and SHA, may give the illusion of high performance. However they are vulnerable to random brute-force attacks. If you use the hash functions on simple data, they can be saved in the rainbow table, making it insecure. In addition, RC2, RC3, RC4, RC5, RC6, MD4, and DES are also known to be vulnerable.\nThere are many functions used to overcome the disadvantages of MD5 and SHA.\nIn Node.js, bcrypt is one of the functions that is commonly used with outstanding performance and easily replace them. The latest hash algorithms, such as Argon2, PBKDF2, and Scrypt, are also good alternatives. Make sure to add a salt to the hash in SHA-2 i.e. SHA-224, SHA-256, SHA-384, SHA-512.", "issueLineNumber": 43, "entireCode": "/**\n * Global helper class. Singleton. Contains common usable functions for any class.\n * @author DeadbraiN\n * @email \n * TODO: create different helpers. e.g.: Helper.String\n * TODO: move helpers to separate namespace - Helper\n */\n\nif (typeof exports !== 'undefined') {\n if (Lib === undefined) {\n var Lib = {};\n var window = {};\n }\n Lib.external = {Helper: require('./external/Helper.js').Helper};\n}\n\n/**\n * @singleton\n * {Object} Global helper object\n */\nLib.Helper = {\n /**\n * Just empty function. Can be used for interface methods, stubs and so on.\n */\n emptyFn: function () {},\n\n /**\n * Clones object|Array|Function\n * @param {Object|Array|Function}\n * @return {Object|Array|Function}\n */\n clone: function (o) {\n return JSON.parse(JSON.stringify(o));\n },\n\n /**\n * Returns unique string id\n * @return {String}\n */\n getId: function () {\n Lib.Helper.uniqueId = Lib.Helper.uniqueId || 0;\n Lib.Helper.uniqueId++;\n return Lib.Helper.md5(Lib.Helper.uniqueId.toString());\n },\n\n /**\n * MD5 hash generator. Written by \n * @param {String} string Input string\n * @return {String} Hash\n */\n md5: Lib.external.Helper.md5,\n\n /**\n * Javascript string pad. http://www.webtoolkit.info/\n * @param {String} str String we should to pad\n * @param {Number|undefined} len Amount of pad symbols\n * @param {String|undefined} pad Pasd symbol\n * @param {String||undefined} dir 'right' | 'left'\n * @return {String}\n **/\n pad: Lib.external.Helper.pad,\n\n /**\n * Strip whitespace from the beginning and end of a string\n * @param {String} str\n * @return {String}\n */\n trim: function (str) {\n return str.replace(/^\\s+|\\s+$/g, \"\");\n },\n\n /**\n * Capitalize string. hello -> Hello\n * @param {String} s\n * @return {String} Capitalized string\n */\n capitalize: function (s) {\n return Lib.Helper.isString(s) && s.length > 0 ? s[0].toUpperCase() + s.substr(1) : s;\n },\n\n /**\n * Analog of printf method. First argument - source string, other - format arguments.\n * e.g.: format('My name is {0}', 'Vasya') -> 'My name is Vasya'\n * @param {String} s Source function\n * @return {String} Formatted string\n */\n format: function (s) {\n var args = Array.prototype.slice.call(arguments);\n var str = s;\n var arg;\n var len;\n\n args.shift();\n for (arg = 0, len = args.length; arg < len; arg++) {\n str = str.replace('{' + arg + '}', args[arg]);\n }\n\n return str;\n },\n\n /**\n * Creates name of the handler, which will handle specified command in console.\n * @param {String} cmd Name of the command\n * @return {String} Handler name\n */\n createCmdHandlerName: function (cmd) {\n return '_on' + Lib.Helper.capitalize(cmd) + 'Cmd';\n },\n\n /**\n * Returns true if the passed value is a JavaScript Array, false otherwise.\n *\n * @param {Object} target The target to test\n * @return {Boolean}\n * @method\n */\n isArray: Array.isArray || function (value) {\n return Object.prototype.toString.call(value) === '[object Array]';\n },\n\n /**\n * Returns true if specified expression is regular expression\n * @param {Mixed} val\n * @return {Boolean}\n */\n isRegexp: function (val) {\n return val instanceof RegExp;\n },\n\n /**\n * Returns true if the passed value is a JavaScript Object, false otherwise.\n * @param {Object} value The value to test\n * @return {Boolean}\n * @method\n */\n isObject: (Object.prototype.toString.call(null) === '[object Object]') ? function (value) {\n // check ownerDocument here as well to exclude DOM nodes\n return value !== null && value !== undefined && Object.prototype.toString.call(value) === '[object Object]' && value.ownerDocument === undefined;\n } : function (value) {\n return Object.prototype.toString.call(value) === '[object Object]';\n },\n\n /**\n * Returns true if the passed value is a JavaScript Function, false otherwise. Safari 3.x and 4.x returns\n * 'function' for typeof , hence we need to fall back to using Object.prototype.toString (slower)\n * @param {Object} value The value to test\n * @return {Boolean}\n * @method\n */\n isFunction: (window.document !== undefined && typeof document.getElementsByTagName('body') === 'function') ? function (value) {\n return Object.prototype.toString.call(value) === '[object Function]';\n } : function (value) {\n return typeof value === 'function';\n },\n\n /**\n * Returns true if the passed value is a number. Returns false for non-finite numbers.\n * @param {Object} value The value to test\n * @return {Boolean}\n */\n isNumber: function (value) {\n return typeof value === 'number' && isFinite(value);\n },\n\n /**\n * Validates that a value is numeric.\n * @param {Object} value Examples: 1, '1', '2.34', '0x23'\n * @return {Boolean} True if numeric, false otherwise\n */\n isNumeric: function (value) {\n return !isNaN(parseFloat(value)) && !isNaN(Number(value)) && isFinite(value);\n },\n\n /**\n * Returns true if the passed value is a string.\n * @param {Object} value The value to test\n * @return {Boolean}\n */\n isString: function (value) {\n return typeof value === 'string';\n },\n\n /**\n * Returns true if the passed value is a boolean.\n *\n * @param {Object} value The value to test\n * @return {Boolean}\n */\n isBoolean: function (value) {\n return typeof value === 'boolean';\n },\n\n /**\n * Returns true if the passed value is an HTMLElement\n * @param {Object} value The value to test\n * @return {Boolean}\n */\n isElement: function (value) {\n return value ? value.nodeType === 1 : false;\n },\n\n /**\n * Makes JSONP cross domain request and calls callback function with one\n * parameter - received data.\n * @param {String} url URL\n * @param {Function} cb Callback.\n * @param {Object} scope Scope for callback\n */\n jsonp: function (url, cb, scope) {\n JSONP.init({callbackName: 'jsqcallback'});\n JSONP.get(url, undefined, function (data) {cb.call(scope, data); });\n }\n};\n\n/**\n * @prop\n * {Mixed} Reference to the global object (namespace)\n */\nvar global = this;\n/**\n * Exports Helper class. It works only for Node.js levels\n * @type {Object}\n */\nif (typeof exports !== 'undefined') {\n exports.Helper = Lib.Helper;\n}", "dangerousExampleEn": "1. var md5 = require('md5');\n2. \n3. console.log(md5('password'));\nLine 3: This is weak for the brute-force attack because it uses md5, a weak hash function.", "safeExampleEn": "1. var bcrypt = require('bcrypt');\n2. \n3. bcrypt.hash(\"password\", 13, function(err, hash) {\n4. console.log(hash);\n5. });\nLine 3: This is safe from the brute-force attack because bcrypt is used to create hash data.", "contexts": [{"lineNo": 43, "eventType": "sink", "messageKey": "jschk.FORBIDDEN.WEAK_ALGORITHM.JS.defect", "params": {"arg0": "md5"}}]}} {"id": "a626c01b69d1dcf1e9b78ff7597dc7a7ac1184bf3839b66451033157b07de43a", "license": {"spdx": ["MIT"], "repo": "swarajban/tiny-dancer", "path": "updateShows.js", "repo_head_hexsha": "a387c442d0ab2902f49a7397902d5ebccc2f41b5", "stack_hexsha": "7226abd737c93dfdbf512075328fd48d50e12950", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of weak cryptographic algorithm", "issueDescriptionEn": "A hash function is a one-way function that receives data of different lengths and maps it to random data of a fixed length. It is commonly used to store user passwords because it always produces the same output for a given input.\nBecause hash can be calculated very quickly, the hash functions, such as MD5 and SHA, may give the illusion of high performance. However they are vulnerable to random brute-force attacks. If you use the hash functions on simple data, they can be saved in the rainbow table, making it insecure. In addition, RC2, RC3, RC4, RC5, RC6, MD4, and DES are also known to be vulnerable.\nThere are many functions used to overcome the disadvantages of MD5 and SHA.\nIn Node.js, bcrypt is one of the functions that is commonly used with outstanding performance and easily replace them. The latest hash algorithms, such as Argon2, PBKDF2, and Scrypt, are also good alternatives. Make sure to add a salt to the hash in SHA-2 i.e. SHA-224, SHA-256, SHA-384, SHA-512.", "issueLineNumber": 49, "entireCode": "const jsdom = require('jsdom')\nconst Promise = require('bluebird')\nconst moment = require('moment')\nconst md5 = require('md5')\n\nconst { pg, SHOWS } = require('./knex')\nconst { PG_DATE_FMT } = require('./lib')\n\nconst EDM_DATE_FMT = 'MM.DD.YYYY'\nconst EDM_URL = 'http://westcoastedm.com/sanfrancisco/'\n\nfunction updateShows () {\n return fetchShows()\n .then(saveShows)\n}\n\nfunction fetchShows () {\n console.log(`Fetching shows from ${EDM_URL}`)\n return new Promise((resolve, reject) => {\n jsdom.env(\n EDM_URL,\n ['https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js'],\n (err, window) => {\n if (err) {\n console.log(`Error loading page: ${err}`)\n return reject(err)\n }\n console.log(`Successfully loaded page`)\n const shows = parseShows(window)\n resolve(shows)\n }\n )\n })\n}\n\nfunction parseShows (window) {\n const shows = []\n const $ = window.$\n $('div.sqs-block-content p strong').remove()\n const content = $('div.sqs-block-content p').html()\n const rawShowStrings = content.split('
    ')\n rawShowStrings.forEach(\n (showString) => {\n if (showString === '') {\n return\n }\n const [dateString, _, artists, venue] = showString.split('•').map((string) => string.trim())\n const show_date = moment(dateString, EDM_DATE_FMT).format(PG_DATE_FMT)\n const show_hash = md5(`${artists}${venue}${show_date}`)\n shows.push({\n artists,\n venue,\n show_date,\n show_hash\n })\n }\n )\n console.log(`Found ${shows.length} shows`)\n return shows\n}\n\nfunction saveShows (shows) {\n const show_hashes = shows.map((show) => show.show_hash)\n console.log('Fetching existing show hashes...')\n return pg(SHOWS)\n .whereIn('show_hash', show_hashes)\n .pluck('show_hash')\n .then(\n (existingHashList) => {\n console.log(`Found ${existingHashList.length}`)\n const existingHashSet = new Set(existingHashList)\n const newShows = shows\n .filter(\n (show) => {\n return ! existingHashSet.has(show.show_hash)\n }\n )\n .map(\n (show) => {\n delete show.show_hash\n show.legitness = 2\n return show\n }\n )\n\n const numNewShows = newShows.length\n if (numNewShows > 0) {\n console.log(`Saving ${newShows.length} shows`)\n return pg(SHOWS).insert(newShows)\n } else {\n console.log(`No new shows found!`)\n return { rowCount: 0}\n }\n\n }\n )\n .then(\n ({ rowCount }) => {\n console.log(`Successfully saved ${rowCount} shows!`)\n }\n )\n .catch(\n (err) => {\n console.log(`Error saving shows`, err)\n throw err\n }\n )\n}\n\nmodule.exports = {\n updateShows\n}", "dangerousExampleEn": "1. var md5 = require('md5');\n2. \n3. console.log(md5('password'));\nLine 3: This is weak for the brute-force attack because it uses md5, a weak hash function.", "safeExampleEn": "1. var bcrypt = require('bcrypt');\n2. \n3. bcrypt.hash(\"password\", 13, function(err, hash) {\n4. console.log(hash);\n5. });\nLine 3: This is safe from the brute-force attack because bcrypt is used to create hash data.", "contexts": [{"lineNo": 49, "eventType": "sink", "messageKey": "jschk.FORBIDDEN.WEAK_ALGORITHM.JS.defect", "params": {"arg0": "md5"}}]}} {"id": "e91d73fece57c379cffc4b06fed9f4cd12a87a29450ef2471e16b9ff48e48cdd", "license": {"spdx": ["MIT"], "repo": "vietduc01100001/video-converter-web", "path": "server/src/router.js", "repo_head_hexsha": "db43ebc5cc2a54945d931d463f96990f5d87abb3", "stack_hexsha": "fb8a00ae803df9b0017a62dd6a67403a63b62eec", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of weak cryptographic algorithm", "issueDescriptionEn": "A hash function is a one-way function that receives data of different lengths and maps it to random data of a fixed length. It is commonly used to store user passwords because it always produces the same output for a given input.\nBecause hash can be calculated very quickly, the hash functions, such as MD5 and SHA, may give the illusion of high performance. However they are vulnerable to random brute-force attacks. If you use the hash functions on simple data, they can be saved in the rainbow table, making it insecure. In addition, RC2, RC3, RC4, RC5, RC6, MD4, and DES are also known to be vulnerable.\nThere are many functions used to overcome the disadvantages of MD5 and SHA.\nIn Node.js, bcrypt is one of the functions that is commonly used with outstanding performance and easily replace them. The latest hash algorithms, such as Argon2, PBKDF2, and Scrypt, are also good alternatives. Make sure to add a salt to the hash in SHA-2 i.e. SHA-224, SHA-256, SHA-384, SHA-512.", "issueLineNumber": 31, "entireCode": "const md5 = require('md5');\nconst fs = require('fs-extra');\nconst handbrake = require('handbrake-js');\nconst initializer = require('./initializer');\nconst cleanup = require('./cleanup');\n\nconst storage = {\n handbrakeInstances: new Map(),\n convertedFiles: new Map()\n};\n\nconst emitter = initializer.getEmitter();\n\nmodule.exports = (app, uploader, ENV) => {\n // Handle convert video requests\n app.post('/videos/upload', uploader.single('file'), (req, res) => {\n if (!req.file) {\n res.status(400).json({ msg: 'File upload failed' });\n console.error('File upload failed: no file from uploader');\n return;\n }\n\n res.status(201).json({ msg: 'Request is being handled' });\n console.log('Request is being handled');\n\n try {\n // Prepare the input\n const [height, rate] = req.body.format.split(',');\n const item = { name: req.file.originalname, path: req.file.path, height, rate };\n const convertedFilename = item.name + '_converted.mp4';\n const hash = md5(convertedFilename);\n\n // Create a converter instance\n const instance = handbrake\n .spawn({\n input: item.path,\n output: `${ENV.CONVERTS_DIR}/${convertedFilename}`,\n encoder: 'x264', // HLS/H.264\n height: parseInt(item.height),\n width: item.height === '720' ? 1280 : 585,\n rate: parseInt(item.rate)\n })\n .on('error', err => {\n emitter.emit('error', { msg: 'Cannot spawn converter instance' });\n console.error(`Cannot spawn converter instance for file ${item.name}`);\n console.error(err);\n })\n .on('progress', progress => {\n emitter.emit('message', {\n status: 'converting',\n hash,\n filename: item.name,\n percentComplete: progress.percentComplete,\n eta: progress.eta\n });\n })\n .on('complete', () => {\n emitter.emit('message', { status: 'completed', hash });\n storage.handbrakeInstances.delete(hash);\n storage.convertedFiles.set(hash, `${ENV.CONVERTS_DIR}/${convertedFilename}`);\n console.log(`File convert finished: ${item.name} -> ${convertedFilename}`);\n\n // Delete uploaded file instantly\n fs.unlinkSync(`${ENV.UPLOADS_DIR}/${item.name}`);\n\n // Delete converted file after FILE_LIFETIME minutes\n setTimeout(() => {\n fs.unlinkSync(`${ENV.CONVERTS_DIR}/${convertedFilename}`);\n storage.convertedFiles.delete(hash);\n console.log(`Converted file deleted: ${convertedFilename}`);\n }, ENV.FILE_LIFETIME * 60 * 1000);\n });\n\n // Save the instance to an in-memory storage\n storage.handbrakeInstances.set(hash, instance);\n console.log(`File convert starts: ${item.name} -> ${convertedFilename}`);\n } catch (err) {\n emitter.emit('error', { msg: 'Request is invalid' });\n console.error('Request is invalid');\n console.error(err);\n }\n });\n\n // Handle download converted video requests\n app.get('/videos/:hash', (req, res) => {\n const { hash } = req.params;\n const path = storage.convertedFiles.get(hash);\n if (fs.existsSync(path)) {\n res.attachment(path).sendFile(path);\n console.log(`Sent file to client: ${path.slice(path.lastIndexOf('/') + 1)}`);\n } else {\n res.status(404).json({ msg: 'File not exist' });\n console.error(`File not exist: ${path}`);\n }\n });\n\n // Handle cancel convert video requests\n app.delete('/videos/:hash', (req, res) => {\n const { hash } = req.params;\n const instance = storage.handbrakeInstances.get(hash);\n if (instance) {\n instance.cancel();\n res.json({ msg: 'Video convert cancelled' });\n emitter.emit('message', { status: 'cancelled', hash });\n storage.handbrakeInstances.delete(hash);\n console.log(`File convert cancelled: ${hash}`);\n const path = storage.convertedFiles.get(hash);\n if (path) fs.unlinkSync(path);\n } else {\n res.status(404).json({ msg: 'File convert not exist' });\n console.error(`File convert not exist: ${hash}`);\n }\n });\n\n // SSE streaming\n app.get('/streaming', (req, res) => {\n res.writeHead(200, {\n 'Content-Type': 'text/event-stream',\n 'Cache-Control': 'no-store, no-cache',\n Connection: 'keep-alive'\n });\n\n res.write(`retry: 1000 \\n\\n`);\n\n emitter.on('error', err => {\n const obj = { error: err };\n res.write(`data: ${JSON.stringify(obj)} \\n\\n`);\n });\n\n emitter.on('message', msg => {\n const obj = { data: msg };\n res.write(`data: ${JSON.stringify(obj)} \\n\\n`);\n });\n });\n\n // Clean up stale files in UPLOADS_DIR & CONVERTS_DIR periodically\n cleanup(storage, ENV);\n};", "dangerousExampleEn": "1. var md5 = require('md5');\n2. \n3. console.log(md5('password'));\nLine 3: This is weak for the brute-force attack because it uses md5, a weak hash function.", "safeExampleEn": "1. var bcrypt = require('bcrypt');\n2. \n3. bcrypt.hash(\"password\", 13, function(err, hash) {\n4. console.log(hash);\n5. });\nLine 3: This is safe from the brute-force attack because bcrypt is used to create hash data.", "contexts": [{"lineNo": 31, "eventType": "sink", "messageKey": "jschk.FORBIDDEN.WEAK_ALGORITHM.JS.defect", "params": {"arg0": "md5"}}]}} {"id": "9d9bb02e351431bc43f9e092793b1653e9904d56cc1e4f879c4a9ad59d8127e7", "license": {"spdx": ["MIT"], "repo": "Vanlee0129/node-des-cbc", "path": "index.js", "repo_head_hexsha": "1cb78770d4fee5468fc13a77673966b5d66b28e1", "stack_hexsha": "4a0edd7e3808f4efe4eae22f1094c2d603df7c73", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of weak cryptographic algorithm", "issueDescriptionEn": "A hash function is a one-way function that receives data of different lengths and maps it to random data of a fixed length. It is commonly used to store user passwords because it always produces the same output for a given input.\nBecause hash can be calculated very quickly, the hash functions, such as MD5 and SHA, may give the illusion of high performance. However they are vulnerable to random brute-force attacks. If you use the hash functions on simple data, they can be saved in the rainbow table, making it insecure. In addition, RC2, RC3, RC4, RC5, RC6, MD4, and DES are also known to be vulnerable.\nThere are many functions used to overcome the disadvantages of MD5 and SHA.\nIn Node.js, bcrypt is one of the functions that is commonly used with outstanding performance and easily replace them. The latest hash algorithms, such as Argon2, PBKDF2, and Scrypt, are also good alternatives. Make sure to add a salt to the hash in SHA-2 i.e. SHA-224, SHA-256, SHA-384, SHA-512.", "issueLineNumber": 16, "entireCode": "const crypto = require(\"crypto\");\n\n// DES 加密\n/**\n * @description DES加密,以hex为例\n * @param {String} encodeTxt 待加密的字符串\n * @param {String} key 秘钥\n * @param {String} iv 偏移量\n */\nfunction desEncode(encodeTxt, key, iv) {\n key =\n key.length >= 8 ? key.slice(0, 8) : key.concat(\"0\".repeat(8 - key.length));\n iv = iv.length >= 8 ? iv.slice(0, 8) : iv.concat(\"0\".repeat(8 - iv.length));\n const keyHex = Buffer.from(key);\n const ivHex = Buffer.from(iv);\n const encipher = crypto.createCipheriv(\"des-cbc\", keyHex, ivHex);\n let encode = encipher.update(encodeTxt, \"utf8\", \"hex\");\n encode += encipher.final(\"hex\");\n return encode;\n}\n\n// DES 解密\n/**\n * @description DES解密,要和加密方式对应起来\n * @param {String} decodeTxt 待解密的字符串\n * @param {String} key 秘钥\n * @param {String} iv 偏移量\n */\nfunction desDecode(decodeTxt, key, iv) {\n key =\n key.length >= 8 ? key.slice(0, 8) : key.concat(\"0\".repeat(8 - key.length));\n iv = iv.length >= 8 ? iv.slice(0, 8) : iv.concat(\"0\".repeat(8 - iv.length));\n const keyHex = Buffer.from(key);\n const ivHex = Buffer.from(iv);\n const decipher = crypto.createDecipheriv(\"des-cbc\", keyHex, ivHex);\n let decode = decipher.update(decodeTxt, \"hex\", \"utf8\");\n decode += decipher.final(\"utf8\");\n return decodes;\n}\n\nmodule.exports = {\n desEncode,\n desDecode,\n};", "dangerousExampleEn": "1. var md5 = require('md5');\n2. \n3. console.log(md5('password'));\nLine 3: This is weak for the brute-force attack because it uses md5, a weak hash function.", "safeExampleEn": "1. var bcrypt = require('bcrypt');\n2. \n3. bcrypt.hash(\"password\", 13, function(err, hash) {\n4. console.log(hash);\n5. });\nLine 3: This is safe from the brute-force attack because bcrypt is used to create hash data.", "contexts": [{"lineNo": 16, "eventType": "sink", "messageKey": "jschk.FORBIDDEN.WEAK_ALGORITHM.JS.defect", "params": {"arg0": "des-cbc"}}]}} {"id": "8698d34749bceb5fecc3af70f720e2261c62f0a2239f3c68b38eceb59fa95525", "license": {"spdx": ["MIT"], "repo": "thondery/kenote-express-base", "path": "src/utils/index.js", "repo_head_hexsha": "48be19b6a50de6ba23975b109b21f204a3c53a1f", "stack_hexsha": "f3e790c16b7cfb18b7718772399c3f7db5c32dff", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of weak cryptographic algorithm", "issueDescriptionEn": "A hash function is a one-way function that receives data of different lengths and maps it to random data of a fixed length. It is commonly used to store user passwords because it always produces the same output for a given input.\nBecause hash can be calculated very quickly, the hash functions, such as MD5 and SHA, may give the illusion of high performance. However they are vulnerable to random brute-force attacks. If you use the hash functions on simple data, they can be saved in the rainbow table, making it insecure. In addition, RC2, RC3, RC4, RC5, RC6, MD4, and DES are also known to be vulnerable.\nThere are many functions used to overcome the disadvantages of MD5 and SHA.\nIn Node.js, bcrypt is one of the functions that is commonly used with outstanding performance and easily replace them. The latest hash algorithms, such as Argon2, PBKDF2, and Scrypt, are also good alternatives. Make sure to add a salt to the hash in SHA-2 i.e. SHA-224, SHA-256, SHA-384, SHA-512.", "issueLineNumber": 80, "entireCode": "\nimport path from 'path'\nimport crypto from 'crypto'\nimport ini from 'ini'\nimport fs from 'fs-extra'\nimport isJson from 'is-json'\nimport _ from 'lodash'\n\nconst salt_len = 12\nconst ran_num = 8\nconst ran_str = 'abcdefghijkmnpqrstuvwxyz0123456789ABCDEFGHJKMNPQRSTUVWXYZ@$!%*#?&'\n\nexport const loadConfig = (config) => {\n let configInfo = {}\n let configFile = path.resolve(process.cwd(), config)\n try {\n let configStr = fs.readFileSync(configFile, 'utf-8')\n if (isJson(configStr)) {\n configInfo = JSON.parse(configStr)\n }\n else {\n configInfo = ini.parse(configStr)\n }\n } catch (error) {\n \n }\n return configInfo\n}\n\nexport const loadError = (Code, Message) => {\n let errors = []\n for (let e in Code) {\n errors.push({\n code: Code[e],\n message: Message[e]\n })\n }\n return errors\n}\n\nconst getAlias = dir => _.upperFirst(dir.match(/[\\w\\-]+$/)[0].replace(/[\\-\\_](\\w)/g, (x) => x.slice(1).toUpperCase() ))\n\nconst getHump = name => name.toLowerCase().replace(/[\\-\\_](\\w)/g, (x) => x.slice(1).toUpperCase() )\n\nexport const loadData = (iniFile) => {\n let dataInfo = {}\n let dataFile = path.resolve(process.cwd(), 'data', iniFile)\n try {\n let dataStr = fs.readFileSync(dataFile, 'utf-8')\n if (isJson(dataStr)) {\n dataInfo = JSON.parse(dataStr)\n }\n else {\n dataInfo = ini.parse(dataStr)\n }\n } catch (error) {\n \n }\n return dataInfo\n}\n\nexport const callback = (resolve, reject, err, doc = null) => {\n if (err) {\n reject(err)\n }\n else {\n resolve(doc)\n }\n}\n\nexport const random = (len = ran_num, char = ran_str) => {\n let str = ''\n for (let i = 0; i < len; i++) {\n let idx = _.random(0, char.length)\n str += char.slice(idx, idx + 1)\n }\n return str\n}\n\nexport const md5 = text => crypto.createHash('md5').update(text).digest('hex')\nexport const sha1 = text => crypto.createHash('sha1').update(text).digest('hex')\n\nconst getEncryptPwd = (pwd, salt) => sha1(`${md5(pwd)}^${salt}`)\n\nexport const encryptPwd = str => {\n let salt = random(salt_len)\n let encrypt = getEncryptPwd(str, salt)\n return { salt, encrypt }\n}\n\nexport const validPassword = (pwd, salt, encrypt) => encrypt === getEncryptPwd(pwd, salt)", "dangerousExampleEn": "1. var md5 = require('md5');\n2. \n3. console.log(md5('password'));\nLine 3: This is weak for the brute-force attack because it uses md5, a weak hash function.", "safeExampleEn": "1. var bcrypt = require('bcrypt');\n2. \n3. bcrypt.hash(\"password\", 13, function(err, hash) {\n4. console.log(hash);\n5. });\nLine 3: This is safe from the brute-force attack because bcrypt is used to create hash data.", "contexts": [{"lineNo": 80, "eventType": "sink", "messageKey": "jschk.FORBIDDEN.WEAK_ALGORITHM.JS.defect", "params": {"arg0": "md5"}}]}} {"id": "3a26b5295eafd3f8409ea0499fe05fe7e7452f2b7a9b64aa8db4f4638524215f", "license": {"spdx": ["MIT"], "repo": "teambition/snapper", "path": "lib/service/stats.js", "repo_head_hexsha": "95a178c4d95b714be29af452242485179aa5ba43", "stack_hexsha": "e8170b2f95cb0e735cddccfe26edcf14ab263b74", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of weak cryptographic algorithm", "issueDescriptionEn": "A hash function is a one-way function that receives data of different lengths and maps it to random data of a fixed length. It is commonly used to store user passwords because it always produces the same output for a given input.\nBecause hash can be calculated very quickly, the hash functions, such as MD5 and SHA, may give the illusion of high performance. However they are vulnerable to random brute-force attacks. If you use the hash functions on simple data, they can be saved in the rainbow table, making it insecure. In addition, RC2, RC3, RC4, RC5, RC6, MD4, and DES are also known to be vulnerable.\nThere are many functions used to overcome the disadvantages of MD5 and SHA.\nIn Node.js, bcrypt is one of the functions that is commonly used with outstanding performance and easily replace them. The latest hash algorithms, such as Argon2, PBKDF2, and Scrypt, are also good alternatives. Make sure to add a salt to the hash in SHA-2 i.e. SHA-224, SHA-256, SHA-384, SHA-512.", "issueLineNumber": 14, "entireCode": "'use strict'\n\nconst os = require('os')\nconst config = require('config')\n\nconst ilog = require('ilog')\nconst redis = require('./redis')\nconst tools = require('../tool')\n\nconst network = JSON.stringify(os.networkInterfaces())\n .match(/\"address\":\"[^\"]+\"/g)\n .map(function (ip) { return ip.slice(11, -1) })\n\nconst serverId = tools.md5(JSON.stringify(network))\n// Hash\nconst statsKey = `${redis.PREFIX}:STATS`\n// HyperLogLog\nconst roomKey = `${redis.PREFIX}:STATS:ROOM`\n// Hash\nconst serverKey = `${redis.PREFIX}:STATS:SERVERS`\n\nconst redisClient = redis.defaultClient\n\nexports.serverId = serverId\n\nexports.os = function () {\n let res = {\n net: network,\n serverId: serverId,\n mem: {\n free: (os.freemem() / 1024 / 1204).toFixed(2) + ' MB',\n total: (os.totalmem() / 1024 / 1204).toFixed(2) + ' MB'\n }\n }\n return res\n}\n\nexports.incrProducerMessages = function (count) {\n redisClient.hincrby(statsKey, 'producerMessages', count)(ilog.error)\n}\n\nexports.incrConsumerMessages = function (count) {\n redisClient.hincrby(statsKey, 'consumerMessages', count)(ilog.error)\n}\n\nexports.incrConsumers = function (count) {\n redisClient.hincrby(statsKey, 'consumers', count)(ilog.error)\n}\n\nexports.addRoomsHyperlog = function (roomId) {\n redisClient.pfadd(roomKey, roomId)(ilog.error)\n}\n\nexports.setConsumersStats = function (consumers) {\n redisClient.hset(serverKey, `${serverId}:${config.instancePort}`, consumers)(ilog.error)\n}\n\nexports.clientsStats = function * () {\n let res = yield [\n redisClient.pfcount(roomKey),\n redisClient.hgetall(statsKey),\n redisClient.hgetall(serverKey)\n ]\n res[1].rooms = '' + res[0]\n let online = Object.keys(res[2]).reduce((count, key) => count + (+res[2][key]), 0)\n return {\n total: res[1],\n online: online,\n current: res[2]\n }\n}", "dangerousExampleEn": "1. var md5 = require('md5');\n2. \n3. console.log(md5('password'));\nLine 3: This is weak for the brute-force attack because it uses md5, a weak hash function.", "safeExampleEn": "1. var bcrypt = require('bcrypt');\n2. \n3. bcrypt.hash(\"password\", 13, function(err, hash) {\n4. console.log(hash);\n5. });\nLine 3: This is safe from the brute-force attack because bcrypt is used to create hash data.", "contexts": [{"lineNo": 14, "eventType": "sink", "messageKey": "jschk.FORBIDDEN.WEAK_ALGORITHM.JS.defect", "params": {"arg0": "md5"}}]}} {"id": "61cc5990604a242416d6016112708fea813cc7e104f23c91c3dc1031fa76dbd4", "license": {"spdx": ["MIT"], "repo": "kevinljw/offol-web", "path": "controllers/postProj.js", "repo_head_hexsha": "087ff04df6205f60cb5dbb80588c5cc7cd489161", "stack_hexsha": "f2ec59913dd5e36628195bbaa70803df5350f52f", "match": "repo_path"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of weak cryptographic algorithm", "issueDescriptionEn": "A hash function is a one-way function that receives data of different lengths and maps it to random data of a fixed length. It is commonly used to store user passwords because it always produces the same output for a given input.\nBecause hash can be calculated very quickly, the hash functions, such as MD5 and SHA, may give the illusion of high performance. However they are vulnerable to random brute-force attacks. If you use the hash functions on simple data, they can be saved in the rainbow table, making it insecure. In addition, RC2, RC3, RC4, RC5, RC6, MD4, and DES are also known to be vulnerable.\nThere are many functions used to overcome the disadvantages of MD5 and SHA.\nIn Node.js, bcrypt is one of the functions that is commonly used with outstanding performance and easily replace them. The latest hash algorithms, such as Argon2, PBKDF2, and Scrypt, are also good alternatives. Make sure to add a salt to the hash in SHA-2 i.e. SHA-224, SHA-256, SHA-384, SHA-512.", "issueLineNumber": 314, "entireCode": "var secrets = require('../config/secrets');\nvar moment = require('moment');\n// var Article = require('../models/Article');\n// var Share = require('../models/Share');\n// var Idea = require('../models/Idea');\nvar User = require('../models/User');\nvar Project = require('../models/Project');\nvar hidStartSerial = secrets.projects.hidStartSerial;\nvar async = require('async');\nvar md5 = require('md5');\nvar nodemailer = require(\"nodemailer\");\nvar transporter = nodemailer.createTransport({\n service: 'SendGrid',\n auth: {\n user: secrets.sendgrid.user,\n pass: .sendgrid.password\n }\n});\nvar addNullNum = 10000000;\n\nvar allProjs = function(req, res) {\n\n\tProject.find({},function(err, projs) {\n \tif (err) console.error(err);\n\n \treturn projs;\n\t});\n \t\n};\n/**\n * GET /contact\n * Contact form page.\n */\nexports.getPostProj = function(req, res) {\n\tProject.find({}, null, {sort: {'_id': -1}}, function(err, projs) {\n \tif (err) throw err;\n\n\t\tres.render('postProj', {\n\t\t\ttitle: 'Project Management',\n\t\t\tallProjects: projs,\n\t\t\tisEditing: false,\n\t\t});\n\t\tallProjs = projs;\n\t});\n \n};\nexports.postGenerator = function(req, res, next) {\n\n\tProject.findById(req.params.id, function(err, proj) {\n\t\tif (!proj) {\n req.flash('errors', { msg: 'No project with that id exists.' });\n return res.redirect('/postProj');\n }\n\t\tgenerateWinnerSerial(req.body.feedBackObjNum, proj.hid, proj.goalmoney, function(winSerials){\n\t \t\tproj.winnerSerials = winSerials;\n\t \t\n\t\t proj.feedBackObjNum = req.body.feedBackObjNum;\n\t\t\t\t\n\t\t\t\tproj.save(function(err) {\n\t\t\t if (err) {\n\t\t\t return next(err);\n\t\t\t }\n\t\t\t req.flash('success', { msg: 'Done.' });\n\t\t\t res.redirect('/postProj/'+req.params.id);\n\t\t\t });\n\t\t \n\t\t});\n\t});\n}\nexports.postPostProj = function(req, res, next) {\n\treq.assert('title', 'Title must be at least 1 characters long').len(1);\n\treq.assert('name', 'Name must be at least 1 characters long').len(1);\n\treq.assert('abstract', 'Abstract must be at least 1 characters long').len(1);\n\treq.assert('content', 'Content must be at least 1 characters long').len(1);\n\treq.assert('video', 'video?').len(1);\n\treq.assert('money', 'money?').isInt();\n\tvar errors = req.validationErrors();\n\n\tif (errors) {\n\t req.flash('errors', errors);\n\t return res.redirect('/postProj');\n\t}\n\tProject.find({}, null, {sort:{\"hid\":-1}}, function(err, projs) {\n \tif (err) throw err;\n \tvar thisHid = hidStartSerial;\n \tif(projs.length>0){\n \t\tthisHid = parseInt(projs[0].hid)+1;\n \t}\n \tconsole.log(\"thisHid:\"+thisHid);\n \tallProjs = projs;\n\t\t// console.log(hidStartSerial, projs.length, thisHid);\n\t\tvar thisProject = new Project({\n\t hoster: req.body.name,\n\t title: req.body.title,\n\t\t abstract: req.body.abstract,\n\t\t goalmoney: parseInt(req.body.money),\n\t\t created_time: moment().format('MMMM Do YYYY, h:mm:ss a'),\n\t\t main_video: req.body.video.replace(\"watch?v=\", \"embed/\").replace(\"youtu.be\", \"www.youtube.com/embed/\"),\n\t\t content: req.body.content,\n\t\t bannerPImg: req.body.bannerPImg,\n\t\t coverPImg: req.body.coverPImg,\n\t\t bannerColor: req.body.bannerColor,\n\t\t hid: thisHid,\n\t\t ticketBuyArr: new Array(parseInt(req.body.money)+1).join('0'),\n\t\t feedBackObjNum: req.body.feedBackObjNum\n\t\t // picture: PictureIsOn?PicPath:''\n\t });\n\n\t\t// for(var i=0; i-1 || videoLink.indexOf(\"youtu.be\")>-1 || videoLink.indexOf(\"youtube\")>-1)){\n \tvideoLink = videoLink.replace(\"watch?v=\", \"v/\");\n \tvideoLink = videoLink.replace(\"youtu.be\", \"www.youtube.com/v\");\n \tvideoLink = videoLink.replace(\"vimeo.com\", \"player.vimeo.com/video\");\n \t// https://player.vimeo.com/video/10881014\n \tconsole.log(videoLink);\n \tLinkIsOn = true;\n }\n if(req.body.IsSendEmail){\n \t\n \tconsole.log(\"SendEmail!!\");\n }\n var thisArticle = new Article({\n\t title: req.body.title,\n\t\t content: req.body.content,\n\t\t author: user.profile.name,\n\t\t authorId: req.params.id,\n\t\t timestamp: moment().format('MMMM Do YYYY, h:mm:ss a'),\n\t\t link: LinkIsOn?videoLink:'',\n\t\t picture: PictureIsOn?PicPath:''\n\t });\n\t console.log(thisArticle);\n\t thisArticle.save(function(err) {\n\t if (err) {\n\t return next(err);\n\t }\n\t req.flash('success', { msg: 'Done.' });\n\t res.redirect('/article');\n\t });\n\t \n });\n\t\n};\nfunction generateWinnerSerial(amount, thisEmail, needForPeople, callback){\n\t// console.log(hostId, thisEmail, nowNum, needForPeople);\n\t\t// var nowNum = 0;\n\n\t\tvar winArr= new Array(parseInt(amount));\n\t\tconsole.log(winArr);\n\n\t\tasync.forEachOf(winArr, function (eachSerial, eachIndex, eachSerial_callback) {\n\t\t\tvar tmpEnN = thisEmail+eachIndex+Date.now();\n\t\t var getThisGuysMd5 = md5(tmpEnN);\n\t\t var thisGuysMd5cutInt = parseInt(getThisGuysMd5.substr(23),16);\n\t\t thisGuysMd5cutInt = thisGuysMd5cutInt%needForPeople;\n\n\t\t for(var i=0; i\"+thisGuysMd5cutInt);\n\t \n\t\t // thisProj.ticketBuyArr.forEach(function(eachEle,index){\n\t\t // \tif(eachEle) console.log(index, '-true');\n\t\t // });\n\t\t \n\n\t\n\t\n};", "dangerousExampleEn": "1. var md5 = require('md5');\n2. \n3. console.log(md5('password'));\nLine 3: This is weak for the brute-force attack because it uses md5, a weak hash function.", "safeExampleEn": "1. var bcrypt = require('bcrypt');\n2. \n3. bcrypt.hash(\"password\", 13, function(err, hash) {\n4. console.log(hash);\n5. });\nLine 3: This is safe from the brute-force attack because bcrypt is used to create hash data.", "contexts": [{"lineNo": 314, "eventType": "sink", "messageKey": "jschk.FORBIDDEN.WEAK_ALGORITHM.JS.defect", "params": {"arg0": "md5"}}]}} {"id": "22f504d6d4898d4c8797196b1141063694284493cbcb600c90582cc1262791ff", "license": {"spdx": ["MIT"], "repo": "xloem/bsvup", "path": "api.js", "repo_head_hexsha": "d4077ae93fca5e3551bd6f78f4fe078776656ba2", "stack_hexsha": "21bf46214096837782a4f22765a7b5ec1dd037e8", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of weak cryptographic algorithm", "issueDescriptionEn": "A hash function is a one-way function that receives data of different lengths and maps it to random data of a fixed length. It is commonly used to store user passwords because it always produces the same output for a given input.\nBecause hash can be calculated very quickly, the hash functions, such as MD5 and SHA, may give the illusion of high performance. However they are vulnerable to random brute-force attacks. If you use the hash functions on simple data, they can be saved in the rainbow table, making it insecure. In addition, RC2, RC3, RC4, RC5, RC6, MD4, and DES are also known to be vulnerable.\nThere are many functions used to overcome the disadvantages of MD5 and SHA.\nIn Node.js, bcrypt is one of the functions that is commonly used with outstanding performance and easily replace them. The latest hash algorithms, such as Argon2, PBKDF2, and Scrypt, are also good alternatives. Make sure to add a salt to the hash in SHA-2 i.e. SHA-224, SHA-256, SHA-384, SHA-512.", "issueLineNumber": 37, "entireCode": "const explorer = require('bitcore-explorers')\nconst Insight = explorer.Insight\nconst insight = new explorer.Insight('https://api.bitindex.network')\nconst bsv = require('bsv')\nconst fs = require('fs')\nconst BitDB = require('./bitdb.js')\nconst MimeLookup = require('mime-lookup');\nconst MIME = new MimeLookup(require('mime-db'))\nconst crypto = require(\"crypto\")\n\nasync function getUTXOs(address){\n return new Promise((resolve, reject)=>{\n insight.getUnspentUtxos(address,(err,unspents)=>{\n if(err){\n reject(\"Insight API return Errors: \" + err)\n }else{\n utxos = unspents\n resolve(unspents)\n }\n })\n })\n}\n\nasync function broadcast(tx){\n return new Promise((resolve, reject)=>{\n insight.broadcast(tx.toString(),(err,res)=>{\n if(err){\n console.log(\" Insight API return Errors: \")\n console.log(err)\n reject(\"Insight API return Errors: \" + err)\n }else resolve(res)\n })\n })\n}\n\nasync function findExist(buf, mime){\n var sha1 = crypto.createHash('sha1').update(buf).digest('hex')\n if(global.debug)console.log(sha1)\n if(global.quick)return null\n var records = []\n if(fs.existsSync(`./.bsv/objects/${sha1}`))records = JSON.parse(fs.readFileSync(`./.bsv/objects/${sha1}`))\n if(!Array.isArray(records) || records.length==0){\n console.log(\" - 向BitDB搜索已存在的文件记录 Querying BitDB\")\n records = await BitDB.findExist(buf)\n records = records.filter(record=>record.contenttype==mime)\n fs.writeFileSync(`./.bsv/objects/${sha1}`, JSON.stringify(records))\n }\n if(records.length==0)return null\n var txs = await Promise.all(records.map(record => getTX(record.txid)))\n var matchTX = await Promise.race(txs.map(tx=>{\n return new Promise(async (resolve, reject)=>{\n var databuf = await getData(tx).catch(err=>new Buffer(0))\n if(databuf.equals(buf))resolve(tx)\n else reject()\n })\n })).catch(err=>null)\n if(matchTX)return matchTX\n else return null\n}\n\nvar dRecords = null\nasync function findD(key, address ,value){\n if(global.quick)return null\n //var dRecords = await BitDB.findD(key, address)\n if(!dRecords){\n console.log(`查询${address}下所有D记录中...`)\n console.log(`Query all D records on ${address} from BitDB...`)\n dRecords = await BitDB.findD(null, address)\n }\n var keyDRecords = dRecords.filter(record=>record.key==key)\n var dRecord = (keyDRecords.length>0)?keyDRecords[0]:null\n if(dRecord && dRecord.value == value)return true\n else return false\n}\n\nasync function getTX(txid){\n return new Promise((resolve, reject)=>{\n if(fs.existsSync(`./.bsv/tx/${txid}`)){\n var rawtx = fs.readFileSync(`./.bsv/tx/${txid}`).toString()\n resolve(bsv.Transaction(rawtx))\n } else{\n insight.requestGet(`/api/tx/${txid}`,(err, res, body)=>{\n if(err || res.statusCode !== 200) reject(err || body)\n //console.log(body)\n try{\n var rawtx = JSON.parse(body).rawtx\n fs.writeFileSync(`./.bsv/tx/${txid}`, rawtx)\n resolve(bsv.Transaction(rawtx))\n }catch(err){\n console.log(\"获取TX时发生错误 Error acquring TX\")\n console.log(body)\n reject(err)\n }\n })\n }\n }).catch(err=>null)\n}\n\n\nasync function getData(tx){\n var dataout = tx.outputs.filter(out=>out.script.isDataOut())\n if(dataout.length==0)throw new Error(\"Not Data TX\")\n var bufs = dataout[0].script.chunks.map(chunk=>(chunk.buf)?chunk.buf:new Buffer(0))\n if(bufs[1].toString()==\"19HxigV4QyBv3tHpQVcUEQyq1pzZVdoAut\")return bufs[2]\n else{\n // 处理Bcat\n var bParts = bufs.slice(7).map(buf=>buf.toString('hex'))\n if(global.debug)console.log(\"处理Bcat中。。。\" + bParts)\n var bPartTXs = await Promise.all(bParts.map(bPart=>getTX(bPart)))\n if(global.debug)console.log(bPartTXs.map(tx=>tx.id))\n var bPartBufs = bPartTXs.map(tx=>tx.outputs.filter(out=>out.script.isDataOut())[0].script.chunks[2].buf)\n if(global.debug)console.log(bPartBufs.map(buf=>buf.length))\n var buf = Buffer.concat(bPartBufs)\n if(global.debug)console.log(buf.length)\n return buf\n }\n}\n\nmodule.exports = {\n findD: findD,\n findExist: findExist,\n broadcast: broadcast,\n getUTXOs: getUTXOs\n}", "dangerousExampleEn": "1. var md5 = require('md5');\n2. \n3. console.log(md5('password'));\nLine 3: This is weak for the brute-force attack because it uses md5, a weak hash function.", "safeExampleEn": "1. var bcrypt = require('bcrypt');\n2. \n3. bcrypt.hash(\"password\", 13, function(err, hash) {\n4. console.log(hash);\n5. });\nLine 3: This is safe from the brute-force attack because bcrypt is used to create hash data.", "contexts": [{"lineNo": 37, "eventType": "sink", "messageKey": "jschk.FORBIDDEN.WEAK_ALGORITHM.JS.defect", "params": {"arg0": "sha1"}}]}} {"id": "e9863e84b928fce95d37c0a57722d5ecef4c0511168c5064aeee88c7237f78c3", "license": {"spdx": ["MIT"], "repo": "chrisdothtml/hyper-stylesheet", "path": "lib/utils.js", "repo_head_hexsha": "515473b19530ffa3bddbb7ad69acf372ce32c583", "stack_hexsha": "b927190a1da91ba00faa65c313132a8d2112aa6c", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of weak cryptographic algorithm", "issueDescriptionEn": "A hash function is a one-way function that receives data of different lengths and maps it to random data of a fixed length. It is commonly used to store user passwords because it always produces the same output for a given input.\nBecause hash can be calculated very quickly, the hash functions, such as MD5 and SHA, may give the illusion of high performance. However they are vulnerable to random brute-force attacks. If you use the hash functions on simple data, they can be saved in the rainbow table, making it insecure. In addition, RC2, RC3, RC4, RC5, RC6, MD4, and DES are also known to be vulnerable.\nThere are many functions used to overcome the disadvantages of MD5 and SHA.\nIn Node.js, bcrypt is one of the functions that is commonly used with outstanding performance and easily replace them. The latest hash algorithms, such as Argon2, PBKDF2, and Scrypt, are also good alternatives. Make sure to add a salt to the hash in SHA-2 i.e. SHA-224, SHA-256, SHA-384, SHA-512.", "issueLineNumber": 18, "entireCode": "import crypto from 'crypto'\nimport { accessSync } from 'fs'\n\nexport function fileExists (path) {\n let result\n\n try {\n accessSync(path)\n result = true\n } catch (e) {\n result = false\n }\n\n return result\n}\n\nexport function md5 (input) {\n return crypto\n .createHash('md5')\n .update(input)\n .digest('hex')\n}", "dangerousExampleEn": "1. var md5 = require('md5');\n2. \n3. console.log(md5('password'));\nLine 3: This is weak for the brute-force attack because it uses md5, a weak hash function.", "safeExampleEn": "1. var bcrypt = require('bcrypt');\n2. \n3. bcrypt.hash(\"password\", 13, function(err, hash) {\n4. console.log(hash);\n5. });\nLine 3: This is safe from the brute-force attack because bcrypt is used to create hash data.", "contexts": [{"lineNo": 18, "eventType": "sink", "messageKey": "jschk.FORBIDDEN.WEAK_ALGORITHM.JS.defect", "params": {"arg0": "md5"}}]}} {"id": "909d4859439f09f856866138b44deaf4e08dd7b8b61ed5f7a4dda9fd266cf81f", "license": {"spdx": ["MIT"], "repo": "lahirudanushka/RC4-Crypto", "path": "src/index.js", "repo_head_hexsha": "13c9cfda0490d0f508a436eae04863b375eb51be", "stack_hexsha": "34186a0d5b1476f92577ff1d150d343962d00be4", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of weak cryptographic algorithm", "issueDescriptionEn": "A hash function is a one-way function that receives data of different lengths and maps it to random data of a fixed length. It is commonly used to store user passwords because it always produces the same output for a given input.\nBecause hash can be calculated very quickly, the hash functions, such as MD5 and SHA, may give the illusion of high performance. However they are vulnerable to random brute-force attacks. If you use the hash functions on simple data, they can be saved in the rainbow table, making it insecure. In addition, RC2, RC3, RC4, RC5, RC6, MD4, and DES are also known to be vulnerable.\nThere are many functions used to overcome the disadvantages of MD5 and SHA.\nIn Node.js, bcrypt is one of the functions that is commonly used with outstanding performance and easily replace them. The latest hash algorithms, such as Argon2, PBKDF2, and Scrypt, are also good alternatives. Make sure to add a salt to the hash in SHA-2 i.e. SHA-224, SHA-256, SHA-384, SHA-512.", "issueLineNumber": 3, "entireCode": "\nconst encrypt = (str, key=\"rc4@123\") => {\n return str && key ? rc4(str, key) : null;\n}\n\nconst decrypt = (str, key=\"rc4@123\") => {\n return str && key ? rc4(str, key) : null;\n}\n\nconst rc4 = (str, key) => {\n\n let s = [], j = 0, x, result = '';\n for (let i = 0; i < 256; i++) {\n s[i] = i;\n }\n\n for (let i = 0; i < 256; i++) {\n j = (j + s[i] + key.charCodeAt(i % key.length)) % 256;\n x = s[i];\n s[i] = s[j];\n s[j] = x;\n }\n\n i = 0;\n j = 0;\n\n for (let y = 0; y < str.length; y++) {\n i = (i + 1) % 256;\n j = (j + s[i]) % 256;\n x = s[i];\n s[i] = s[j];\n s[j] = x;\n result += String.fromCharCode(str.charCodeAt(y) ^ s[(s[i] + s[j]) % 256]);\n }\n return result;\n}\n\nmodule.exports = { encrypt, decrypt };", "dangerousExampleEn": "1. var md5 = require('md5');\n2. \n3. console.log(md5('password'));\nLine 3: This is weak for the brute-force attack because it uses md5, a weak hash function.", "safeExampleEn": "1. var bcrypt = require('bcrypt');\n2. \n3. bcrypt.hash(\"password\", 13, function(err, hash) {\n4. console.log(hash);\n5. });\nLine 3: This is safe from the brute-force attack because bcrypt is used to create hash data.", "contexts": [{"lineNo": 3, "eventType": "sink", "messageKey": "jschk.FORBIDDEN.WEAK_ALGORITHM.JS.defect", "params": {"arg0": "rc4"}}]}} {"id": "98393dc94f2d37087921544088bd2355b67eee9acdda793fa731b0e6a57c180f", "license": {"spdx": ["MIT"], "repo": "whendev/Task-List-Api", "path": "src/controllers/user.js", "repo_head_hexsha": "a7b0d4c1ac50026f0e8b03a74cae0a48dd9a797b", "stack_hexsha": "5c5093cddf091cb86550cde02d252e1f53854e44", "match": "repo_path"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of weak cryptographic algorithm", "issueDescriptionEn": "A hash function is a one-way function that receives data of different lengths and maps it to random data of a fixed length. It is commonly used to store user passwords because it always produces the same output for a given input.\nBecause hash can be calculated very quickly, the hash functions, such as MD5 and SHA, may give the illusion of high performance. However they are vulnerable to random brute-force attacks. If you use the hash functions on simple data, they can be saved in the rainbow table, making it insecure. In addition, RC2, RC3, RC4, RC5, RC6, MD4, and DES are also known to be vulnerable.\nThere are many functions used to overcome the disadvantages of MD5 and SHA.\nIn Node.js, bcrypt is one of the functions that is commonly used with outstanding performance and easily replace them. The latest hash algorithms, such as Argon2, PBKDF2, and Scrypt, are also good alternatives. Make sure to add a salt to the hash in SHA-2 i.e. SHA-224, SHA-256, SHA-384, SHA-512.", "issueLineNumber": 12, "entireCode": "const md5 = require('md5');\nconst userRepository = require('../repositories/user');\nconst authService = require('../services/auth-service');\n\nfunction propriedades() {\n const content = {\n create: async (req, res) => {\n try {\n await userRepository.createUserDB({\n name: req.body.name,\n email: req.body.email,\n password: md5(req.body.password + global.SALT_KEY),\n });\n res.status(201).send({ massage: 'Cliente cadastrado com sucesso!' });\n } catch (error) {\n res.status(400).send({ massage: 'Não foi possivel cadastrar novo user!' });\n }\n },\n login: async (req, res) => {\n try {\n const user = await userRepository.authenticate({\n email: req.body.email,\n password: (.password + global.SALT_KEY),\n });\n\n if (!user) {\n // eslint-disable-next-line no-undef\n res.status(404).send({ message: 'Email ou senha invalidos!', data: error });\n }\n\n const token = await authService.gerateToken({\n id: user._id,\n email: user.email,\n name: user.name,\n });\n\n res.status(201).send({\n token,\n data: {\n email: user.email,\n name: user.name,\n },\n });\n } catch (error) {\n res.status(400).send({ message: 'Email ou senha invalidos!', data: error });\n }\n },\n };\n return content;\n}\n\nmodule.exports = propriedades();", "dangerousExampleEn": "1. var md5 = require('md5');\n2. \n3. console.log(md5('password'));\nLine 3: This is weak for the brute-force attack because it uses md5, a weak hash function.", "safeExampleEn": "1. var bcrypt = require('bcrypt');\n2. \n3. bcrypt.hash(\"password\", 13, function(err, hash) {\n4. console.log(hash);\n5. });\nLine 3: This is safe from the brute-force attack because bcrypt is used to create hash data.", "contexts": [{"lineNo": 12, "eventType": "sink", "messageKey": "jschk.FORBIDDEN.WEAK_ALGORITHM.JS.defect", "params": {"arg0": "md5"}}]}} {"id": "faa282d156f99e2e34f1819d1eae2a95c7227176a7b45ecfd016aae0ad48ad62", "license": {"spdx": ["MIT"], "repo": "cuihuale/mui", "path": "node_modules/gmudoc/views/gmu/index.js", "repo_head_hexsha": "18383fbb9aa25fb99d91e09c3a969a5912e93eab", "stack_hexsha": "bc3daa13146df95d47436ffbe7102d2a2ba8797b", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of weak cryptographic algorithm", "issueDescriptionEn": "A hash function is a one-way function that receives data of different lengths and maps it to random data of a fixed length. It is commonly used to store user passwords because it always produces the same output for a given input.\nBecause hash can be calculated very quickly, the hash functions, such as MD5 and SHA, may give the illusion of high performance. However they are vulnerable to random brute-force attacks. If you use the hash functions on simple data, they can be saved in the rainbow table, making it insecure. In addition, RC2, RC3, RC4, RC5, RC6, MD4, and DES are also known to be vulnerable.\nThere are many functions used to overcome the disadvantages of MD5 and SHA.\nIn Node.js, bcrypt is one of the functions that is commonly used with outstanding performance and easily replace them. The latest hash algorithms, such as Argon2, PBKDF2, and Scrypt, are also good alternatives. Make sure to add a salt to the hash in SHA-2 i.e. SHA-224, SHA-256, SHA-384, SHA-512.", "issueLineNumber": 363, "entireCode": "(function(){\n var util = require( '../../lib/util.js' ),\n _ = util._,\n ejs = require( 'ejs' ),\n marked = require( 'marked' ),\n path = require( 'path' ),\n sha1 = require( 'sha1' ),\n qr = require( 'qrpng' ),\n async = require( 'async' ),\n GlobCollector = require( '../../lib/collector.js' ).GlobCollector,\n view;\n\n function View() {\n var me = this;\n\n this.locals = {};\n this.localStack = [ this.locals ];\n this.qrcodes = {};\n\n\n // 注册变量和方法给tpl用\n this.assign( '_', _ );\n\n\n // 最好把一些危险的方法移出。比如build, render方法。\n _.forEach( View.prototype, function( fn, name ) {\n me.assign( name, function() {\n return fn.apply( me, arguments );\n } );\n } );\n\n\n // 注册主题\n me.assign( 'themes', {\n purple: './css/purple.css',\n blue: './css/blue.css',\n dark: './css/dark.css',\n orange: './css/orange.css'\n });\n me.assign( 'activeTheme', 'purple' );\n }\n\n util.extend( View.prototype, {\n init: function( opts ) {\n this.assign( 'title', opts.title || 'GMU API 文档' );\n this.themeDir = opts.tplDir || path.join( __dirname, 'tpl' );\n },\n\n assign: function( key, val ) {\n this.locals[ key ] = val;\n },\n\n fetch: function( key ) {\n return this.locals[ key ] || '';\n },\n\n build: function( json, complete ) {\n var me = this,\n qrcodes;\n\n this.files = {};\n this.transform( json );\n this.render();\n\n qrcodes = this.qrcodes;\n\n async.each( Object.keys( qrcodes ), function( key, next ){\n var value = qrcodes[ key ];\n\n qr( value, 3, function( err, png ) {\n if ( err ) {\n throw new Error( err );\n }\n\n me.files[ key ] = png;\n next();\n });\n }, function( err ){\n if( !err ) {\n complete( me.files );\n }\n });\n\n },\n\n gennerateID: function( str ) {\n return str.replace(/[^a-zA-Z0-9_]+/g, '_');\n },\n\n forUrl: function( href ) {\n return '#' + this.gennerateID( href );\n },\n\n transform: function( json ) {\n var navs = {},\n modules = {},\n me = this;\n\n _.forEach( json.modules, function( module ) {\n var modulename = module.name,\n host = navs[ modulename ] = {};\n\n _.forEach( module.items, function( item ) {\n host[ modulename ] = host[ modulename ] || [];\n host[ modulename ].push({\n text: item.shortname || item.name,\n skin: item.itemtype,\n href: me.forUrl( modulename + ':' + item.name )\n });\n me.addSearchEntry( item.shortname || item.name, item.name,\n me.forUrl( modulename + ':' + item.name),\n item.description, modulename );\n } );\n\n _.forEach( module.classes, function( clazz ) {\n var classname = clazz.name,\n items = [],\n options = [],\n events = [];\n\n _.forEach( clazz.items, function( item ){\n host[ classname ] = host[ classname ] || [];\n\n switch( item.itemtype ) {\n case 'event':\n events.push( item );\n me.addSearchEntry( item.shortname || item.name, item.name,\n me.forUrl( modulename + ':' + classname + ':events' ),\n item.description, classname + ' - Events' );\n break;\n\n case 'property':\n if ( /^options/i.exec( item.name ) ) {\n options.push( item );\n me.addSearchEntry( item.shortname || item.name, item.name,\n me.forUrl( modulename + ':' + classname + ':options' ),\n item.description, classname + ' - Options' );\n\n // 如果property不是options大头的,则添加到items里面去。\n break;\n }\n case 'method':\n case 'constructor':\n items.push( item );\n me.addSearchEntry( item.shortname || item.name, item.name,\n me.forUrl( modulename + ':' + classname + ':' + item.name),\n item.description, classname );\n\n host[ classname ].push({\n text: item.shortname || item.name,\n skin: item.itemtype,\n href: me.forUrl( modulename + ':' + classname + ':' + item.name )\n });\n break;\n }\n } );\n\n events.length && host[ classname ].unshift({\n skin: 'events',\n text: 'events',\n href: me.forUrl( modulename + ':' + classname + ':events' )\n });\n\n options.length && host[ classname ].unshift({\n skin: 'options',\n text: 'options',\n href: me.forUrl( modulename + ':' + classname + ':options' )\n });\n\n clazz.items = items;\n clazz.options = options;\n clazz.events = events;\n clazz.title = clazz.title || '';\n clazz.description = clazz.description || '';\n\n clazz.plugins = clazz.plugins.map(function( name ){\n var obj = module.classes[ name ];\n obj.isPlugin = true;\n return obj;\n });\n\n clazz.plugins.length && host[ classname ].push({\n skin: 'plugins',\n text: 'plugins',\n href: me.forUrl( modulename + ':' + classname + ':plugins' )\n });\n } );\n\n module.title = module.title || '';\n module.description = module.description || '';\n } );\n\n me.assign( 'navs', navs );\n me.assign( 'files', json.files );\n me.assign( 'modules', json.modules );\n },\n\n renderTpl: function( file, data ) {\n var fileconent,\n locals;\n\n locals = this.localStack[ this.localStack.length - 1 ];\n\n data = data ? _.extend( {}, locals, data ) : locals;\n file = path.join( this.themeDir, file + '.ejs' );\n\n fileconent = util.readFile( file );\n\n this.localStack.push( data );\n fileconent = ejs.render( fileconent, {\n locals: data\n } );\n this.localStack.pop();\n\n return fileconent;\n },\n\n render: function() {\n var content = this.renderTpl( 'layout' ),\n collector = new GlobCollector(),\n files = this.files;\n\n files[ 'index.html' ] = content;\n collector.collect(['**/*.*', '!*.ejs'], this.themeDir ).forEach(function( file ){\n files[ file.relative ] = file.absolute;\n });\n },\n\n renderFileInfo: function( filename ) {\n var me = this,\n host = me.localStack[ me.localStack.length - 1 ],\n files = me.fetch('files'),\n file = files[ filename || host.file ],\n html = '';\n\n html += '文件' + file.name ;\n\n if( file && file[ 'import' ] ) {\n html += '依赖'\n html += me._fixDependencies( file, files ).join(', ');\n }\n return '
    !html
    '.replace(/\\!html/, html);\n },\n\n _fixDependencies: function( file, map ) {\n var me = this,\n ret = file[ 'import' ] || [];\n\n if ( !file._fixed && file[ 'import' ] ) {\n\n ret.forEach(function( item ) {\n map[ item ] && (ret = _.union( me._fixDependencies( map[ item ], map ), ret ));\n });\n\n file._fixed = true;\n }\n\n return file[ 'import' ] = ret;\n },\n\n renderUses: function( arr, wrap ) {\n var parts = [],\n me = this,\n host = me.localStack[ me.localStack.length - 1 ],\n modulename = host.module,\n classes = host.modules[ modulename ].classes,\n clazz;\n\n arr.forEach(function( val ) {\n if ( val.description ) {\n parts.push( me.markdown( val.description ).replace(/^

    (.*?)<\\/p>/, '$1') );\n } else {\n clazz = classes[ val.name ];\n parts.push( me.markdown( '[' + (clazz ? clazz.shortname || clazz.name : val.name) + '](#' + modulename + ':' + val.name + ')' ).replace(/^

    (.*?)<\\/p>/, '$1') );\n }\n });\n\n wrap = wrap || '

    依赖: %s

    ';\n\n return wrap.replace(/%s/, parts.join(', ') );\n },\n\n renderParams: function( params ) {\n var me = this,\n html = '';\n\n if ( params && params.length ) {\n html += '
      ';\n\n _.forEach( params, function( param ) {\n html += '
    • ';\n\n param.name && (html += '' + param.name + '');\n\n html += ' {' + param.type.join( ', ') + '}';\n\n if ( param.optional ) {\n html += ' [可选]';\n }\n\n if ( param.defaultvalue ) {\n html += ' [默认值: ' + param.defaultvalue + '] ';\n }\n\n html += '';\n\n html += ' ' + param.description ? me.markdown( param.description ) : '';\n\n if ( param.props ) {\n html += me.renderParams.call( me, param.props );\n }\n\n html += '
    • ';\n } );\n\n html += '
    ';\n }\n\n return html;\n },\n\n markdown: function( text ) {\n return marked( text );\n },\n\n formatExample: function( text ) {\n if ( !/```/.test( text ) ) {\n text = '```javascript\\n' + text + '\\n```';\n }\n return this.markdown( text );\n },\n\n addSearchEntry: function( label, value, href, desc, category ) {\n var arr;\n\n arr = this._search_entries || (this._search_entries = []);\n desc = this.stripTags( desc );\n desc = desc.substring(0, 30);\n\n arr.push({\n label: label,\n value: value,\n desc: desc,\n href: href,\n category: category\n });\n },\n\n getSearchEntry: function() {\n return this._search_entries || [];\n },\n\n stripTags: function( input, allowed ) {\n allowed = (((allowed || \"\") + \"\").toLowerCase().match(/<[a-z][a-z0-9]*>/g) || []).join(''); // making sure the allowed arg is a string containing only tags in lowercase ()\n var tags = /<\\/?([a-z][a-z0-9]*)\\b[^>]*>/gi,\n commentsAndPhpTags = /|<\\?(?:php)?[\\s\\S]*?\\?>/gi;\n return input.replace(commentsAndPhpTags, '').replace(tags, function($0, $1) {\n return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : '';\n });\n },\n\n addQrcode: function( data ) {\n var hash = './qrcode/' + sha1( data ) + '.png';\n\n this.qrcodes[ hash ] = data;\n return hash;\n }\n } );\n\n\n\n\n module.exports = view = new View();\n\n // hack marked.InlineLexer\n (function(){\n var outputLink = marked.InlineLexer.prototype.outputLink;\n\n\n marked.InlineLexer.prototype.outputLink = function(cap, link) {\n var match;\n\n if (cap[0][0] !== '!') {\n match = /^#(.*:.*)/.exec( link.href );\n if ( match ) {\n link.href = view.forUrl( match[ 1 ] );\n }\n } else {\n match = /^qrcode:(.*)$/i.exec( link.href );\n match && (link.href = view.addQrcode( match[ 1 ] ));\n }\n return outputLink.apply( this, arguments );\n };\n })();\n})();", "dangerousExampleEn": "1. var md5 = require('md5');\n2. \n3. console.log(md5('password'));\nLine 3: This is weak for the brute-force attack because it uses md5, a weak hash function.", "safeExampleEn": "1. var bcrypt = require('bcrypt');\n2. \n3. bcrypt.hash(\"password\", 13, function(err, hash) {\n4. console.log(hash);\n5. });\nLine 3: This is safe from the brute-force attack because bcrypt is used to create hash data.", "contexts": [{"lineNo": 363, "eventType": "sink", "messageKey": "jschk.FORBIDDEN.WEAK_ALGORITHM.JS.defect", "params": {"arg0": "sha1"}}]}} {"id": "435e9c8468d1b11a6c9f3c2e4d6c2399fdcd7e949779f08f3621cda6d394f76f", "license": {"spdx": ["MIT"], "repo": "MrJustyy/jkzx_fe", "path": "libs/api-generator/utils.js", "repo_head_hexsha": "9d379a2f76a168dc3af9a5c82e72e27ad8e3638f", "stack_hexsha": "35c869bd4eabff9b1ffd09dadca10a1d14448cd5", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of weak cryptographic algorithm", "issueDescriptionEn": "A hash function is a one-way function that receives data of different lengths and maps it to random data of a fixed length. It is commonly used to store user passwords because it always produces the same output for a given input.\nBecause hash can be calculated very quickly, the hash functions, such as MD5 and SHA, may give the illusion of high performance. However they are vulnerable to random brute-force attacks. If you use the hash functions on simple data, they can be saved in the rainbow table, making it insecure. In addition, RC2, RC3, RC4, RC5, RC6, MD4, and DES are also known to be vulnerable.\nThere are many functions used to overcome the disadvantages of MD5 and SHA.\nIn Node.js, bcrypt is one of the functions that is commonly used with outstanding performance and easily replace them. The latest hash algorithms, such as Argon2, PBKDF2, and Scrypt, are also good alternatives. Make sure to add a salt to the hash in SHA-2 i.e. SHA-224, SHA-256, SHA-384, SHA-512.", "issueLineNumber": 102, "entireCode": "\"use strict\";\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};\nexports.__esModule = true;\nexports.getPackageName = exports.templateFilesRelyConfirm = exports.templateFilesOverwriteConfirm = exports.getOldProjectId = exports.getMd5 = exports.isInRoot = exports.moveFile = exports.writeFile = exports.mixGeneratedCode = exports.relativeImport = exports.withoutExt = void 0;\nvar path = require(\"path\");\nvar mkdirp = require(\"mkdirp\");\nvar fs = require(\"fs\");\nvar crypto = require(\"crypto\");\nvar inquirer = require(\"inquirer\");\nvar chalk_1 = require(\"chalk\");\nvar packageJson = require('../package.json');\nfunction withoutExt(p) {\n return p.replace(/\\.[^/.]+$/, '');\n}\nexports.withoutExt = withoutExt;\nfunction relativeImport(from, to) {\n return withoutExt('./' + path.relative(path.dirname(from), to));\n}\nexports.relativeImport = relativeImport;\nfunction mixGeneratedCode(codeArr) {\n var imports = codeArr.map(function (c) { return c[\"import\"]; });\n var bodies = codeArr.map(function (c) { return c.body; });\n var _exports = codeArr.map(function (c) { return c[\"export\"]; });\n return \"\\n \" + imports.join('\\n') + \"\\n \" + bodies.join('\\n') + \"\\n \" + _exports.join('\\n') + \"\\n \";\n}\nexports.mixGeneratedCode = mixGeneratedCode;\nfunction writeFile(filepath, contents) {\n return new Promise(function (resolve, reject) {\n mkdirp(path.dirname(filepath), function (err) {\n if (err)\n return reject(\"filepath: \" + filepath + \", \" + err);\n fs.writeFile(filepath, contents, function (err) {\n if (err)\n return reject(\"filepath: \" + filepath + \", \" + err);\n resolve();\n });\n });\n });\n}\nexports.writeFile = writeFile;\nfunction moveFile(from, to) {\n return new Promise(function (resolve, reject) {\n mkdirp(path.dirname(to), function (err) {\n if (err)\n return reject(\"\\u8BFB\\u53D6\\u6587\\u4EF6\\u5931\\u8D25: \" + from + \", \" + err);\n var contents = fs.readFileSync(from);\n fs.writeFile(to, contents, function (err) {\n if (err)\n return reject(\"\\u5199\\u5165\\u6587\\u4EF6\\u5931\\u8D25: \" + to + \", \" + err);\n resolve();\n });\n });\n });\n}\nexports.moveFile = moveFile;\n/**\n * 命令是否在根目录执行\n */\nfunction isInRoot() {\n var cwd = process.cwd();\n var flag = fs.existsSync(path.resolve(cwd, 'package.json'));\n return flag;\n}\nexports.isInRoot = isInRoot;\n/** 获取文件md5 */\nfunction getMd5(fileContent) {\n var hash = crypto.createHash('md5');\n hash.update(fileContent);\n return hash.digest('hex');\n}\nexports.getMd5 = getMd5;\nfunction getOldProjectId(rappperPath) {\n var indexPath = path.resolve(process.cwd(), rappperPath, './index.ts');\n try {\n var content = fs.readFileSync(indexPath, 'utf-8') || '';\n var projectIdStr = content.split('\\n')[1] || '';\n var matchArr = projectIdStr.match(/\\/\\*\\sRap仓库id:\\s(\\S*)\\s\\*\\//) || [];\n return matchArr[1];\n }\n catch (err) {\n return undefined;\n }\n}\nexports.getOldProjectId = getOldProjectId;\n/** 模板文件覆盖确认 */\nfunction templateFilesOverwriteConfirm() {\n return __awaiter(this, void 0, void 0, function () {\n var question, answers;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n question = [\n {\n name: 'confirmed',\n type: 'confirm',\n message: chalk_1[\"default\"].green('检测到您修改了 rapper 生成的模板代码,新生成的模板代码将覆盖您的修改,确定要继续么?'),\n \"default\": false\n },\n ];\n return [4 /*yield*/, inquirer.prompt(question)];\n case 1:\n answers = _a.sent();\n return [2 /*return*/, answers];\n }\n });\n });\n}\nexports.templateFilesOverwriteConfirm = templateFilesOverwriteConfirm;\n/** 存在接口依赖被删确认 */\nfunction templateFilesRelyConfirm() {\n return __awaiter(this, void 0, void 0, function () {\n var question, answers;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n question = [\n {\n name: 'confirmed',\n type: 'confirm',\n message: chalk_1[\"default\"].green('确定要继续同步接口到本地吗? (会存在页面中调用的接口不存在的风险)?'),\n \"default\": false\n },\n ];\n return [4 /*yield*/, inquirer.prompt(question)];\n case 1:\n answers = _a.sent();\n return [2 /*return*/, answers];\n }\n });\n });\n}\nexports.templateFilesRelyConfirm = templateFilesRelyConfirm;\n/** 获取当前包名 */\nfunction getPackageName() {\n return packageJson.name;\n}\nexports.getPackageName = getPackageName;", "dangerousExampleEn": "1. var md5 = require('md5');\n2. \n3. console.log(md5('password'));\nLine 3: This is weak for the brute-force attack because it uses md5, a weak hash function.", "safeExampleEn": "1. var bcrypt = require('bcrypt');\n2. \n3. bcrypt.hash(\"password\", 13, function(err, hash) {\n4. console.log(hash);\n5. });\nLine 3: This is safe from the brute-force attack because bcrypt is used to create hash data.", "contexts": [{"lineNo": 102, "eventType": "sink", "messageKey": "jschk.FORBIDDEN.WEAK_ALGORITHM.JS.defect", "params": {"arg0": "md5"}}]}} {"id": "2e1952b9ac5ca8ca6711417dd9ef3a1c07a754052523c7fca1f3dd55d3c068a3", "license": {"spdx": ["MIT"], "repo": "Lraym001/cs595-s21", "path": "assignments/Raymond/6/index.js", "repo_head_hexsha": "318c20c89e0221813623994d826659632acb4232", "stack_hexsha": "75fb4905da99fce8e32c4d87d213c776285b8ce8", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of weak cryptographic algorithm", "issueDescriptionEn": "A hash function is a one-way function that receives data of different lengths and maps it to random data of a fixed length. It is commonly used to store user passwords because it always produces the same output for a given input.\nBecause hash can be calculated very quickly, the hash functions, such as MD5 and SHA, may give the illusion of high performance. However they are vulnerable to random brute-force attacks. If you use the hash functions on simple data, they can be saved in the rainbow table, making it insecure. In addition, RC2, RC3, RC4, RC5, RC6, MD4, and DES are also known to be vulnerable.\nThere are many functions used to overcome the disadvantages of MD5 and SHA.\nIn Node.js, bcrypt is one of the functions that is commonly used with outstanding performance and easily replace them. The latest hash algorithms, such as Argon2, PBKDF2, and Scrypt, are also good alternatives. Make sure to add a salt to the hash in SHA-2 i.e. SHA-224, SHA-256, SHA-384, SHA-512.", "issueLineNumber": 11, "entireCode": "const express = require('express')\nconst { createReadStream } = require('fs')\nconst fs = require('fs')\nconst app = express()\nconst md5 = require('md5')\n\nvar log = require('C:/Users/Louis/OneDrive/Desktop/6/fingerprints.json')\n\napp.get('/', (req, res) => \n\t\t{\n\t\tvar userHash = md5(req.headers.accept+req.headers['user-agent']);\n\t\tvar date = new Date();\n\n\t if (log[userHash]) \n\t \t{\n\t\t \tvar user = log[userHash]['user-agent']\n log[userHash]['last-visit'] = date\n\t\t \tconsole.log('Returning User!');\n\n\t \t}\t \n\t else \n\t \t{\n\t\t \tconsole.log('New User');\n\t\t \tstream = createReadStream('index.html');\n\t \t\tstream.pipe(res);\n\t\t \tlog[userHash] = req.headers;\n\t\t \tlog[userHash]['last-visit'] = date\t \n\n\n\n\t \t}\n\n\tfs.writeFile('fingerprints.json', JSON.stringify(log), (error) => \n \t\t{ \n\t\t\t if (error) { \n\t\t\t console.log(error); \n\t\t\t } \n\t\t\t}); \t\n\t\t});\n\napp.listen(4000)", "dangerousExampleEn": "1. var md5 = require('md5');\n2. \n3. console.log(md5('password'));\nLine 3: This is weak for the brute-force attack because it uses md5, a weak hash function.", "safeExampleEn": "1. var bcrypt = require('bcrypt');\n2. \n3. bcrypt.hash(\"password\", 13, function(err, hash) {\n4. console.log(hash);\n5. });\nLine 3: This is safe from the brute-force attack because bcrypt is used to create hash data.", "contexts": [{"lineNo": 11, "eventType": "sink", "messageKey": "jschk.FORBIDDEN.WEAK_ALGORITHM.JS.defect", "params": {"arg0": "md5"}}]}} {"id": "fc9ead87d09577299cdc4020ff0a24929b638ef53da4d121283223eb4aa229f3", "license": {"spdx": ["Apache-2.0"], "repo": "modscleo4/jsdb", "path": "core/User.js", "repo_head_hexsha": "324cfd8678d40f34fcd84b9b11f9f064fbe46e6b", "stack_hexsha": "b82d8cbd07b1f0a8bbe4533b02d75a9c88b2a1e3", "match": "repo_path"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of weak cryptographic algorithm", "issueDescriptionEn": "A hash function is a one-way function that receives data of different lengths and maps it to random data of a fixed length. It is commonly used to store user passwords because it always produces the same output for a given input.\nBecause hash can be calculated very quickly, the hash functions, such as MD5 and SHA, may give the illusion of high performance. However they are vulnerable to random brute-force attacks. If you use the hash functions on simple data, they can be saved in the rainbow table, making it insecure. In addition, RC2, RC3, RC4, RC5, RC6, MD4, and DES are also known to be vulnerable.\nThere are many functions used to overcome the disadvantages of MD5 and SHA.\nIn Node.js, bcrypt is one of the functions that is commonly used with outstanding performance and easily replace them. The latest hash algorithms, such as Argon2, PBKDF2, and Scrypt, are also good alternatives. Make sure to add a salt to the hash in SHA-2 i.e. SHA-224, SHA-256, SHA-384, SHA-512.", "issueLineNumber": 176, "entireCode": "/**\n * Copyright 2020 \n\n * Licensed under the Apache License, Version 2.0 (the 'License');\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n\n * http://www.apache.org/licenses/LICENSE-2.0\n\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an 'AS IS' BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * @file User Class\n *\n * @author <>\n */\n\n'use strict';\n\nconst {config} = require('../config');\nconst md5 = require('md5');\n\nconst DB = require('./DB');\nconst Table = require('./Table');\n\nclass User {\n #table;\n #name;\n\n /**\n *\n * @param {string} name\n */\n constructor(name) {\n if (name !== 'grantall::jsdbadmin' && !User.exists(name)) {\n throw new Error(`User ${name} does not exist.`);\n }\n\n this.table = new DB('jsdb').table('users');\n this.name = name;\n }\n\n /**\n *\n * @return {Table}\n */\n get table() {\n return this.#table;\n }\n\n /**\n *\n * @param {Table} table\n */\n set table(table) {\n if (!(table instanceof Table)) {\n throw new TypeError(`table is not Table.`);\n }\n\n this.#table = table;\n }\n\n /**\n *\n * @return {string}\n */\n get name() {\n return this.#name;\n }\n\n /**\n *\n * @param {string} name\n */\n set name(name) {\n if (typeof name !== 'string') {\n throw new TypeError(`name is not string.`);\n }\n\n this.#name = name;\n }\n\n /**\n *\n * @param {string} name\n * @param {string} password\n * @return {boolean}\n */\n static auth(name, password) {\n if (name === 'grantall::jsdbadmin') {\n throw new Error('AUTHERR: Wrong password');\n }\n\n let users = new DB('jsdb').table('users').select(['password', 'valid', 'privileges'], {\n where: `\\`username\\` == '${name}'`,\n orderBy: [{column: 'username', mode: 'ASC'}]\n });\n\n if (users.length === 0 || !users[0].valid) {\n throw new Error(`AUTHERR: Invalid username: ${name}`);\n }\n\n return users[0].password === (password);\n }\n\n privileges() {\n if (this.name === 'grantall::jsdbadmin') {\n return {'*': 15};\n }\n\n let users = new DB('jsdb').table('users').select(['valid', 'privileges'], {\n where: `\\`username\\` == '${this.name}'`,\n orderBy: [{column: 'username', mode: 'ASC'}]\n });\n\n if (users.length === 0 || !users[0].valid) {\n throw new Error(`AUTHERR: Invalid username: ${this.name}`);\n }\n\n return users[0].privileges;\n }\n\n update(update = {username: null, password: null, privileges: null, valid: null}) {\n // grantall::jsdbadmin is not a real user, this is for avoid errors\n if (this.name === 'grantall::jsdbadmin') {\n throw new Error(`Invalid username: ${this.name}`);\n }\n\n let users = new DB('jsdb').table('users').select(['password', 'privileges'], {\n where: `\\`username\\` == '${this.name}'`,\n orderBy: [{column: 'username', mode: 'ASC'}]\n });\n\n if (users.length === 0) {\n throw new Error(`Invalid username: ${this.name}`);\n }\n\n // Do not allow renaming user jsdbadmin\n if (update.username && this.name === 'jsdbadmin') {\n throw new Error('User jsdbadmin cannot be renamed');\n }\n\n if (update.password) {\n update.password = (update.password);\n }\n\n if (update.privileges) {\n update.privileges = JSON.parse(update.privileges);\n\n for (let key in update.privileges) {\n if (update.privileges.hasOwnProperty(key)) {\n update.privileges[key] = parseInt(update.privileges[key], 2);\n }\n }\n\n update.privileges = JSON.stringify(update.privileges);\n }\n\n new DB('jsdb').table('users').update(update, {where: `\\`username\\` == '${this.name}'`});\n\n return true;\n }\n\n static create(name, password, privileges, valid = true) {\n if (name === 'grantall::jsdbadmin') {\n throw new Error('Invalid username');\n }\n\n if (User.exists(name)) {\n throw new Error(`User ${name} already exists`);\n }\n\n new DB('jsdb').table('users').insert(['DEFAULT', name, md5(`${password}`), valid, JSON.stringify(privileges)]);\n\n return new User(name);\n }\n\n static exists(name) {\n if (config.server.ignAuth && name === 'grantall::jsdbadmin') {\n return true;\n }\n\n const user = new DB('jsdb').table('users').select(['id', 'valid'], {where: `\\`username\\` == '${name}'`});\n\n if (user.length === 0) {\n return false;\n } else if (!user[0].valid) {\n throw new Error(`User ${name} is disabled`);\n }\n\n return true;\n }\n\n drop() {\n // grantall::jsdbadmin is not a real user, this is for avoid errors\n // Do not allow delete user jsdbadmin\n if (this.name === 'grantall::jsdbadmin' || this.name === 'jsdbadmin') {\n throw new Error(`Invalid username: ${this.name}`);\n }\n\n new DB('jsdb').table('users').delete({where: `\\`username\\` == '${this.name}'`});\n\n return true;\n }\n}\n\nmodule.exports = User;", "dangerousExampleEn": "1. var md5 = require('md5');\n2. \n3. console.log(md5('password'));\nLine 3: This is weak for the brute-force attack because it uses md5, a weak hash function.", "safeExampleEn": "1. var bcrypt = require('bcrypt');\n2. \n3. bcrypt.hash(\"password\", 13, function(err, hash) {\n4. console.log(hash);\n5. });\nLine 3: This is safe from the brute-force attack because bcrypt is used to create hash data.", "contexts": [{"lineNo": 176, "eventType": "sink", "messageKey": "jschk.FORBIDDEN.WEAK_ALGORITHM.JS.defect", "params": {"arg0": "md5"}}]}} {"id": "96b81112065e6012735d8f5ce4f3bc90f4bf113b5ce47998cf085d59287e202d", "license": {"spdx": ["MIT"], "repo": "bigeasy/packet", "path": "test/readme/readme.t.js", "repo_head_hexsha": "34b213ed75343e794330d21eadf960596027e25f", "stack_hexsha": "2aeacc3f1bc7e1b776d07677017a91e3ed92f8f5", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of weak cryptographic algorithm", "issueDescriptionEn": "A hash function is a one-way function that receives data of different lengths and maps it to random data of a fixed length. It is commonly used to store user passwords because it always produces the same output for a given input.\nBecause hash can be calculated very quickly, the hash functions, such as MD5 and SHA, may give the illusion of high performance. However they are vulnerable to random brute-force attacks. If you use the hash functions on simple data, they can be saved in the rainbow table, making it insecure. In addition, RC2, RC3, RC4, RC5, RC6, MD4, and DES are also known to be vulnerable.\nThere are many functions used to overcome the disadvantages of MD5 and SHA.\nIn Node.js, bcrypt is one of the functions that is commonly used with outstanding performance and easily replace them. The latest hash algorithms, such as Argon2, PBKDF2, and Scrypt, are also good alternatives. Make sure to add a salt to the hash in SHA-2 i.e. SHA-224, SHA-256, SHA-384, SHA-512.", "issueLineNumber": 1748, "entireCode": "// [![Actions Status](https://github.com/bigeasy/packet/workflows/Node%20CI/badge.svg)](https://github.com/bigeasy/packet/actions)\n// [![codecov](https://codecov.io/gh/bigeasy/packet/branch/master/graph/badge.svg)](https://codecov.io/gh/bigeasy/packet)\n// [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n//\n// Incremental binary parsers and serializers for Node.js.\n//\n// | What | Where |\n// | --- | --- |\n// | Discussion | https://github.com/bigeasy/packet/issues/1 |\n// | Documentation | https://bigeasy.github.io/packet |\n// | Source | https://github.com/bigeasy/packet |\n// | Issues | https://github.com/bigeasy/packet/issues |\n// | CI | https://travis-ci.org/bigeasy/packet |\n// | Coverage: | https://codecov.io/gh/bigeasy/packet |\n// | License: | MIT |\n//\n// Packet creates **pre-compiled**, **pure-JavaScript**, **binary parsers** and\n// **serializers** that are **incremental** through a packet definition pattern\n// language that is **declarative** and very **expressive**.\n//\n// Packet simplifies the construction and maintenance of libraries that convert\n// binary to JavaScript and back. The name Packet may make you think that it is\n// designed solely for binary network protocols, but it is also great for reading\n// and writing binary file formats.\n//\n// **Incremental** — Node packet creates incremental parsers and serializers\n// that are almost as fast as the parser you'd write by hand, but a easier to\n// define and maintain.\n//\n// **Declarative** — Packet defines a binary structure using a syntax-bashed\n// JavaScript definition langauge. A single definition is used to define both\n// parsers and serializers. If you have a protocol specification, or even just a C\n// header file with structures that define your binary data, you can probably\n// translate that directly into a Packet definition.\n//\n// **Expressive** — The pattern language can express\n//\n// * signed and unsigned integers,\n// * endianess of singed and unsigned integers,\n// * floats and doubles,\n// * fixed length arrays of characters or numbers,\n// * length encoded strings of characters or numbers,\n// * zero terminated strings of characters or numbers,\n// * said strings terminated any fixed length terminator you specify,\n// * padding of said strings with any padding value you specify,\n// * signed and unsigned integers extracted from bit packed integers,\n// * string to integer value mappings,\n// * if/then/else conditionals,\n// * switch conditions,\n// * character encodings,\n// * custom transformations,\n// * assertions,\n// * and pipelines of custom transformations and assertions.\n//\n// Packet installs from NPM.\n\n// ## Living `README.md`\n//\n// This `README.md` is also a unit test using the\n// [Proof](https://github.com/bigeasy/proof) unit test framework. We'll use the\n// Proof `okay` function to assert out statements in the readme. A Proof unit test\n// generally looks like this.\n\nrequire('proof')(115, okay => {\n // Be sure to run the unit test with the `--allow-natives-syntax` switch. The\n // `--allow-natives-syntax` switch allows us to test that when we parse we are\n // creating objects that have JavaScript \"fast properties.\"\n //\n // ## Parsers and Serializers\n //\n // **TODO** Here you need your incremental and whole parser interface with a simple\n // example. Would be an over view. In the next section we get into the weeds.\n //\n // ## Packet Definition Language\n //\n // To test our examples below we are going to use the following function.\n\n const fs = require('fs')\n const path = require('path')\n\n const packetize = require('../../packetize')\n const SyncParser = require('../../sync/parser')\n const SyncSerializer = require('../../sync/serializer')\n\n // Generate a packet parser and serializer mechnaics module.\n\n // Please ignore all the synchronous file operations. They are for testing\n // only. You will not generate packet parsers at runtime. You will use the\n // `packetizer` executable to generate your packet parser and serializer\n // mechanics modules and ship them.\n\n //\n function compile (name, definition, options) {\n const source = packetize(definition, options)\n const file = path.resolve(__dirname, '..', 'readme', name + '.js')\n fs.writeFileSync(file, source)\n return file\n }\n\n // Load mechanics and run a synchronous serialize and parse.\n\n // This looks more like production code, except for the part where you call\n // our for-the-sake-of-testing runtime compile.\n\n //\n function test (name, definition, object, expected, options = {}) {\n const moduleName = compile(name, definition, options)\n\n const mechanics = require(moduleName)\n\n const serializer = new SyncSerializer(mechanics)\n const buffer = serializer.serialize('object', object)\n\n okay(buffer.toJSON().data, expected, `${name} correctly serialized`)\n\n const parser = new SyncParser(mechanics)\n const actual = parser.parse('object', buffer)\n\n okay(actual, object, `${name} correctly parsed`)\n }\n\n // ### Whole Integers\n //\n // Integers are specified as multiples of 8 bits. For integers less than 48 bits\n // you can define the integer field as a JavaScript `typeof === 'number'`. If the\n // integer is larger than 48 bits you should define the field as JavaScript\n // `BigInt`.\n //\n // **Mnemonic**: A count of bits to serialize or parse defined as a JavaScript\n // `'number'` or `BigInt` since that's the type it will produce. We use a count of\n // bits as opposed to a count of bytes so that our code looks consistent when when\n // we define bit packed integers which need to be defined in bits and not bytes.\n //\n // In the following definition `value` is a 16-bit `'number'` with valid integer\n // values from 0 to 65,535. Serializes objects with `'number'` fields must provide\n // a `'number'` type value and the number must be in range. No type or range\n // checking is performed.\n\n const definition = {\n object: {\n value: 16\n }\n }\n\n const object = {\n value: 0xabcd\n }\n\n test('whole-integer', definition, object, [ 0xab, 0xcd ])\n\n // Integers smaller than 48 bits _should_ be defined using a `'number'` to specify\n // the count of bits. Integers larger than 48 bits _must_ be defined as `BigInt`.\n //\n // In the following definition `value` is a 64-bit `BigInt` with a valid integer\n // values from 0 to 18,446,744,073,709,551,616. Serializes objects with `BigInt`\n // fields must provide a `BigInt` type value and the number must be in range. No\n // type or range checking is performed.\n //\n // **Mnemonic**: The `n` suffix is the same suffix used to indicate a `BigInt`\n // literal in JavaScript.\n\n {\n const definition = {\n object: {\n value: 64n\n }\n }\n\n const object = {\n value: 0xfedcba9876543210n\n }\n\n test('whole-integer-64', definition, object, [\n 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10\n ])\n }\n\n // ### Negative Integers\n //\n // Integers with negative values are generally represented as two's compliment\n // integers on most machines. To parse and serialize as two's compliment you\n // precede the bit length of an integer field with a `-` negative symbol.\n //\n // In the following definition `value` is a two's compliment 16-bit integer with\n // valid values from -32768 to 32767. Two's compliment is a binary representation\n // of negative numbers.\n //\n // **Mnemonic**: Negative symbol to indicate a potentially negative value.\n\n {\n const definition = {\n object: {\n value: -16\n }\n }\n\n const object = {\n value: -1\n }\n\n test('negative-integer', definition, object, [ 0xff, 0xff ])\n }\n\n // As with whole integers, you _must_ define an integer larger than 32-bits as a\n // `BitInt`.\n //\n // In the following definition `value` is a two's compliment 16-bit integer with\n // valid values from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.\n\n {\n const definition = {\n object: {\n value: -64n\n }\n }\n\n const object = {\n value: -1n\n }\n\n test('negative-integer-64', definition, object, [\n 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff\n ])\n }\n\n // ### Endianness\n //\n // By default, all numbers are written out big-endian, where the bytes are written\n // from the most significant to the least significant. The same order in which\n // you'd specify the value as a hexadecimal literal in JavaScript.\n //\n // Little-endian means that the bytes are serialized from the least significant\n // byte to the most significant byte. Note that this is the order of _bytes_ and\n // not _bits_. This would be the case if you wrote an integer out directly to a\n // file from a C program on an Intel machine.\n //\n // To parse and serialize an integer as little-endian you precede the bit length of\n // an integer field with a `~` tilde.\n //\n // In the following definition `value` is a 16-bit `number` field with valid\n // integer values from 0 to 65,535. A value of `0xabcd` would be serialized in\n // little-endian order as `[ 0xcd, 0xab ]`.\n //\n // **Mnemonic**: The tilde is curvy and we're mixing things up, turning them\n // around, vice-versa like.\n\n {\n const definition = {\n object: {\n value: ~16\n }\n }\n\n const object = {\n value: 0xabcd\n }\n\n test('little-endian', definition, object, [ 0xcd, 0xab ])\n }\n\n // If you want a little-endian negative number combine both `-` and `~`. You can\n // combine the `-` and `~` as `-~` and `~-`.\n //\n // In the following definition both `first` and `second` are 16-bit `number` fields\n // with valid integer values from -32768 to 32767. A value of `-0x2` would be\n // converted to the twos compliment representation 0xfffe and serialized in\n // little-endian as `[ 0xfe, 0xff ]`.\n\n {\n const definition = {\n object: {\n first: ~-16,\n second: -~16\n }\n }\n\n const object = {\n first: -2,\n second: -2\n }\n\n test('little-endian-twos-compliment', definition, object, [\n 0xfe, 0xff, 0xfe, 0xff\n ])\n }\n\n // Just as with the default big-endian integer fields, little-endian integer fields\n // greater than 32-bits must be specified as `BigInt` fields using a `'bigint'`\n // literal.\n\n {\n const definition = {\n object: {\n value: ~64n,\n }\n }\n\n const object = {\n value: 0xfedcba9876543210n\n }\n\n test('little-endian-64', definition, object, [\n 0x10, 0x32, 0x54, 0x76, 0x98, 0xba, 0xdc, 0xfe\n ])\n }\n\n // Similarly, for little-endian signed number fields greater than 32-bits you\n // combine the `-` and `~` with a `BigInt` literal. You can combine the `-` and `~`\n // as `-~` and `~-`.\n\n {\n const definition = {\n object: {\n first: ~-64n,\n second: -~64n\n }\n }\n\n const object = {\n first: -2n,\n second: -2n\n }\n\n test('little-endian-twos-compliment-64', definition, object, [\n 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, // first\n 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff // second\n ])\n }\n\n // ### Nested Structures\n //\n // You can nest structures arbitrarily. The nesting of structures does not effect\n // the serialization or parsing, it will still be a series bytes in the stream, but\n // it may help the structure your programs group values in a meaningful way.\n\n {\n const definition = {\n object: {\n header: {\n type: 8,\n length: 16\n },\n options: {\n encrypted: 8,\n checksum: 32\n }\n }\n }\n\n const object = {\n header: {\n type: 1,\n length: 64\n },\n options: {\n encrypted: 0,\n checksum: 0xaaaaaaaa\n }\n }\n\n test('nested-structures', definition, object, [\n 0x01, // header.type\n 0x00, 0x40, // header.length\n 0x00, // options.encrypted\n 0xaa, 0xaa, 0xaa, 0xaa // options.checksum\n ])\n }\n\n // You can define a nested structure and then elide it by defining the structure\n // with a name that begins with a `_`. This is silly so don't do it. It is\n // available merely to be consistent with packet integers, accumulators and limits.\n //\n // **TODO** Short example.\n //\n // ### Packed Integers\n //\n // Packed integers are expressed as nested structures grouped in an `Array`\n // followed by an integer definition of the packed integer size. The byte lengths\n // in the packed integer must sum to the size of the packed integer.\n //\n // Packed integer fields are always big-endian and cannot be made little endian.\n // Packed integer fields can be made two's compliment by preceding the field bit\n // length with a `-` negative symbol just like whole integers.\n //\n // A packed 32-bit integer with a single two's compliment (potentially negative)\n // value named `volume`.\n //\n // The bit length values of the packed values sum to 32. Note that we consider\n // `volume` to be 10 bits and not -10 bits in this summation of packed field\n // values. The `-` is used to indicate a two's compliment integer field.\n\n {\n const definition = {\n object: {\n header: [{\n type: 7,\n encrypted: 1,\n volume: -10,\n length: 14\n }, 32 ]\n }\n }\n\n const object = {\n header: {\n type: 3,\n encrypted: 1,\n volume: -1,\n length: 1024\n }\n }\n\n test('packed-integer', definition, object, [\n 0x7, // type and encrypted packed into ne byte\n 0xff, // eight bytes of volume\n 0xc4, // two types of volume and top of length\n 0x0 // rest of length\n ])\n }\n\n // The packed integer will be serialized as big-endian by default. You can specify\n // that the packed integer is serialized as little-endian by proceeding the bit\n // length with a `~` tilde.\n\n {\n const definition = {\n object: {\n header: [{\n type: 7,\n encrypted: 1,\n volume: -10,\n length: 14\n }, ~32 ]\n }\n }\n\n const object = {\n header: {\n type: 3,\n encrypted: 1,\n volume: -1,\n length: 1024\n }\n }\n\n test('packed-integer-little-endian', definition, object, [\n 0x0, // rest of length\n 0xc4, // two types of volume and top of length\n 0xff, // eight bytes of volume\n 0x7 // type and encrypted packed into ne byte\n ])\n }\n\n // You many not want the nested structure of the packed header to appear in your\n // parsed object. You can elide the nested structure by giving it a name that\n // begins with an `_`.\n //\n // **TODO** Example.\n //\n // Elide only works for packet integers, accumulators, limits and structures. If\n // you name a field of any other type it will be defined with the underscore.\n //\n // **TODO** Example.\n //\n // ### Literals\n //\n // Literals are bytes written on serialization that are constant and not based on a\n // value in the serialized structure.\n //\n // You define a constant with an array that contains a `String` that describes the\n // constant value in hexadecimal digits. There should be two hexadecimal digits for\n // every byte. The length of the field is determined by the number of bytes\n // necessary to hold the value.\n //\n // **Mnemonic**: A string literal reminds us this is literal and stands out because\n // it is not numeric. Hexadecimal helps distinguish these constant values from\n // field sizes and other aspects of the definition language expressed with numbers.\n\n {\n const definition = {\n object: {\n constant: [ 'fc' ],\n value: 16\n }\n }\n\n const object = {\n value: 0xabcd\n }\n\n test('constant', definition, object, [\n 0xfc, 0xab, 0xcd\n ])\n }\n\n // Generated parsers skip the constant bytes and do not validate the parsed value.\n // If you want to perform validation you can define the field as an integer field\n // and inspect the parsed field value. This means you will also have to\n // consistently set the serialized field value on your own.\n //\n // A literal is ignored on serialization if it exists. It is not set in the\n // generated structure on parsing. In our example the `contsant` property of the\n // object is not generated on parse.\n //\n // **TODO** How about an explicit example that doesn't require as much exposition\n // as our `test` definition.\n //\n // Not much point in naming a literal, is there? The literal it will not be read\n // from the serialized object nor will the named literal property be set in a\n // parsed parsed object. What if you have multiple literals? Now you have to have\n // `constant1` and `constant2`. It starts to look ugly as follows.\n\n {\n const definition = {\n object: {\n constant1: [ 'fc' ],\n key: 16,\n constant2: [ 'ab' ],\n value: 16\n }\n }\n\n const object = {\n key: 1,\n value: 0xabcd\n }\n\n test('constants', definition, object, [\n 0xfc, 0x0, 01,\n 0xab, 0xab, 0xcd\n ])\n }\n\n // You can forgo naming a literal by defining it as padding before or after a\n // field.\n //\n // To prepend a literal to a field definition in an array where the literal\n // definition is the first element and field definition is the second. The literal\n // will be written before writing the field value and skipped when parsing the\n // field value.\n\n {\n const definition = {\n object: {\n key: [[ 'fc' ], 16 ],\n value: [[ 'ab' ], 16 ]\n }\n }\n\n const object = {\n key: 1,\n value: 0xabcd\n }\n\n test('unnamed-literals', definition, object, [\n 0xfc, 0x0, 01,\n 0xab, 0xab, 0xcd\n ])\n }\n\n // You can specify an unnamed literal that follows a field. Enclose the field\n // definition in an array with the field definition as the first element and the\n // literal definition as the second element.\n\n {\n const definition = {\n object: {\n value: [ 16, [ 'ea' ] ],\n }\n }\n\n const object = {\n value: 0xabcd\n }\n\n test('unnamed-literal-after', definition, object, [\n 0xab, 0xcd, 0xea\n ])\n }\n\n // You can specify an unnamed literal both before and after a field. Enclose the\n // field definition in an array and define preceding literal as the first element\n // and following literal as the last element.\n //\n // The example above can be defined using literals around the `key` property alone.\n\n {\n const definition = {\n object: {\n key: [[ 'fc' ], 16, [ 'ab' ] ],\n value: 16\n }\n }\n\n const object = {\n key: 1,\n value: 0xabcd\n }\n\n test('unnamed-literals-before-and-after', definition, object, [\n 0xfc, 0x0, 01,\n 0xab, 0xab, 0xcd\n ])\n }\n\n // You can define a literal that repeats its value. The constant value is defined\n // using an array that contains a `String` with the literal value as the first\n // element and the number of times to repeat the value as the second element.\n //\n // **Mnemonic**: The repeat count follows the hexadecimal definition, its relation\n // to the definition is expressed by its containment in an array.\n\n {\n const definition = {\n object: {\n constant: [ 'beaf', 3 ],\n value: 16\n }\n }\n\n const object = { value: 0xabcd }\n\n test('literal-repeat', definition, object, [\n 0xbe, 0xaf, 0xbe, 0xaf, 0xbe, 0xaf,\n 0xab, 0xcd\n ])\n }\n\n // You can express repeated literals as unnamed literals by prepending or appending\n // them to a field definition.\n\n {\n const definition = {\n object: {\n value: [[ 'beaf', 3 ], 16 ]\n }\n }\n\n const object = { value: 0xabcd }\n\n test('unamed-literal-repeat', definition, object, [\n 0xbe, 0xaf, 0xbe, 0xaf, 0xbe, 0xaf,\n 0xab, 0xcd\n ])\n }\n\n // Note that a literal definition without a repeat count is the same as a literal\n // definition with a repeat count of `1`.\n\n {\n const definition = {\n object: {\n explicit: [[ 'beaf', 1 ], 16 ],\n implicit: [[ 'beaf' ], 16 ]\n }\n }\n\n const object = { explicit: 0xabcd, implicit: 0xabcd }\n\n test('unamed-literal-repeat-once', definition, object, [\n 0xbe, 0xaf, 0xab, 0xcd,\n 0xbe, 0xaf, 0xab, 0xcd\n ])\n }\n\n // Little endian serialization of literals seems like an unlikely use case. One\n // would imagine at a specification would specify the bytes in network byte order.\n // Often times filler bytes are a repeat of a single byte so endianness doesn't\n // matter.\n //\n // If you want little-endian serialization of a literal value you could simply\n // reverse the bits yourself.\n //\n // Here we write `0xbeaf` little-endian by explicitly flipping `0xbe` and `0xaf`.\n\n {\n const definition = {\n object: {\n value: [[ 'afbe' ], 16 ]\n }\n }\n\n const object = { value: 0xabcd }\n\n test('unamed-literal-little-endian-explicit', definition, object, [\n 0xaf, 0xbe,\n 0xab, 0xcd\n ])\n }\n\n // Simple enough, however...\n //\n // If specify a repeat count prepended by a `~` the pattern will be written\n // little-endian.\n //\n // **Mnemonic**: Use use a tilde `~` because it's squiggly and we're swirling the\n // bytes around vice-versa. Same mnemonic for little-endian integer fields.\n\n {\n const definition = {\n object: {\n value: [[ 'beaf', ~1 ], 16 ]\n }\n }\n\n const object = { value: 0xabcd }\n\n test('unamed-literal-little-endian', definition, object, [\n 0xaf, 0xbe,\n 0xab, 0xcd\n ])\n }\n\n // You can repeat the little-endian serialization more than once.\n\n {\n const definition = {\n object: {\n value: [[ 'beaf', ~3 ], 16 ]\n }\n }\n\n const object = { value: 0xabcd }\n\n test('unamed-literal-little-endian-repeat', definition, object, [\n 0xaf, 0xbe, 0xaf, 0xbe, 0xaf, 0xbe,\n 0xab, 0xcd\n ])\n }\n\n // Unnamed little-endian literals can be appended or prepended. Any unnamed literal\n // definition can be appended, prepended or both.\n //\n // ### Length-Encoded Arrays\n //\n // A common pattern in serialization formats is a series of repeated values\n // preceded by a count of those values.\n //\n // **Mnemonic**: We enclose the definition in an array. The first element is an\n // integer field definition for the length. It's scalar appearance indicates that\n // it does not repeat. The repeated value is enclosed in an array indicating that\n // it will be the value that repeats. The ordering of the scalar followed by the\n // array mirrors the binary representation of a length/count followed by repeated\n // values.\n\n {\n const definition = {\n object: {\n array: [ 16, [ 8 ] ]\n }\n }\n\n const object = {\n array: [ 0xaa, 0xbb, 0xcc, 0xdd ]\n }\n\n test('length-encoded', definition, object, [\n 0x0, 0x4, 0xaa, 0xbb, 0xcc, 0xdd\n ])\n }\n\n // The repeated value can be of any type including structures.\n\n {\n const definition = {\n object: {\n array: [ 16, [{ key: 16, value: 16 }] ]\n }\n }\n\n const object = {\n array: [{ key: 0xaa, value: 0xbb }, { key: 0xcc, value: 0xdd }]\n }\n\n test('length-encoded-structures', definition, object, [\n 0x0, 0x2, // length encoding\n 0x0, 0xaa, 0x0, 0xbb, // first structure\n 0x0, 0xcc, 0x0, 0xdd // second structure\n ])\n }\n\n // You can even nest length-encoded arrays inside length-encoded arrays.\n\n {\n const definition = {\n object: {\n array: [ 16, [[ 16, [ 8 ]]] ]\n }\n }\n\n const object = {\n array: [[ 0xaa, 0xbb ], [ 0xcc, 0xdd ]]\n }\n\n test('length-encoded-nested', definition, object, [\n 0x0, 0x2, // length encoding\n 0x0, 0x2, 0xaa, 0xbb, // first array length encoding and values\n 0x0, 0x2, 0xcc, 0xdd // second array length encoding and values\n ])\n }\n\n // Because pure binary data is a special case, instead of an array of `8` bit\n // bites, you can specify a length encoded binary data as a `Buffer`.\n\n {\n const definition = {\n object: {\n array: [ 16, [ Buffer ] ]\n }\n }\n\n const object = {\n array: Buffer.from([ 0xaa, 0xbb, 0xcc, 0xdd ])\n }\n\n test('length-encoded-buffer', definition, object, [\n 0x0, 0x4, 0xaa, 0xbb, 0xcc, 0xdd\n ])\n }\n\n // ### Inline Transforms and Assertions\n //\n // Inline transforms are specified by wrapping a field definition in an array with\n // a pre-serialization function before or a post-parsing function after it or both.\n // The pre-serialization function and post-parsing function must be enclosed in an\n // array.\n //\n // A pre-serialization transformation function takes the value from the JavaScript\n // object and returns the transformed that is then written to the stream. The\n // post-parsing transformation function takes a value extracted from the stream and\n // returns the transformed value that is assigned to the JavaScript object.\n //\n // The following transform will convert a hexadecimal string to an integer on\n // serialization and back to a hexadecimal string on parse.\n //\n // **Mnemonic**: A function is obviously a function, it does something to in the\n // midst of parsing. We used functions elsewhere in the language, so we enclose\n // them in arrays, The array brackets act as parenthesis, these are parenthetical\n // user actions on the stream.\n\n {\n const definition = {\n object: {\n value: [[ $_ => parseInt($_, 16) ], 32, [ $_ => $_.toString(16) ]]\n }\n }\n\n const object = {\n value: '89abcdef'\n }\n\n test('transform-basic', definition, object, [\n 0x89, 0xab, 0xcd, 0xef\n ])\n }\n\n // Whoa, what's with the parameter names pal? `$_` violates everything I was ever\n // taught about naming variables. How would you even pronounce that?\n //\n // Well, once upon a time I wrote me a lot of Perl. In Perl this variable is called\n // \"dollar under.\" It is the default variable for an array value when you loop\n // through an array with `foreach`. I miss those days, so I thought I revive them.\n // You can name positional arguments anything you like, but I'll be using these\n // names to get you used to them, because they're available as named arguments as\n // well.\n //\n // You can also use named arguments via object deconstruction. When you do, you\n // must specify names that are in the current namespace. The namespace will contain\n // the object properties in the current path.\n\n {\n const definition = {\n object: {\n value: [[ ({ value }) => parseInt(value, 16) ], 32, [ ({ value }) => value.toString(16) ]]\n }\n }\n\n const object = {\n value: '89abcdef'\n }\n\n test('transform-by-name', definition, object, [\n 0x89, 0xab, 0xcd, 0xef\n ])\n }\n\n // You can also refer to the current variable using the Perl-esque \"dollar under\"\n // variable. Perl-esque variables can make your code more concise. If used\n // consistently it will still be human readable.\n\n {\n const definition = {\n object: {\n value: [[ ({ $_ }) => parseInt($_, 16) ], 32, [ ({ $_ }) => $_.toString(16) ]]\n }\n }\n\n const object = {\n value: '89abcdef'\n }\n\n test('transform-dollar-under', definition, object, [\n 0x89, 0xab, 0xcd, 0xef\n ])\n }\n\n // There are two Perl-esque variable names `$_` for the immediate property value,\n // and `$` for the root object. Any other system provided names such as `$i`,\n // `$buffer`, `$start` and `$end` will begin with a `$` do distinguish them from\n // user specified names and to avoid namespace collisions.\n //\n // **Mnemonic**: Borrowed from Perl `foreach` loop, `$_` is the immediate property\n // value, useful for its brevity. `$` is the root variable, the shortest special\n // variable because if you're starting from the root, you have a path ahead of you.\n //\n // A transform or assertion is always defined with an array with three elements. If\n // you only want to define a pre-serialization action, the last element will be an\n // empty array. If you only want to define a post-parsing action, the first element\n // will be an empty array.\n //\n // In the following example we do not want to perform a post-parsing action, so we\n // leave the post-parsing array empty, but we do not neglect to add it.\n\n {\n const definition = {\n object: {\n value: [[ $_ => typeof $_ == 'string' ? parseInt($_, 16) : $_ ], 32, []]\n }\n }\n\n const moduleName = compile('transform-pre-only', definition)\n const mechanics = require(moduleName)\n\n {\n const buffer = new SyncSerializer(mechanics).serialize('object', { value: '89abcdef' })\n const object = new SyncParser(mechanics).parse('object', buffer)\n okay(object, { value: 0x89abcdef }, 'transform-pre-only-convert')\n }\n\n {\n const buffer = new SyncSerializer(mechanics).serialize('object', { value: 0x89abcdef })\n const object = new SyncParser(mechanics).parse('object', buffer)\n okay(object, { value: 0x89abcdef }, 'transform-pre-only-no-convert')\n }\n }\n\n // Named arguments have limitations. We're using a simple regex based parser to\n // extract the arguments from the function source, not a complete JavaScript\n // parser. We are able to parse object destructuring, array destructuring, and\n // default argument values of numbers, single quoted strings and double quoted\n // strings.\n //\n // Do not use regular expressions, interpolated strings or function calls, in your\n // default argument assignments. You can use any valid JavaScript in your function\n // bodies.\n //\n // In the following definition we've added an unused named variable that is default\n // assigned a value extracted from a literal string by a regular expression. The\n // right curly brace in the literal string won't confuse our simple argument\n // parser, but the right curly brace in the regular expression will.\n\n {\n const definition = {\n object: {\n value: [[\n ({ $_, packet: { extra = /^([}])/.exec(\"}\")[1] } }) => parseInt($_, 16)\n ], 32, [\n ({ $_ }) => $_.toString(16)\n ]]\n }\n }\n\n const _definition = {\n object: {\n value: [[ $_ => typeof $_ == 'string' ? parseInt($_, 16) : $_ ], 32, []]\n }\n }\n\n try {\n packetize(definition)\n } catch (error) {\n okay(error instanceof SyntaxError, 'unable to parse regex')\n }\n }\n\n // As you can see it's an unlikely use case. Basically, if you find yourself\n // writing logic in your named arguments, stop and place it in a function in a\n // module and invoke that module function from the inline function.\n //\n // We'll continue to use `$_` and `$` in positional argument examples so we can all\n // get used to them.\n //\n // The first argument to a transformation function with positional arguments is the\n // transformed value, the second argument is the root object being transformed.\n //\n // The following WebSockets inspired example xors a value with a `mask` property in\n // the packet.\n\n {\n const definition = {\n object: {\n mask: 16,\n value: [[ ($_, $) => $_ ^ $.mask ], 16, [ ($_, $) => $_ ^ $.mask ]]\n }\n }\n\n const object = {\n mask: 0xaaaa,\n value: 0xabcd\n }\n\n test('transform-mask-positional', definition, object, [\n 0xaa, 0xaa, 0x1, 0x67\n ])\n }\n\n // This can be expressed using named arguments. Note how we can order the arguments\n // any way we like.\n\n {\n const definition = {\n object: {\n mask: 16,\n value: [[ ({ $, $_ }) => $_ ^ $.mask ], 16, [ ({ $_, $ }) => $_ ^ $.mask ]]\n }\n }\n\n const object = {\n mask: 0xaaaa,\n value: 0xabcd\n }\n\n test('transform-mask-named', definition, object, [\n 0xaa, 0xaa, 0x1, 0x67\n ])\n }\n\n // You can also name the names of the object properties in the current path. Again,\n // note that the order of names does not matter with named arguments.\n\n {\n const definition = {\n object: {\n mask: 16,\n value: [[\n ({ object, value }) => value ^ object.mask\n ], 16, [\n ({ value, object }) => value ^ object.mask\n ]]\n }\n }\n\n const object = {\n mask: 0xaaaa,\n value: 0xabcd\n }\n\n test('transform-mask-long-named', definition, object, [\n 0xaa, 0xaa, 0x1, 0x67\n ])\n }\n\n // (Not to self: Seems like it might also be useful to be able to reference the\n // current object in a loop, which could be `$0` for the current object, `$1` for a\n // parent. This would be simpler than passing in the indices, but that would be\n // simple enough, just give them the already existing `$i`. Heh, no make them\n // suffer.)\n //\n // The third argument passed to a transformation function is an array of indices\n // indicating the index of each array in the path to the object. **TODO** Move\n // fixed arrays above.\n\n {\n const definition = {\n object: {\n array: [ 16, [{\n mask: 16,\n value: [[\n ($_, $, $i) => $_ ^ $.array[$i[0]].mask\n ], 16, [\n ($_, $, $i) => $_ ^ $.array[$i[0]].mask\n ]]\n }]]\n }\n }\n\n const object = {\n array: [{\n mask: 0xaaaa, value: 0xabcd\n }, {\n mask: 0xffff, value: 0x1234\n }]\n }\n\n test('transform-mask-array-positional', definition, object, [\n 0x0, 0x2, // length encoded count of elements\n 0xaa, 0xaa, 0x1, 0x67, // first element\n 0xff, 0xff, 0xed, 0xcb // second element\n ])\n }\n\n // We can use named arguments as well.\n\n {\n const definition = {\n object: {\n array: [ 16, [{\n mask: 16,\n value: [[\n ({ $_, $, $i }) => $_ ^ $.array[$i[0]].mask\n ], 16, [\n ({ $_, $, $i }) => $_ ^ $.array[$i[0]].mask\n ]]\n }]]\n }\n }\n\n const object = {\n array: [{\n mask: 0xaaaa, value: 0xabcd\n }, {\n mask: 0xffff, value: 0x1234\n }]\n }\n\n test('transform-mask-array-named', definition, object, [\n 0x0, 0x2, // length encoded count of elements\n 0xaa, 0xaa, 0x1, 0x67, // first element\n 0xff, 0xff, 0xed, 0xcb // second element\n ])\n }\n\n // We can also use the names of the object properties in the current path. The `$i`\n // array variable of is a special system property and it therefore retains its\n // dollar sign prepended name.\n\n {\n const definition = {\n object: {\n array: [ 16, [{\n mask: 16,\n value: [[\n ({ value, object, $i }) => value ^ object.array[$i[0]].mask\n ], 16, [\n ({ value, object, $i }) => value ^ object.array[$i[0]].mask\n ]]\n }]]\n }\n }\n\n const object = {\n array: [{\n mask: 0xaaaa, value: 0xabcd\n }, {\n mask: 0xffff, value: 0x1234\n }]\n }\n\n test('transform-mask-array-full-named', definition, object, [\n 0x0, 0x2, // length encoded count of elements\n 0xaa, 0xaa, 0x1, 0x67, // first element\n 0xff, 0xff, 0xed, 0xcb // second element\n ])\n }\n\n // If your pre-serialization function and post-parsing function are the same you\n // can specify it once and use it for both serialization and parsing by surrounding\n // it with an additional array.\n\n {\n const definition = {\n object: {\n mask: 16,\n value: [[[ ($_, $) => $_ ^ $.mask ]], 16 ]\n }\n }\n\n const object = {\n mask: 0xaaaa, value: 0xabcd\n }\n\n test('transform-mask-same', definition, object, [\n 0xaa, 0xaa, 0x1, 0x67\n ])\n }\n\n // Note that the above functions can also be defined using `function` syntax. Arrow\n // functions are generally more concise, however.\n\n {\n const definition = {\n object: {\n mask: 16,\n value: [[[ function ({ value, object }) {\n return value ^ object.mask\n } ]], 16 ]\n }\n }\n\n const object = {\n mask: 0xaaaa, value: 0xabcd\n }\n\n test('transform-mask-function-syntax', definition, object, [\n 0xaa, 0xaa, 0x1, 0x67\n ])\n }\n\n // ### Fixed Length Arrays\n //\n // Fixed length arrays are arrays of a fixed length. They are specified by an array\n // containing the numeric length of the array.\n //\n // **Mnemonic**: Like a length encoded definition the element definition is placed\n // inside an array because it is the array element. Like a length encoded\n // definition the length of the array precedes the element definition. It is the\n // length of the array enclosed in an array like C array declaration.\n\n {\n const definition = {\n object: {\n fixed: [[ 2 ], [ 16 ]]\n }\n }\n\n const object = {\n fixed: [ 0xabcd, 0xdcba ]\n }\n\n test('fixed', definition, object, [\n 0xab, 0xcd, 0xdc, 0xba\n ])\n }\n\n // Calculated length arrays are fixed length arrays where the fixed length is\n // specified by function. The length is, therefore, not fixed at all. It is\n // calculated.\n //\n // In the following example we have a length encoding that is in a header and there\n // is a field between the length encoding and the array so we can't use a\n // length-encoded array definition. We use a calculated length that references the\n // header's length field.\n //\n // **Mnemonic** Same as fixed length arrays replacing the fixed length with a\n // function indicating that the function will calculate the length.\n\n {\n const definition = {\n object: {\n header: {\n length: 16,\n type: 8\n },\n array: [[ $ => $.header.length ], [ 16 ]]\n }\n }\n\n const object = {\n header: {\n length: 2,\n type: 1\n },\n array: [ 0xabcd, 0xdcba ]\n }\n\n test('fixed-calculated', definition, object, [\n 0x0, 0x2, // header.length\n 0x1, // header.type\n 0xab, 0xcd, 0xdc, 0xba\n ])\n }\n\n // ### Requiring Modules\n //\n // The functions in our packet parser may depend on external libraries. We can\n\n {\n const definition = {\n object: {\n value: [[ value => ip.toLong(value) ], 32, [ value => ip.fromLong(value) ]]\n }\n }\n\n const source = packetize(definition, { require: { ip: 'ip' } })\n\n const moduleName = path.resolve(__dirname, 'require.js')\n fs.writeFileSync(moduleName, source)\n\n const mechanics = require(moduleName)\n\n const object = { value: '127.0.0.1' }\n\n const buffer = new SyncSerializer(mechanics).serialize('object', object)\n\n okay(buffer.toJSON().data, [\n 127, 0, 0, 1\n ], 'require serialized')\n\n const parsed = new SyncParser(mechanics).parse('object', buffer)\n okay(parsed, object, 'require parsed')\n }\n\n // ### Assertions\n //\n // **TODO** Needs examples of failed assertions.\n //\n // We can also perform inline assertions. You specify an assertion the same way you\n // specify a transformation. You wrap your definition in an array.\n // A pre-serialization assertion is a function within an array in the element\n // before the definition. A post-parsing assertions is a function within an array\n // in the element after the definition.\n //\n // When performing inline assertions, we are not transforming a value, we're simply\n // checking it's validity and raising an exception if a value is invalid. You could\n // use a transformation to do this, but you would end up returning the value as is.\n //\n // With an assertion function the return value is ignored. It is not used as the\n // serialization or assignment value.\n //\n // To declare an assertion function you assign a default value of `0` or `null` to\n // the immediate property argument.\n //\n // In the following definition we use a `0` default value for the immediate\n // property argument which indicates that the value and should not be used for\n // serialization for the pre-serialization function nor assignment for the\n // post-parsing function.\n\n {\n const definition = {\n object: {\n value: [[\n ($_ = 0) => assert($_ < 1000, 'excedes max value')\n ], 16, [\n ($_ = 0) => assert($_ < 1000, 'excedes max value')\n ]]\n }\n }\n const object = {\n value: 1\n }\n test('assertion', definition, object, [\n 0x0, 0x1\n ], { require: { assert: 'assert' } })\n }\n\n // (I assume I'll implement this in this way:) The exception will propagate to the\n // API caller so that you can catch it in your code and cancel the serialization or\n // parse. (However, if I do wrap the assertion in a try/catch and rethrow it\n // somehow, then the following example is moot.\n //\n // If you where to use a transform, you would have to return the value and your\n // definition would be more verbose.\n\n {\n const definition = {\n object: {\n value: [[\n $_ => {\n assert($_ < 1000, 'excedes max value')\n return $_\n }\n ], 16, [\n $_ => {\n assert($_ < 1000, 'execdes max value')\n return $_\n }\n ]]\n }\n }\n const object = {\n value: 1\n }\n test('assertion-not-assertion', definition, object, [\n 0x0, 0x1\n ], { require: { assert: 'assert' } })\n }\n\n // You can use the name function for both pre-serialization and post-parsing by\n // surrounding the function in an additional array.\n\n {\n const definition = {\n object: {\n value: [[[ ($_ = 0) => assert($_ < 1000, 'excedes max value') ]], 16 ]\n }\n }\n const object = {\n value: 1\n }\n test('assertion-mirrored', definition, object, [\n 0x0, 0x1\n ], { require: { assert: 'assert' } })\n }\n\n // You can use named arguments to declare an assertion function.\n\n {\n const definition = {\n object: {\n value: [[[ ({ $_ = 0 }) => assert($_ < 1000, 'excedes max value') ]], 16 ]\n }\n }\n const object = {\n value: 1\n }\n test('assertion-named', definition, object, [\n 0x0, 0x1\n ], { require: { assert: 'assert' } })\n }\n\n // ### Assertion and Transformation Arguments\n //\n // You can pass arguments to assertions and transforms. Any value in the array that\n // follows the function that is not itself a `function` is considered an argument\n // to the function. The arguments are passed in the order in which they are\n // specified preceding the immediate property value.\n //\n // In the following definition the function is followed by a `number` argument\n // which is passed as the first parameter to the function in serialize or parser.\n\n {\n const definition = {\n object: {\n value: [[[ (max, $_ = 0) => assert($_ < max, `value excedes ${max}`), 1024 ]], 16 ]\n }\n }\n const object = {\n value: 1\n }\n test('assertion-parameter', definition, object, [\n 0x0, 0x1\n ], { require: { assert: 'assert' } })\n }\n\n // This is useful when defining a function that you use more than once in your\n // definition.\n\n {\n const max = (max, $_ = 0) => assert($_ < max, `value excedes ${max}`)\n\n const definition = {\n object: {\n length: [[[ max, 1024 ]], 16 ],\n type: [[[ max, 12 ]], 8 ]\n }\n }\n const object = {\n length: 256,\n type: 3\n }\n test('assertion-parameter-reuse', definition, object, [\n 0x1, 0x0, 0x3\n ], { require: { assert: 'assert' } })\n }\n\n // When using named arguments, the argument values are assigned to the named\n // parameters preceding the first variable that is defined in the current scope.\n // That is, the first occurrence of a variable name that is either the name of a\n // property in the current path or a system name beginning with `$` dollar sign.\n //\n // In the following definition the first argument to the `max` function will be\n // assigned to the `max` named argument. The positional argument mapping stops at\n // the `$path` parameter since it is a system parameter beginning with `$` dollar\n // sign. The `'oops'` parameter of the `max` function call for the `type` property\n // will be ignored.\n\n {\n const max = ({ max, $path, $_ = 0 }) => assert($_ < max, `${$path.pop()} excedes ${max}`)\n\n const definition = {\n object: {\n length: [[[ max, 1024 ]], 16 ],\n type: [[[ max, 12, 'oops' ]], 8 ]\n }\n }\n const object = {\n length: 256,\n type: 3\n }\n test('assertion-parameter-named-reuse', definition, object, [\n 0x1, 0x0, 0x3\n ], { require: { assert: 'assert' } })\n }\n\n // ### Terminated Arrays\n //\n // In the following example, we terminate the array when we encounter a `0` value.\n // The `0` is not included in the array result.\n\n {\n const definition = {\n object: {\n array: [[ 8 ], 0x0 ]\n }\n }\n const object = {\n array: [ 0xab, 0xcd ]\n }\n test('terminated', definition, object, [\n 0xab, 0xcd, 0x0\n ])\n }\n\n // #### Multi-byte Terminators\n //\n // You can specify multi-byte terminators by specifying the multi-byte terminator\n // byte by byte in the end of the definition array.\n //\n // In the following example, we terminate the array when we encounter a `0xa` value\n // followed by a `0xd` value, carriage return followed by line feed.\n //\n // The `0` is not included in the array result.\n\n {\n const definition = {\n object: {\n array: [[ 8 ], 0xd, 0xa ]\n }\n }\n const object = {\n array: [ 0xab, 0xcd ]\n }\n test('terminated-multibyte', definition, object, [\n 0xab, 0xcd, 0xd, 0xa\n ])\n }\n\n // ### String Value Maps\n //\n // **TODO**: Need first draft.\n\n {\n const definition = {\n object: {\n header: [{ type: [ 8, [ 'off', 'on' ] ] }, 8 ]\n }\n }\n const object = {\n header: {\n type: 'on'\n }\n }\n test('string-value-map', definition, object, [\n 0x1\n ])\n }\n\n // ### Floating Point Values\n //\n // Packet supports serializing and parsing IEEE754 floating point numbers. This is\n // the representation common to C.\n //\n // A floating point number is is specified by specifying the value as a floating\n // the point number as `number` with the bit size repeated in the decimal digits of\n // the number.\n //\n // **TODO** Values of `1.1` and `-1.5` are not serializing and restoring correctly.\n // I can't remember if this is expected.\n\n {\n const definition = {\n object: {\n doubled: 64.64,\n float: 32.32\n }\n }\n const object = {\n doubled: 1.2,\n float: -1.5\n }\n test('float', definition, object, [\n 0x3f, 0xf3, 0x33, 0x33,\n 0x33, 0x33, 0x33, 0x33,\n 0xbf, 0xc0, 0x0, 0x0\n ])\n }\n\n // There are only two sizes of floating point number available, 64-bit and 32-bit.\n // These are based on the IEEE 754 standard. As of 2008, the standard defines a\n // [128-bit quad precision floating\n // point](https://en.wikipedia.org/wiki/Quadruple-precision_floating-point_format)\n // but the JavaScript `number` is itself a 64-bit IEEE 754 double-precision float,\n // so we'd have to introduce one of the big decimal libraries from NPM to support\n // it, so it's probably best you sort out a solution for your application using\n // inline functions, maybe serializing to a byte array or `BigInt`. If you\n // encounter at 128-bit number in the wild, I'd be curious. Please let me know.\n //\n // ### Conditionals\n //\n // **TODO**: Need first draft.\n //\n // Basic conditionals are expressed as an array of boolean functions paired with\n // field definitions. The functions and definitions repeat creating an if/else if\n // conditional. The array can end with a field definition that acts as the `else`\n // condition.\n //\n // If the function has positional arguments, the function is called with the root\n // object, followed by an array of indices into any arrays the current path,\n // followed by an array of names of the properties in the current path.\n //\n // In the following definition the bit size of value is 8 bits of the `type`\n // property is `1`, 16 bits if the type property is `2`, 24 bits if the `type`\n // property `3` and `32` bits for any other value of `type`.\n\n {\n const definition = {\n object: {\n type: 8,\n value: [\n $ => $.type == 1, 8,\n $ => $.type == 2, 16,\n $ => $.type == 3, 24,\n true, 32\n ]\n }\n }\n const object = {\n type: 2,\n value: 1\n }\n test('conditional', definition, object, [\n 0x2,\n 0x0, 0x1\n ])\n }\n\n // You can use conditionals in bit-packed integers as well.\n\n {\n const definition = {\n object: {\n header: [{\n type: 4,\n value: [\n $ => $.header.type == 1, 28,\n $ => $.header.type == 2, [{ first: 4, second: 24 }, 28 ],\n $ => $.header.type == 3, [{ first: 14, second: 14 }, 28 ],\n true, [[ 24, 'ffffff' ], 4 ]\n ]\n }, 32 ]\n }\n }\n const object = {\n header: {\n type: 2,\n value: { first: 0xf, second: 0x1 }\n }\n }\n test('conditional-packed', definition, object, [\n 0x2f, 0x0, 0x0, 0x1\n ])\n }\n\n // ### Switch Conditionals\n //\n // **TODO**: Need first draft. Also, example is wrong.\n\n {\n const definition = {\n object: {\n type: 8,\n value: [\n ($) => $.type, [\n { $_: 1 }, 8,\n { $_: [ 2, 3 ] }, 16,\n { $_: [] }, 32\n ]\n ]\n }\n }\n const object = {\n type: 2,\n value: 1\n }\n test('switch', definition, object, [\n 0x2, 0x0, 0x1\n ])\n }\n\n // ### References to Parietals\n //\n // **TODO**: First draft done.\n //\n // If you have a complicated type that requires a complicated definition that is\n // tedious to repeat, you can reference that definition by name.\n //\n // References can be used as types and can also be used as length encoding lengths\n // if they resolve to an integer type. If you create a type that is only used by\n // reference that you do not want available as a packet, prepend and underscore and\n // it will not be returned as a packet type.\n //\n // **Mnemonic**: A string name to name the referenced type.\n //\n // In the following a definition an encoded integer is defined as a partial that\n // will not be presented as a packet due to the `_` prefix to the name. It is\n // referenced by the `series` property as a type and used for the length encoding\n // of the `data` property.\n\n {\n const definition = {\n $encodedInteger: [\n [\n value => value <= 0x7f, 8,\n value => value <= 0x3fff, [ 16, [ 0x80, 7 ], [ 0x0, 7 ] ],\n value => value <= 0x1fffff, [ 24, [ 0x80, 7 ], [ 0x80, 7 ], [ 0x0, 7 ] ],\n true, [ 32, [ 0x80, 7 ], [ 0x80, 7 ], [ 0x80, 7 ], [ 0x0, 7 ] ]\n ],\n [ 8,\n sip => (sip & 0x80) == 0, 8,\n true, [ 8,\n sip => (sip & 0x80) == 0, [ 16, [ 0x80, 7 ], [ 0x0, 7 ] ],\n true, [ 8,\n sip => (sip & 0x80) == 0, [ 24, [ 0x80, 7 ], [ 0x80, 7 ], [ 0x0, 7 ] ],\n true, [ 32, [ 0x80, 7 ], [ 0x80, 7 ], [ 0x80, 7 ], [ 0x0, 7 ] ]\n ]\n ]\n ]\n ],\n object: {\n value: '$encodedInteger',\n // array: [ '$encodedInteger', [ 8 ] ] ~ I haven't done this, requires using conditionals in length encoded arrays or calculated arrays.\n }\n }\n const object = {\n value: 1,\n // array: [ 1 ]\n }\n test('partial', definition, object, [\n 0x1 // , 0x1, 0x1\n ])\n }\n\n // ### Checksums and Running Calculations\n //\n // Some protocols perform checksums on the body of message. Others require tracking\n // the remaining bytes in a message based on a length property in a header and\n // making decisions about the contents of the message based on the bytes remaining.\n //\n // To perform running calculations like buffers and remaining bytes we can use\n // accumulators, lexically scoped object variables that can be used to store the\n // state of a running calculation.\n //\n // The following definition creates an MD5 checksum of the body of a packet and\n // stores the result in a checksum property that follows the body of the message.\n\n {\n const definition = {\n object: [{ hash: () => crypto.createHash('md5') }, {\n body: [[[\n ({ $buffer, $start, $end, hash }) => hash.update($buffer.slice($start, $end))\n ]], {\n number: 32,\n data: [[ 8 ], 0x0 ]\n }],\n checksum: [[\n ({ $_, hash }) => $_ = hash.digest()\n ], [[ 16 ], [ Buffer ]], [\n ({ checksum = 0, hash }) => {\n assert.deepEqual(hash.digest().toJSON(), checksum.toJSON())\n }\n ]]\n }]\n }\n const object = {\n body: {\n number: 1,\n data: [ 0x41, 0x42, 0x43 ]\n },\n checksum: Buffer.from([ 0xc9, 0xd0, 0x87, 0xbd, 0x2f, 0x8f, 0x4a, 0x33, 0xd4, 0xeb, 0x2d, 0xe4, 0x47, 0xc0, 0x40, 0x28 ])\n }\n test('checksum', definition, object, [\n 0x0, 0x0, 0x0, 0x1,\n 0x41, 0x42, 0x43, 0x0,\n 0xc9, 0xd0, 0x87, 0xbd,\n 0x2f, 0x8f, 0x4a, 0x33,\n 0xd4, 0xeb, 0x2d, 0xe4,\n 0x47, 0xc0, 0x40, 0x28\n ], { require: { assert: 'assert', crypto: 'crypto' } })\n }\n\n // Here we also introduce the concept of buffer inlines. These are inlines that\n // operate not on the serialized or parsed value, but instead on the underlying\n // buffer. In the above example the `hash.update()` inline is not called once for\n // each property in the `body`, it is called for each buffer chunk that contains\n // the binary data for the `body`.\n //\n // Unlike ordinary inline functions, a buffer inline is not called prior to\n // serialization. Buffer inlines are called as late as possible to process as much\n // of the buffer continuously as possible. In the previous example, the\n // `hash.update()` inline is applied to the binary data that defines the entire\n // `body` which it encapsulates.\n //\n // We use nested structures to group.\n //\n // **TODO**: Simpler calculation example to start. Calculation is important because\n // it will allow us to talk about the difference between `sizeof`,\n // `offsetof`.\n //\n // **TODO**: Come back and implement this by finding a way to extract sizeof and\n // offset of. Punting because I don't really know what inspired this example or\n // what it is supposed to illustrate.\n\n {\n const definition = {\n packet: [{ counter: () => [] }, {\n header: {\n type: 8,\n length: [[\n ({ $, counter }) => {\n return counter[0] = $sizeof.packet($) - $offsetof.packet($, 'body')\n }\n ], 16, [\n ({ $_, counter }) => {\n return counter[0] = $_\n }\n ]]\n },\n body: [[[\n ({ $_ = 0, $start, $end, counter }) => counter[0] -= $end - $start\n ]], {\n value: 32,\n string: [[ 8 ], 0x0 ],\n variable: [\n ({ counter }) => counter[0] == 4, 32,\n ({ counter }) => counter[0] == 2, 16,\n 8\n ]\n }],\n }]\n }\n }\n\n // ### Parameters\n //\n // **TODO**: Need first draft, or reread this and see if it is a real first draft.\n //\n // Accumulators described in the preceding section also define parameters. Any\n // accumulator declared on the top most field will create parameters to the\n // generated serializes and parsers.\n\n {\n const definition = {\n object: [{ counter: [ 0 ] }, [[[\n ({ $start, $end, counter }) => counter[0] += $end - $start\n ]], {\n number: 8,\n string: [ [ 8 ], 0x0 ]\n }]]\n }\n // **TODO**: API call to get counter.\n }\n\n // The parameters are available as both arguments that can be passed to inline\n // functions as well as generally available in the program scope. Be careful not to\n // careful not to hide any module declarations you've declared.\n\n {\n const definition = {\n object: [{ encoding: 'utf8' }, {\n string: [[\n value => Buffer.from(value, encoding)\n ], [ [ Buffer ], 0x0 ], [\n value => value.toString(encoding)\n ]]\n }]\n }\n const moduleName = compile('parameters', definition, {})\n // *TODO*: API call to encode string ascii or something.\n }\n})\n\n// You can run this unit test yourself to see the output from the various\n// code sections of the readme.\n\n// When can also use modules local to the current project using relative paths, but\n// we face a problem; we're not going to ship language definition with our\n// completed project, we're going to ship the generated software. Therefore,\n// relative must be relative to the generated file. Your relative paths much be\n// relative to the output directory... (eh, whatever. Maybe I can fix that up for\n// you.)\n\n{\n ; ({\n packet: {\n value: [[ $value => ip.toLong($value) ], 32, [ $value => ip.fromLong($value) ]]\n }\n }, {\n require: { ip: '../ip' }\n })\n}\n\n{\n const description = {\n packet: {\n type: [ 8, { 0: 'off', 1: 'on', null: 'unknown' } ]\n }\n }\n}\n\n// ## What's Missing\n//\n// A section of things that need to be written.\n//\n// * **TODO** Did we support packed `BigInt` integers?\n// * **TODO** Absent values.\n// * **TODO** Switch statements.\n// * **TODO** Composition.\n// * **TODO** Parse or serialize conditionals, i.e. unconditionals.\n//\n// ## Outline\n//\n// * Living `README.md`.\n// * Parsers and Serializers\n// * Packet Definition Language\n// * Integers\n// * Negative Integers\n// * Endianness\n// * Nested Structures\n// * Packed Integers\n// * Literals\n// * Length-Encoded Arrays\n// * Inline Transforms and Assertions\n// * Fixed Length Arrays\n// * Requiring Modules\n// * Assertions\n// * Assertion and Transformation Arguments\n// * Terminated Arrays\n// * Multi-byte Terminators\n// * String Value Maps\n// * Floating Point Values\n// * Conditionals\n// * Switch Conditionals\n// * References to Partials\n// * Accumulators\n// * Parameters\n// * What's Missing\n// * Outline", "dangerousExampleEn": "1. var md5 = require('md5');\n2. \n3. console.log(md5('password'));\nLine 3: This is weak for the brute-force attack because it uses md5, a weak hash function.", "safeExampleEn": "1. var bcrypt = require('bcrypt');\n2. \n3. bcrypt.hash(\"password\", 13, function(err, hash) {\n4. console.log(hash);\n5. });\nLine 3: This is safe from the brute-force attack because bcrypt is used to create hash data.", "contexts": [{"lineNo": 1748, "eventType": "sink", "messageKey": "jschk.FORBIDDEN.WEAK_ALGORITHM.JS.defect", "params": {"arg0": "md5"}}]}} {"id": "ed3afeeafcc99f0a299438486999905cb8ca3d3f9d636e9055f3248ca24de31d", "license": {"spdx": ["MIT"], "repo": "k0machi/Belligerence", "path": "modules/conflicts/model.js", "repo_head_hexsha": "e979dd3c87bd4a61b63b0f70a87e99aa54e5d234", "stack_hexsha": "ce59aa7d178b2aeab9ea6cbe2ebc12c50ef98559", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of weak cryptographic algorithm", "issueDescriptionEn": "A hash function is a one-way function that receives data of different lengths and maps it to random data of a fixed length. It is commonly used to store user passwords because it always produces the same output for a given input.\nBecause hash can be calculated very quickly, the hash functions, such as MD5 and SHA, may give the illusion of high performance. However they are vulnerable to random brute-force attacks. If you use the hash functions on simple data, they can be saved in the rainbow table, making it insecure. In addition, RC2, RC3, RC4, RC5, RC6, MD4, and DES are also known to be vulnerable.\nThere are many functions used to overcome the disadvantages of MD5 and SHA.\nIn Node.js, bcrypt is one of the functions that is commonly used with outstanding performance and easily replace them. The latest hash algorithms, such as Argon2, PBKDF2, and Scrypt, are also good alternatives. Make sure to add a salt to the hash in SHA-2 i.e. SHA-224, SHA-256, SHA-384, SHA-512.", "issueLineNumber": 42, "entireCode": "(function(){\n\n\t'use strict';\n\n\tmodule.exports = function(sequelize, DataTypes) {\n\t\t\tvar ConflictsModel = sequelize.define('conflicts_table',\n\t\t\t{\n\t\t\t\tnameField: {\n\t\t\t\t\ttype: DataTypes.STRING,\n\t\t\t\t\tfield: 'name'\n\t\t\t\t},\n\t\t\t\tactiveField: {\n\t\t\t\t\ttype: DataTypes.BOOLEAN,\n\t\t\t\t\tfield: 'active',\n\t\t\t\t\tdefaultValue: true\n\t\t\t\t},\n\t\t\t\tstatusField: {\n\t\t\t\t\ttype: DataTypes.INTEGER,\n\t\t\t\t\tfield: 'status',\n\t\t\t\t\tdefaultValue: 0\n\t\t\t\t},\n\t\t\t\tvictorField: {\n\t\t\t\t\ttype: DataTypes.INTEGER,\n\t\t\t\t\tfield: 'victor',\n\t\t\t\t\tdefaultValue: 0\n\t\t\t\t},\n\t\t\t\thashField: {\n\t\t\t\t\ttype: DataTypes.STRING,\n\t\t\t\t\tdefaultValue: ''\n\t\t\t\t}\n\t\t\t},\n\t\t\t{\n\t\t\t\tfreezeTableName: true,\n\t\t\t\tname: {\n\t\t\t\t\tsingular: 'Conflict',\n\t\t\t\t\tplural: 'Conflicts'\n\t\t\t\t},\n\t\t\t\thooks: {\n\t\t\t\t\tbeforeCreate: function(model, options) {\n\t\t\t\t\t\tvar md5 \t= require(\"md5\"),\n\t\t\t\t\t\t\tconfig \t= require('./../../config.js'),\n\t\t\t\t\t\t\tnewHash = (md5((Math.random(9999999))+(new Date()))).substring(0,config.db.hashSize);\n\t\t\t\t\t\tmodel.setDataValue('hashField', newHash);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tclassMethods: {\n\t\t\t\t\tgetStatus: function() {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\"Ongoing\": 0,\n\t\t\t\t\t\t\t\"Suspended\": 1,\n\t\t\t\t\t\t\t\"Finished\": 2\n\t\t\t\t\t\t};\n\t\t\t\t\t},\n\t\t\t\t\tassociate: function(models) {\n\t\t\t\t\t\tConflictsModel.belongsTo(models.maps);\n\t\t\t\t\t\tConflictsModel.belongsToMany(models.factions, { through: models.participants });\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t}\n\t\t);\n\n\t\treturn ConflictsModel;\n\t};\n\n})();", "dangerousExampleEn": "1. var md5 = require('md5');\n2. \n3. console.log(md5('password'));\nLine 3: This is weak for the brute-force attack because it uses md5, a weak hash function.", "safeExampleEn": "1. var bcrypt = require('bcrypt');\n2. \n3. bcrypt.hash(\"password\", 13, function(err, hash) {\n4. console.log(hash);\n5. });\nLine 3: This is safe from the brute-force attack because bcrypt is used to create hash data.", "contexts": [{"lineNo": 42, "eventType": "sink", "messageKey": "jschk.FORBIDDEN.WEAK_ALGORITHM.JS.defect", "params": {"arg0": "md5"}}]}} {"id": "5972d4c51a10614ba237a1d4455ddb2a6b6f37810707bc3109571783672f275c", "license": {"spdx": ["BSD-3-Clause"], "repo": "redpandalabs/koa-seed-template", "path": "src/util.js", "repo_head_hexsha": "43afc00958cb584c72fb4cae8919d4b2692ecb46", "stack_hexsha": "07a42baa25b1c69c563293ba3bc704f6bee3542f", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of weak cryptographic algorithm", "issueDescriptionEn": "A hash function is a one-way function that receives data of different lengths and maps it to random data of a fixed length. It is commonly used to store user passwords because it always produces the same output for a given input.\nBecause hash can be calculated very quickly, the hash functions, such as MD5 and SHA, may give the illusion of high performance. However they are vulnerable to random brute-force attacks. If you use the hash functions on simple data, they can be saved in the rainbow table, making it insecure. In addition, RC2, RC3, RC4, RC5, RC6, MD4, and DES are also known to be vulnerable.\nThere are many functions used to overcome the disadvantages of MD5 and SHA.\nIn Node.js, bcrypt is one of the functions that is commonly used with outstanding performance and easily replace them. The latest hash algorithms, such as Argon2, PBKDF2, and Scrypt, are also good alternatives. Make sure to add a salt to the hash in SHA-2 i.e. SHA-224, SHA-256, SHA-384, SHA-512.", "issueLineNumber": 58, "entireCode": "// Utility Functions\n'use strict'\n\nconst crypto = require('crypto')\nconst _ = require('ramda')\nconst bcrypt = require('bcrypt')\n\nconst iv = 'asdfasdfasdfasdf'\n\nconst randomString = (length) => crypto.randomBytes(length ? length : 64).toString('hex')\n\nconst randomNumber = (length) =>\n _.isEmpty(length) ? Math.floor(Math.random() * 9999999) : parseInt(Math.floor(Math.random() * 9999999).toString().slice(0, length))\n\nconst randomStringWithTimestamp = () => crypto.randomBytes(2).toString('hex').toUpperCase() + Date.now()\n\nconst milliSecondsInOneWeek = 1000 * 60 * 60 *24 * 7\n\nconst padLeftZero = (number) => (number < 10) ? '0'.concat(number) : number\n\nconst formatDateToDDMMYYYY = (date) => _.join('-', _.map(padLeftZero, [date.getDate(), date.getMonth() + 1, date.getFullYear()]))\n\n// hash users password using SHA512\nconst sha512 = (password, salt) => {\n const hash = crypto.createHmac('sha512', salt)\n hash.update(password)\n const value = hash.digest('hex')\n return value\n}\n\nconst sha256 = (data) => {\n const hash = crypto.createHash('sha256')\n hash.update(data)\n const value = hash.digest('hex')\n return value\n}\n\nconst bcryptPassword = (password, salt) => {\n // salt must be in the form => $Vers$log2(NumRounds)$saltvalue\n const formattedSalt = '$2a$10$'.concat(salt)\n return bcrypt.hashSync(password, formattedSalt)\n}\n\nconst AES_encrypt = (key, data) => {\n const cipher = crypto.createCipheriv('aes-256-cbc', key.slice(0,32), iv)\n let encrypted = cipher.update(data, 'utf8', 'hex') //eslint-disable-line\n encrypted += cipher.final('hex') //eslint-disable-line\n return encrypted\n}\n\nconst AES_decrypt = (key, data) => {\n const decipher = crypto.createDecipheriv('aes-256-cbc', key.slice(0,32), iv)\n let decrypted = decipher.update(data, 'hex', 'utf8') //eslint-disable-line\n decrypted += decipher.final('utf8') //eslint-disable-line\n return decrypted\n}\n\nconst md5 = (data) => crypto.createHash('md5').update(data).digest('hex')\n\nmodule.exports = {\n randomString,\n randomNumber,\n randomStringWithTimestamp,\n sha512,\n sha256,\n bcryptPassword,\n AES_encrypt,\n AES_decrypt,\n milliSecondsInOneWeek,\n md5,\n formatDateToDDMMYYYY\n}", "dangerousExampleEn": "1. var md5 = require('md5');\n2. \n3. console.log(md5('password'));\nLine 3: This is weak for the brute-force attack because it uses md5, a weak hash function.", "safeExampleEn": "1. var bcrypt = require('bcrypt');\n2. \n3. bcrypt.hash(\"password\", 13, function(err, hash) {\n4. console.log(hash);\n5. });\nLine 3: This is safe from the brute-force attack because bcrypt is used to create hash data.", "contexts": [{"lineNo": 58, "eventType": "sink", "messageKey": "jschk.FORBIDDEN.WEAK_ALGORITHM.JS.defect", "params": {"arg0": "md5"}}]}} {"id": "13fe5ce99fe107c1b7ccc1b967631e97d4c9ec3275b7efe28e9c9f3d9ee767b1", "license": {"spdx": ["MIT"], "repo": "axolo/rbac-baby", "path": "dotjs/api/routes/files.js", "repo_head_hexsha": "8268c6bed7c1d24c787d4d67486a30bc4568c872", "stack_hexsha": "fae8507754d823e29205275881b63feb4303d759", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of weak cryptographic algorithm", "issueDescriptionEn": "A hash function is a one-way function that receives data of different lengths and maps it to random data of a fixed length. It is commonly used to store user passwords because it always produces the same output for a given input.\nBecause hash can be calculated very quickly, the hash functions, such as MD5 and SHA, may give the illusion of high performance. However they are vulnerable to random brute-force attacks. If you use the hash functions on simple data, they can be saved in the rainbow table, making it insecure. In addition, RC2, RC3, RC4, RC5, RC6, MD4, and DES are also known to be vulnerable.\nThere are many functions used to overcome the disadvantages of MD5 and SHA.\nIn Node.js, bcrypt is one of the functions that is commonly used with outstanding performance and easily replace them. The latest hash algorithms, such as Argon2, PBKDF2, and Scrypt, are also good alternatives. Make sure to add a salt to the hash in SHA-2 i.e. SHA-224, SHA-256, SHA-384, SHA-512.", "issueLineNumber": 60, "entireCode": "/**\n * 同一个物理存储的文件可对应多个不同的主题。\n * 比如,主题1附件1对应物理存储文件1,主题2的附件1也可能对应物理存储文件1,\n * 因此,数据库记录跟物理存储关系为N:1。\n * 1、跨域:采用cors\n * 2、去重(HASH、MD5)\n * @todo 3、进度(客户端可见上传下载实时进度、可后台进行)\n * @todo 4、权限(读、写、积分、付费等)\n * @todo 5、限流(字节数、次数等)\n * @todo 6、CDN存取(AWS、七牛、或者自制)\n * @todo 7、自动分目录(按用户、按日期、按类型?)\n * @todo 8、无引用文件清理、删除\n * @todo 9、断点续传\n * @todo 10、下载线程控制\n */\n\nvar files = require('../models/files');\nvar upload = require('../plugins/upload');\nvar fs = require('fs');\nvar crypto = require('crypto');\nvar express = require('express');\nvar router = express.Router();\n\nrouter.all('/count', function(req, res) {\n files.count({}, function(err, count) {\n res.jsonp(err ? err : count);\n });\n});\n\nrouter.all('/list', function(req, res){\n files\n .find({})\n .sort({ update: -1 })\n .limit(10)\n .skip(0)\n .exec(function(err, doc){\n res.jsonp(err ? err : doc);\n });\n});\n\nrouter.all('/download/:id', function(req, res){\n files\n .findOne()\n .where({ _id: req.params.id })\n .exec(function(err, doc) {\n if(err) {\n res.jsonp(err);\n } else {\n res.download(doc.destination + '/' + doc.filename, doc.originalname, function(err) {\n if(err){\n res.jsonp(err);\n }\n });\n }\n })\n});\n\nrouter.all('/upload', upload.single('file'), function(req, res) {\n var rs = fs.createReadStream(req.file.path);\n var hash = crypto.createHash('md5');\n rs.on('data', hash.update.bind(hash));\n rs.on('end', function() {\n var md5 = hash.digest('hex');\n var filename = md5 + /\\.[^\\.]+$/.exec(req.file.originalname.toLowerCase()); //md5.ext\n fs.rename(req.file.path, req.file.destination + '/' + filename, function(err) {\n if(err) {\n //@todo 处理错误\n res.jsonp(err);\n } else {\n files({\n filename: filename,\n destination: req.file.destination,\n encoding: req.file.encoding,\n mimetype: req.file.mimetype,\n size: req.file.size,\n hash: md5,\n originalname: req.file.originalname,\n description: req.body.description\n }).save(function(err, doc) {\n res.jsonp(err?err:doc);\n });\n }\n });\n });\n});\n\nmodule.exports = router;", "dangerousExampleEn": "1. var md5 = require('md5');\n2. \n3. console.log(md5('password'));\nLine 3: This is weak for the brute-force attack because it uses md5, a weak hash function.", "safeExampleEn": "1. var bcrypt = require('bcrypt');\n2. \n3. bcrypt.hash(\"password\", 13, function(err, hash) {\n4. console.log(hash);\n5. });\nLine 3: This is safe from the brute-force attack because bcrypt is used to create hash data.", "contexts": [{"lineNo": 60, "eventType": "sink", "messageKey": "jschk.FORBIDDEN.WEAK_ALGORITHM.JS.defect", "params": {"arg0": "md5"}}]}} {"id": "87ffc0434fb3d74396e82210506412ea7f9003cd8d564676aa2223f9067db560", "license": {"spdx": ["MIT"], "repo": "atahani/telepathy-backend", "path": "app/models/client.server.model.js", "repo_head_hexsha": "22c10ecc3b1dd1831347efa416e4c876c5af2cd7", "stack_hexsha": "37fc45ce7d36c4ec8e04e0085df66e218a78ffce", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of weak cryptographic algorithm", "issueDescriptionEn": "A hash function is a one-way function that receives data of different lengths and maps it to random data of a fixed length. It is commonly used to store user passwords because it always produces the same output for a given input.\nBecause hash can be calculated very quickly, the hash functions, such as MD5 and SHA, may give the illusion of high performance. However they are vulnerable to random brute-force attacks. If you use the hash functions on simple data, they can be saved in the rainbow table, making it insecure. In addition, RC2, RC3, RC4, RC5, RC6, MD4, and DES are also known to be vulnerable.\nThere are many functions used to overcome the disadvantages of MD5 and SHA.\nIn Node.js, bcrypt is one of the functions that is commonly used with outstanding performance and easily replace them. The latest hash algorithms, such as Argon2, PBKDF2, and Scrypt, are also good alternatives. Make sure to add a salt to the hash in SHA-2 i.e. SHA-224, SHA-256, SHA-384, SHA-512.", "issueLineNumber": 89, "entireCode": "'use strict';\n\n/**\n * Module dependencies.\n */\nvar mongoose=require('mongoose'),\n\tSchema=mongoose.Schema,\n\tcrypto = require('crypto');\n\n/**\n * Client Schema , the app_id is _id that mongoDB generate automatically\n * the settings for client config like GCM,APNS,MPNS settings have name & value\n */\nvar ClientSchema=new Schema({\n\tapp_key:{\n\t\ttype:String,\n\t\tunique:true\n\t},\n\ttitle:{\n\t\ttype:String,\n\t\ttrim:true,\n\t\trequired:true\n\t},\n\tshort_name:{\n\t\ttype:String,\n\t\ttrim:true,\n\t\tunique:true\n\t},\n\ttrusted_app:{\n\t\ttype:Boolean,\n\t\tdefault:false\n\t},\n\t_user:{\n\t\ttype:Schema.ObjectId,\n\t\tref:'User'\n\t},\n\tactive_status:{\n\t\ttype:Boolean,\n\t\tdefault:false\n\t},\n\tweb_address_url:{\n\t\ttype:String,\n\t\ttrim:true,\n\t\trequired:true\n\t},\n\tcall_back_url:{\n\t\ttype:String,\n\t\ttrim:true\n\t},\n\tdescription:{\n\t\ttype:String,\n\t\ttrim:true,\n\t\trequired:true\n\t},\n\tapp_logo_file_name:{\n\t\ttype:String\n\t},\n\tplatform:{\n\t\ttype:String,\n\t\tenum: ['android', 'ios','web','windows_desktop'],\n\t\trequired:true\n\t},\n\tsettings:[{\n\t\t_id:false,\n\t\tname:String,\n\t\tvalue:String\n\t}],\n\tcreated_at: {\n\t\ttype: Date,\n\t\tdefault: Date.now\n\t},\n\tupdated_at:{\n\t\ttype:Date\n\t}\n});\n\n/**\n * Hook a pre save method to generate app_key\n */\nClientSchema.pre('save', function(next) {\n\tthis.app_key=crypto.randomBytes(20).toString('hex');\n\tnext();\n});\n\n/**\n * Get hashed App_key for application using\n */\nClientSchema.methods.getAppKey=function(){\n\treturn crypto.createHash('md5').update(this.app_key).digest('hex');\n};\n\n/**\n * Check app_key hash and client status\n * @param app_key input\n * @returns {boolean} is valid return true\n */\nClientSchema.methods.isValidAppKey=function(app_key){\n\treturn this.active_status && crypto.createHash('md5').update(this.app_key).digest('hex')===app_key;\n};\n\nmongoose.model('Client', ClientSchema);", "dangerousExampleEn": "1. var md5 = require('md5');\n2. \n3. console.log(md5('password'));\nLine 3: This is weak for the brute-force attack because it uses md5, a weak hash function.", "safeExampleEn": "1. var bcrypt = require('bcrypt');\n2. \n3. bcrypt.hash(\"password\", 13, function(err, hash) {\n4. console.log(hash);\n5. });\nLine 3: This is safe from the brute-force attack because bcrypt is used to create hash data.", "contexts": [{"lineNo": 89, "eventType": "sink", "messageKey": "jschk.FORBIDDEN.WEAK_ALGORITHM.JS.defect", "params": {"arg0": "md5"}}]}} {"id": "054e86e7cc8de62cae131e5293760c233bf3d0e86ffa3493889327bdfbfe3e63", "license": {"spdx": ["MIT"], "repo": "nogproject/nog", "path": "packages/nog-catalog/nog-catalog-main-server.js", "repo_head_hexsha": "445038916a41849469d2232ef14006c1d7f5b8e0", "stack_hexsha": "dae4eb6f0d9b3ca1975a29f2d38083da8336e461", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of weak cryptographic algorithm", "issueDescriptionEn": "A hash function is a one-way function that receives data of different lengths and maps it to random data of a fixed length. It is commonly used to store user passwords because it always produces the same output for a given input.\nBecause hash can be calculated very quickly, the hash functions, such as MD5 and SHA, may give the illusion of high performance. However they are vulnerable to random brute-force attacks. If you use the hash functions on simple data, they can be saved in the rainbow table, making it insecure. In addition, RC2, RC3, RC4, RC5, RC6, MD4, and DES are also known to be vulnerable.\nThere are many functions used to overcome the disadvantages of MD5 and SHA.\nIn Node.js, bcrypt is one of the functions that is commonly used with outstanding performance and easily replace them. The latest hash algorithms, such as Argon2, PBKDF2, and Scrypt, are also good alternatives. Make sure to add a salt to the hash in SHA-2 i.e. SHA-224, SHA-256, SHA-384, SHA-512.", "issueLineNumber": 106, "entireCode": "import crypto from 'crypto';\nimport { EJSON } from 'meteor/ejson';\nimport { Match, check } from 'meteor/check';\nimport { Meteor } from 'meteor/meteor';\nimport { Mongo } from 'meteor/mongo';\nimport { Counter } from 'meteor/natestrauser:publish-performant-counts';\nimport { _ } from 'meteor/underscore';\nimport { NogError } from 'meteor/nog-error';\nconst {\n ERR_CONFLICT,\n ERR_CONTENT_MISSING,\n ERR_LOGIC,\n ERR_LOST_LOCK,\n ERR_NOT_OF_KIND,\n ERR_REF_NOT_FOUND,\n ERR_REPO_MISSING,\n ERR_UNIMPLEMENTED,\n nogthrow,\n} = NogError;\nimport { matchPositiveNumber } from 'meteor/nog-settings';\n\nimport { defCatalogMethods } from './nog-catalog-methods.js';\nimport { makeCollName, makePubName } from './nog-catalog-common.js';\nimport { createMongoDocLock } from './concurrency.js';\nimport {\n matchCatalogPipelineStep,\n compilePipeline,\n} from './catalog-pipeline.js';\nimport './nog-catalog-settings.js';\n\n\nconst AA_UPDATE_CATALOG = 'nog-catalog/update';\nconst AA_CONFIGURE_CATALOG = 'nog-catalog/configure';\nconst AA_GET_CONTENT = 'nog-content/get';\nconst AA_FSO_READ_REPO = 'fso/read-repo';\nconst AA_FSO_UPDATE_CATALOG = 'fso/update-catalog';\n\nconst {\n catalogMaxStringLength,\n catalogMaxNumMetaIndexes,\n} = Meteor.settings;\n\nconst rgxUuid = (\n /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/\n);\n\nconst matchUuidStringOrBinary = Match.Where((x) => {\n if (Match.test(x, String)) {\n if (!x.match(rgxUuid)) {\n throw new Match.Error('Invalid string UUID.');\n }\n return true;\n } else if (Match.test(x, Match.Where(EJSON.isBinary))) {\n if (x.length !== 16) {\n throw new Match.Error('Invalid binary UUID.');\n }\n return true;\n }\n throw new Match.Error('Expected String or Binary.');\n});\n\nconst matchSimpleName = Match.Where((x) => {\n check(x, String);\n if (!x.match(/^[a-zA-Z0-9-_]+$/)) {\n throw new Match.Error('Invalid simple name.');\n }\n return true;\n});\n\nconst matchCatalogVolumeName = Match.Where((x) => {\n check(x, String);\n const rgxName = /^[\\w.]+\\.vol_\\w+_\\d+$/;\n if (!rgxName.test(x)) {\n throw new Match.Error('Invalid catalog volume name.');\n }\n return true;\n});\n\nconst matchMetaFieldName = Match.Where((x) => {\n check(x, String);\n const rgxName = /^m\\d+$/;\n if (!rgxName.test(x)) {\n throw new Match.Error('Invalid meta field name.');\n }\n return true;\n});\n\nconst matchCatalogContentRepoConfig = Match.Where((x) => {\n check(x, {\n repoSelector: Object, // MongoDB selector.\n pipeline: [matchCatalogPipelineStep],\n });\n return true;\n});\n\nconst matchCatalogConfig = Match.Where((x) => {\n check(x, {\n preferredMetaKeys: [String],\n contentRepoConfigs: [matchCatalogContentRepoConfig],\n });\n return true;\n});\n\n\nfunction sha1Hex(d) {\n return crypto.createHash('sha1').update(d, 'utf8').digest('hex');\n}\n\n\nfunction isDuplicateMongoIdError(err) {\n return err.code === 11000;\n}\n\n\n// `tokenize()` splits a search string into text tokens and prefix tokens of\n// format `:`. It has been copied from `nog-search.coffee`. See\n// there for details.\n//\n// `compileQuery()` uses the prefix tokens to compile a regex MongoDB selector,\n// which should be useful for expert users. Text tokens are joined for\n// fulltext search over the string fields.\n//\n// XXX The query language should probably be clarified and be factored out and\n// unified with the query language for `nog-search`.\n\nfunction tokenize(str) {\n const m = str.match(/(\\S+:)?\"[^\"]+\"|\\S+/g);\n if (!m) {\n return [];\n }\n const tokens = [];\n for (let tok of m) {\n const isQuoted = !!tok.match(/\"/);\n tok = tok.replace(/\"/g, ''); // Remove quotes.\n const parts = tok.split(':');\n if (parts.length === 1) {\n tokens.push({ type: 'text', text: tok, isQuoted });\n } else {\n tokens.push({\n type: 'prefix',\n text: parts.slice(1).join(':'),\n prefix: parts[0],\n isQuoted,\n });\n }\n }\n return tokens;\n}\n\n\nfunction compileQuery(str) {\n const tokens = tokenize(str);\n const query = {};\n const text = [];\n for (const tok of tokens) {\n if (tok.type === 'prefix') {\n let { prefix } = tok;\n if (prefix.match(/^m\\d+$/)) {\n prefix = `m.${prefix}`;\n }\n query[prefix] = { $regex: tok.text, $options: 'i' };\n } else if (tok.type === 'text') {\n text.push(tok.text);\n }\n }\n if (text.length > 0) {\n query.$text = { $search: text.join(' ') };\n }\n return query;\n}\n\n\nfunction getCatalogConfig({\n contentStore: store, euid, ownerName, repoName,\n}) {\n const nameSel = { ownerName, repoName };\n const refName = 'branches/master';\n // `store` getters throw if missing.\n const refs = store.getRefs(euid, nameSel);\n const master = refs[refName];\n const commit = store.getCommit(euid, { ...nameSel, sha1: master });\n const tree = store.getTree(euid, { ...nameSel, sha1: commit.tree });\n const { catalog } = tree.meta;\n if (!_.isObject(catalog)) {\n nogthrow(ERR_NOT_OF_KIND);\n }\n check(catalog.config, String);\n const parsed = EJSON.parse(tree.meta.catalog.config);\n check(parsed, matchCatalogConfig);\n return parsed;\n}\n\n\nfunction createFieldManager({\n catalogs, catalogId, preferredMetaKeys, stage,\n}) {\n const metaKeysField = `${stage}.metaKeys`;\n catalogs.update(\n { _id: catalogId, [metaKeysField]: { $exists: false } },\n { $set: { [metaKeysField]: preferredMetaKeys } },\n );\n\n const keyIndexOrder = [...preferredMetaKeys];\n const keyToField = {};\n const fieldToKey = {};\n\n function readKeyMap() {\n const { metaKeys } = catalogs.findOne(catalogId)[stage];\n // eslint-disable-next-line no-plusplus\n for (let i = 0; i < metaKeys.length; i++) {\n const key = metaKeys[i];\n const field = `m${i}`;\n keyToField[key] = field;\n fieldToKey[field] = key;\n }\n }\n\n function allocField(metaKey) {\n catalogs.update(\n { _id: catalogId, [metaKeysField]: { $ne: metaKey } },\n { $push: { [metaKeysField]: metaKey } },\n );\n readKeyMap();\n return keyToField[metaKey];\n }\n\n readKeyMap();\n\n return {\n getMongoField(metaKey) {\n const f = keyToField[metaKey];\n if (f) {\n return f;\n }\n return allocField(metaKey);\n },\n\n getKey(field) {\n return fieldToKey[field];\n },\n\n getMongoFields() {\n return _.values(keyToField);\n },\n\n getMongoIndexFields() {\n const fields = new Set();\n for (const k of keyIndexOrder) {\n fields.add(this.getMongoField(k));\n }\n for (const f of this.getMongoFields()) {\n fields.add(f);\n }\n return [...fields.values()].splice(0, catalogMaxNumMetaIndexes);\n },\n\n isMongoFieldName(name) {\n return !!name.match(/^m\\d+$/);\n },\n };\n}\n\n\nfunction truncatedMetaVal(val) {\n let isTruncated = false;\n\n if (_.isNumber(val) || Match.test(val, [Number])) {\n return { val, isTruncated };\n }\n\n function truncated(s) {\n if (s.length <= catalogMaxStringLength) {\n return s;\n }\n isTruncated = true;\n const indicator = '[TRUNCATED]';\n const last = catalogMaxStringLength - indicator.length - 1;\n return s.slice(0, last) + indicator;\n }\n\n let trunc;\n if (_.isString(val)) {\n trunc = truncated(val);\n } else {\n trunc = val.map(truncated);\n }\n\n return { val: trunc, isTruncated };\n}\n\n\nfunction treeWalk({ contentStore, treeId, rateLimiters }, cb) {\n function walk(entry, parentPath) {\n let content = null;\n rateLimiters.readLimiter.op();\n if (entry.type === 'object') {\n content = contentStore.objects.findOne(entry.sha1);\n } else if (entry.type === 'tree') {\n content = contentStore.trees.findOne(entry.sha1);\n } else {\n const reason = `Unknown entry type ${entry.type}.`;\n nogthrow(ERR_LOGIC, { reason });\n }\n if (!content) {\n const reason = `Missing entry ${JSON.stringify(entry)}.`;\n nogthrow(ERR_CONTENT_MISSING, { reason });\n }\n\n let path;\n if (parentPath == null) {\n path = '';\n } else if (parentPath === '') {\n path = content.name;\n } else {\n path = `${parentPath}/${content.name}`;\n }\n\n cb({ path, ...content }, rateLimiters);\n\n if (content.entries) {\n for (const e of content.entries) {\n walk(e, path);\n }\n }\n }\n\n walk({ type: 'tree', sha1: treeId }, null);\n}\n\n\nfunction addContentRepoSudo({\n contentStore, repo, volume, fieldManager, pipelineFuncs, logger, renewLock,\n rateLimiters,\n}) {\n const refName = 'branches/master';\n const repoId = repo._id;\n\n const commitId = repo.refs[refName];\n if (!commitId) {\n nogthrow(ERR_REF_NOT_FOUND);\n }\n const commit = contentStore.commits.findOne(commitId);\n if (!commit) {\n nogthrow(ERR_CONTENT_MISSING);\n }\n\n const repoFullname = `${repo.owner}/${repo.name}`;\n logger.log(\n `[nog-catalog] Begin full entry scan of repo \\`${repoFullname}\\`.`,\n );\n\n let totalCount = 0;\n let selectCount = 0;\n\n treeWalk({\n contentStore, treeId: commit.tree, rateLimiters,\n }, (origContent) => {\n renewLock();\n\n let content = { ...origContent };\n\n totalCount += 1;\n for (const fn of pipelineFuncs) {\n content = fn(content);\n if (!content) {\n return;\n }\n }\n selectCount += 1;\n\n const fixed = {\n _id: content._id,\n name: content.name,\n m: {},\n };\n\n for (const [k, v] of _.pairs(content.meta)) {\n // XXX We silently ignore null and objects. Is this good enough?\n if (Match.test(v, Match.OneOf(String, Number, [String], [Number]))) {\n const { val, isTruncated } = truncatedMetaVal(v);\n if (isTruncated) {\n logger.log(\n '[nog-catalog] Truncated meta value in databank ' +\n `to satisfy max string length ${catalogMaxStringLength}: ` +\n `${content._id}.meta.${k}`,\n );\n }\n const field = fieldManager.getMongoField(k);\n // Force value to array, so that `$unwind` in MongoDB pipelines works\n // correctly with MongoDB < 3.2. This could be removed when we use\n // MongoDB >= 3.2 everywhere. See `publishCatalogVolumeStats()`.\n if (_.isArray(val)) {\n fixed.m[field] = val;\n } else {\n fixed.m[field] = [val];\n }\n }\n }\n\n const refpath = {\n repoId,\n owner: repo.owner,\n repo: repo.name,\n commitId,\n path: content.path,\n };\n fixed.refpaths = [refpath];\n\n rateLimiters.writeLimiter.op();\n try {\n volume.insert(fixed);\n } catch (err) {\n if (!isDuplicateMongoIdError(err)) {\n throw err;\n }\n }\n volume.update(content._id, { $addToSet: { refpaths: refpath } });\n });\n\n volume.update(\n { 'refpaths.repoId': repoId },\n { $pull: { refpaths: { repoId, commitId: { $ne: commitId } } } },\n { multi: true },\n );\n\n logger.log(\n `[nog-catalog] End full entry scan of repo \\`${repoFullname}\\`: ` +\n `selected ${selectCount} of ${totalCount} entries.`,\n );\n}\n\n\nfunction dropRetiredVolumes({ catalogs, logger }) {\n catalogs.find(\n { retiredVolumes: { $exists: true } },\n { fields: { retiredVolumes: true } },\n ).forEach((catalog) => {\n catalog.retiredVolumes.forEach(({ name }) => {\n const c = new Mongo.Collection(name, { defineMutationMethods: false });\n c.rawCollection().drop();\n logger.log(`[nog-catalog] Dropped retired volume \\`${name}\\`.`);\n });\n catalogs.update(catalog._id, { $unset: { retiredVolumes: '' } });\n });\n}\n\n\n// `dropStaleCatalogs()` removes catalogs whose name does not match the\n// `catalogId`. Such catalogs may be leftovers of deleted catalog repos.\nfunction dropStaleCatalogs({\n catalogs, catalogId, nameDetails, logger,\n}) {\n catalogs.find(\n {\n ...nameDetails, // `{ owner, name }` or `{ fsoPath }`\n _id: { $ne: catalogId },\n },\n {\n fields: {\n retiredVolumes: true,\n 'active.volumes': true,\n 'building.volumes': true,\n },\n },\n ).forEach((catalog) => {\n const volumes = [].concat(\n catalog.retiredVolumes || [],\n catalog.active ? catalog.active.volumes : [],\n catalog.building ? catalog.building.volumes : [],\n );\n volumes.forEach(({ name }) => {\n const c = new Mongo.Collection(name, { defineMutationMethods: false });\n c.rawCollection().drop();\n logger.log(`[nog-catalog] Dropped stale volume \\`${name}\\`.`);\n });\n catalogs.remove(catalog._id);\n logger.log(\n `[nog-catalog] Dropped stale catalog \\`${catalog._id}\\` ` +\n `${EJSON.stringify(nameDetails)}.`,\n );\n });\n}\n\n\n// `createCollection(name)` ensures that the MongoDB collection exists on disk.\n\nfunction createCollection(name) {\n const c = new Mongo.Collection(name);\n if (!c.findOne()) {\n c.remove(c.insert({}));\n }\n return c;\n}\n\n\nfunction createLogger() {\n return {\n messages: [],\n\n log(msg) {\n const nowIso = (new Date()).toISOString();\n this.messages.push(`${nowIso}: ${msg}`);\n console.log(msg);\n },\n };\n}\n\nconst matchCatalogPlugin = Match.Where((x) => {\n check(x, {\n name: String,\n version: Number,\n repoSelectorKey: String,\n addContent: Function,\n getCatalogConfig: Function,\n });\n return true;\n});\n\nfunction createPluginRegistry() {\n return {\n // `plugins` contains all plugins in registration order.\n plugins: [],\n\n // `fso` contains the `fso` plugin if is has been registered.\n fso: null,\n\n versions() {\n return this.plugins.map(p => ({\n name: p.name,\n version: p.version,\n }));\n },\n\n register(plug) {\n check(plug, matchCatalogPlugin);\n this.plugins.push(plug);\n if (plug.name === 'fso') {\n this.fso = plug;\n }\n },\n\n findAddContentHook(repoSelector) {\n for (const plug of this.plugins) {\n if (_.has(repoSelector, plug.repoSelectorKey)) {\n return plug;\n }\n }\n return null;\n },\n };\n}\n\nfunction createCatalogServerModule({\n namespace,\n contentStore,\n checkAccess, testAccess,\n rateLimiters,\n}) {\n const catalogs = new Mongo.Collection(makeCollName(namespace, 'catalogs'));\n const volumes = {};\n const plugins = createPluginRegistry();\n let nogSuggest = null;\n\n function findCatalogVolume(euid, { ownerName, repoName, volumeName }) {\n if (!testAccess(euid, AA_GET_CONTENT, { ownerName, repoName })) {\n console.log(\n `[nog-catalog] Access denied to catalog volume \\`${volumeName}\\`.`,\n );\n return null;\n }\n\n const catalog = catalogs.findOne(\n { owner: ownerName, name: repoName },\n { fields: { 'active.volumes': 1 } },\n );\n if (!catalog || !catalog.active) {\n return null;\n }\n\n const volNames = new Set(catalog.active.volumes.map(v => v.name));\n if (!volNames.has(volumeName)) {\n return null;\n }\n\n const vol = volumes[volumeName] || createCollection(volumeName);\n volumes[volumeName] = vol;\n return vol;\n }\n\n function findCatalogVolumeFso(euid, { repoPath, volumeName }) {\n if (!testAccess(euid, AA_FSO_READ_REPO, { path: repoPath })) {\n console.log(\n `[nog-catalog] Access denied to catalog volume \\`${volumeName}\\`.`,\n );\n return null;\n }\n\n const catalog = catalogs.findOne(\n { fsoPath: repoPath },\n { fields: { 'active.volumes': 1 } },\n );\n if (!catalog || !catalog.active) {\n return null;\n }\n\n const volNames = new Set(catalog.active.volumes.map(v => v.name));\n if (!volNames.has(volumeName)) {\n return null;\n }\n\n const vol = volumes[volumeName] || createCollection(volumeName);\n volumes[volumeName] = vol;\n return vol;\n }\n\n function updateCatalogCommon(euid, {\n catalogId, config, nameDetails, options = {},\n }) {\n const logger = createLogger();\n const version = 2; // Bump to force rebuild when implementation changes.\n const pluginVersions = plugins.versions();\n const configHash = sha1Hex(EJSON.stringify(\n { version, pluginVersions, config }, { canonical: true },\n ));\n const { contentRepoConfigs, preferredMetaKeys } = config;\n\n try {\n catalogs.insert({ _id: catalogId });\n } catch (err) {\n if (!isDuplicateMongoIdError(err)) {\n throw err;\n }\n }\n // Save the last user that ran update. The `FsoCatalogUpdater` uses it for\n // automatic background updates.\n const updateUser = _.isObject(euid) ? euid._id : euid;\n catalogs.update(catalogId, {\n $set: {\n updateUser,\n ...nameDetails,\n },\n });\n\n const lock = createMongoDocLock({\n collection: catalogs, docId: catalogId, core: { op: 'UPDATE' },\n logPrefix: `[nog-catalog] updateCatalog \\`${catalogId}\\``,\n });\n if (!lock.tryLock()) {\n nogthrow(ERR_CONFLICT);\n }\n\n function renewLock() {\n if (!lock.tryRenew()) {\n nogthrow(ERR_LOST_LOCK);\n }\n }\n\n dropStaleCatalogs({\n catalogs, catalogId, nameDetails, logger,\n });\n\n let catalog = catalogs.findOne(catalogId);\n let stage = null;\n let serial = null;\n if (catalog.active && catalog.active.configHash === configHash) {\n stage = 'active';\n ({ serial } = catalog.active);\n if (catalog.building) {\n const retire = catalog.building.volumes || [];\n catalogs.update(catalogId, {\n $addToSet: { retiredVolumes: { $each: retire } },\n $unset: { building: '' },\n });\n }\n } else {\n stage = 'building';\n let retire = [];\n if (catalog.building) {\n retire = catalog.building.volumes || [];\n }\n catalogs.update(\n { _id: catalogId, 'building.configHash': { $ne: configHash } },\n {\n $addToSet: { retiredVolumes: { $each: retire } },\n $set: { building: { configHash, volumes: [] } },\n $inc: { serial: 1 },\n },\n );\n catalog = catalogs.findOne(catalogId);\n ({ serial } = catalog);\n catalogs.update(catalogId, {\n $set: { 'building.serial': serial },\n });\n }\n logger.log(\n `[nog-catalog] Using catalog serial ${catalog.serial}, ` +\n `config hash ${configHash}, in stage \\`${stage}\\`.`,\n );\n\n const volumeName = makeCollName(\n namespace, `catalogs.vol_${catalogId}_${serial}`,\n );\n const volume = volumes[volumeName] || createCollection(volumeName);\n volumes[volumeName] = volume;\n\n catalogs.update(catalogId, {\n $addToSet: { [`${stage}.volumes`]: { name: volumeName } },\n });\n\n const fieldManager = createFieldManager({\n catalogs, catalogId, preferredMetaKeys, stage,\n });\n\n for (const cfg of contentRepoConfigs) {\n renewLock();\n\n const { repoSelector, pipeline } = cfg;\n const pipelineFuncs = compilePipeline(pipeline);\n\n const plug = plugins.findAddContentHook(repoSelector);\n if (plug) {\n plug.addContent(euid, {\n catalogs, catalogId, stage,\n volume, fieldManager, truncatedMetaVal,\n repoSelector, pipelineFuncs,\n logger, renewLock, rateLimiters,\n options,\n });\n continue; // eslint-disable-line no-continue\n }\n\n contentStore.deletedRepos.find(repoSelector).forEach((repo) => {\n renewLock();\n\n const repoId = repo._id;\n if (contentStore.repos.findOne(repoId)) {\n return; // Content not yet fully deleted.\n }\n const sel = {\n _id: catalogId,\n [`${stage}.deletedRepos`]: repoId,\n };\n if (catalogs.findOne(sel)) {\n return; // Catalog entries already removed.\n }\n\n const repoFullname = `${repo.owner}/${repo.name}`;\n logger.log(\n `[nog-catalog] Begin entry cleanup for ` +\n `deleted repo \\`${repoFullname}\\`.`,\n );\n\n volume.update(\n { 'refpaths.repoId': repoId },\n { $pull: { refpaths: { repoId } } },\n { multi: true },\n );\n volume.remove({ refpaths: [] });\n catalogs.update(catalogId, {\n $pull: { [`${stage}.repos`]: { repoId } },\n $addToSet: { [`${stage}.deletedRepos`]: repoId },\n });\n\n logger.log(\n `[nog-catalog] Completed entry cleanup for ` +\n `deleted repo \\`${repoFullname}\\`.`,\n );\n });\n\n // XXX Repos that may not be accessed are ignored. The behavior is\n // undefined when access permissions change. The current\n // implementation preserves catalog items if the repo has been indexed\n // before.\n\n contentStore.repos.find(repoSelector).forEach((repo) => {\n renewLock();\n\n const haveAccess = testAccess(euid, AA_GET_CONTENT, {\n ownerName: repo.owner,\n repoName: repo.name,\n });\n if (!haveAccess) {\n logger.log(\n `[nog-catalog] Ignored repo \\`${repo.owner}/${repo.name}\\` ` +\n 'without access.',\n );\n return;\n }\n\n const repoId = repo._id;\n const commit = repo.refs['branches/master'];\n const sel = {\n _id: catalogId,\n [`${stage}.repos`]: { repoId, commit },\n };\n if (catalogs.findOne(sel)) {\n return; // Already up-to-date.\n }\n addContentRepoSudo({\n contentStore, repo, volume, fieldManager, pipelineFuncs, logger,\n renewLock, rateLimiters,\n });\n volume.remove({ refpaths: [] });\n catalogs.update(catalogId, {\n $addToSet: { [`${stage}.repos`]: { repoId, commit } },\n });\n catalogs.update(catalogId, {\n $pull: { [`${stage}.repos`]: { repoId, commit: { $ne: commit } } },\n });\n });\n }\n\n const volumeRaw = volume.rawCollection();\n volumeRaw.indexesSync = Meteor.wrapAsync(volumeRaw.indexes, volumeRaw);\n\n const currentIndexes = new Set(\n volumeRaw.indexesSync().map(idx => idx.name),\n );\n const desiredIndexes = new Set(fieldManager.getMongoIndexFields());\n\n for (const idx of currentIndexes) {\n renewLock();\n if (idx === 'text') {\n continue; // eslint-disable-line no-continue\n }\n if (fieldManager.isMongoFieldName(idx) && !desiredIndexes.has(idx)) {\n volume._dropIndex(idx);\n logger.log(`[nog-catalog] Dropped index ${idx}`);\n }\n }\n\n if (!currentIndexes.has('text')) {\n volume._ensureIndex({ '$**': 'text' }, { name: 'text' });\n }\n for (const idx of desiredIndexes) {\n renewLock();\n if (!currentIndexes.has(idx)) {\n volume._ensureIndex({ [`m.${idx}`]: 1 }, { name: idx });\n }\n }\n\n renewLock();\n volume._ensureIndex({ name: 1 });\n renewLock();\n volume._ensureIndex({ 'refpaths.repoId': 1 });\n\n const memoState = catalogs.findOne(catalogId, {\n fields: {\n [`${stage}.metaKeyCountsMemoHash`]: 1,\n [`${stage}.configHash`]: 1,\n [`${stage}.repos`]: 1,\n [`${stage}.deletedRepos`]: 1,\n },\n })[stage];\n const memoArgs = {\n configHash: memoState.configHash,\n repos: _.sortBy(memoState.repos, r => r.repoId),\n deletedRepos: _.sortBy(memoState.deletedRepos),\n };\n const memoHash = sha1Hex(EJSON.stringify(memoArgs, { canonical: true }));\n\n if (memoState.metaKeyCountsMemoHash !== memoHash) {\n const metaKeyCounts = {};\n for (const f of fieldManager.getMongoFields()) {\n renewLock();\n const cnt = volume.find({ [`m.${f}`]: { $exists: true } }).count();\n metaKeyCounts[f] = cnt;\n }\n catalogs.update(catalogId, {\n $set: {\n [`${stage}.metaKeyCounts`]: metaKeyCounts,\n [`${stage}.metaKeyCountsMemoHash`]: memoHash,\n },\n });\n }\n\n renewLock();\n if (stage === 'building') {\n if (catalog.active && catalog.active.volumes) {\n catalogs.update(catalogId, {\n $addToSet: { retiredVolumes: { $each: catalog.active.volumes } },\n });\n }\n\n catalogs.update(catalogId, { $rename: { building: 'active' } });\n }\n\n renewLock();\n dropRetiredVolumes({ catalogs, logger });\n\n lock.unlock();\n\n logger.log(\n `[nog-catalog] Completed catalog update: serial ${catalog.serial}, ` +\n `config hash ${configHash}.`,\n );\n\n return {\n status: 'ok',\n messages: logger.messages,\n };\n }\n\n const mod = {\n catalogs,\n volumes,\n\n registerPlugin(plug) {\n plugins.register(plug);\n },\n\n registerNogSuggest(plug) {\n nogSuggest = plug;\n },\n\n updateCatalog(euid, { ownerName, repoName }) {\n check(ownerName, matchSimpleName);\n check(repoName, matchSimpleName);\n\n checkAccess(euid, AA_UPDATE_CATALOG, { ownerName, repoName });\n\n const { _id: catalogId } = contentStore.repos.findOne(\n { owner: ownerName, name: repoName },\n { fields: { _id: 1 } },\n );\n if (!catalogId) {\n nogthrow(ERR_REPO_MISSING);\n }\n\n const config = getCatalogConfig({\n contentStore, euid, ownerName, repoName,\n });\n const nameDetails = { owner: ownerName, name: repoName };\n\n return updateCatalogCommon(euid, {\n catalogId, config, nameDetails,\n });\n },\n\n updateCatalogFso(euid, opts) {\n check(opts, {\n repoPath: String,\n selectRepos: Match.Optional([matchUuidStringOrBinary]),\n });\n\n if (!plugins.fso) {\n nogthrow(ERR_UNIMPLEMENTED, {\n reason: 'The fso catalog plugin is disabled.',\n });\n }\n\n // The plugin calls `checkAccess()`.\n const { repoPath } = opts;\n const {\n catalogId, config, nameDetails,\n } = plugins.fso.getCatalogConfig(euid, { repoPath });\n\n function parseSelectRepos() {\n if (!opts.selectRepos) {\n return null;\n }\n return opts.selectRepos.map((id) => {\n if (typeof id === 'string') {\n return Buffer.from(id.replace(/-/g, ''), 'hex');\n }\n return Buffer.from(id);\n });\n }\n\n const options = {\n fsoSelectRepos: parseSelectRepos(),\n };\n return updateCatalogCommon(euid, {\n catalogId, config, nameDetails, options,\n });\n },\n\n configureCatalog(euid, {\n ownerName, repoName, catalogConfig,\n }) {\n check(ownerName, matchSimpleName);\n check(repoName, matchSimpleName);\n check(catalogConfig, matchCatalogConfig);\n\n checkAccess(euid, AA_CONFIGURE_CATALOG, {\n ownerName, repoName, catalogConfig,\n });\n const refName = 'branches/master';\n const refs = contentStore.getRefs(euid, { ownerName, repoName });\n const master = refs[refName];\n const commit = contentStore.getCommit(euid, {\n ownerName, repoName, sha1: master,\n });\n const tree = contentStore.getTree(euid, {\n ownerName, repoName, sha1: commit.tree,\n });\n\n const content = _.pick(tree, 'name', 'entries', 'meta');\n content.meta = { ...tree.meta };\n content.meta.catalog = {\n config: EJSON.stringify(catalogConfig, { canonical: true }),\n };\n const newTreeId = contentStore.createTree(euid, {\n ownerName, repoName, content,\n });\n\n const newCommitId = contentStore.createCommit(euid, {\n ownerName, repoName,\n content: {\n subject: 'Configure catalog',\n message: '',\n meta: {},\n parents: [master],\n tree: newTreeId,\n },\n });\n contentStore.updateRef(euid, {\n ownerName, repoName, refName, new: newCommitId, old: master,\n });\n },\n\n updateSuggestionsFromCatalog(euid, opts) {\n check(opts, {\n repoPath: String,\n mdNamespace: String,\n sugNamespaces: [String],\n });\n const { repoPath, mdNamespace, sugNamespaces } = opts;\n\n // XXX We should probably use a different AA here when NogSuggest\n // supports per-group suggestions.\n checkAccess(euid, AA_FSO_UPDATE_CATALOG, { path: repoPath });\n\n // Create `inserter` early, since it performs additional access checks.\n const inserter = nogSuggest.createPropertyInserter(euid, {\n mdNamespace, sugNamespaces,\n });\n\n const catalog = catalogs.findOne(\n { fsoPath: repoPath },\n {\n fields: {\n 'active.metaKeys': 1,\n 'active.serial': 1,\n },\n },\n );\n if (!catalog || !catalog.active) {\n nogthrow(ERR_REPO_MISSING);\n }\n const { _id: catalogId } = catalog;\n const { serial, metaKeys } = catalog.active;\n\n const volumeName = makeCollName(\n namespace, `catalogs.vol_${catalogId}_${serial}`,\n );\n const volume = volumes[volumeName];\n if (!volume) {\n nogthrow(ERR_REPO_MISSING);\n }\n\n const learner = nogSuggest.createPropertyTypeLearner();\n volume.find({}).forEach((doc) => {\n for (const [k, values] of Object.entries(doc.m)) {\n const property = metaKeys[Number(k.substr(1))];\n learner.update({ property, values });\n }\n });\n\n inserter.insertKnownProperties({\n properties: learner.predict({ threshold: 0.5, minCount: 1 }),\n });\n\n let nCandidates = 0;\n let nInserted = 0;\n volume.find({}).forEach((doc) => {\n for (const [k, values] of Object.entries(doc.m)) {\n nCandidates += values.length;\n const property = metaKeys[Number(k.substr(1))];\n nInserted += inserter.insertKnownPropertyValues({\n propertySymbol: property,\n values,\n });\n }\n });\n\n return (\n `Inserted ${nInserted} of ${nCandidates} suggestion candidates.`\n );\n },\n };\n\n defCatalogMethods({ namespace, mod });\n\n function publishCatalog({ ownerName, repoName }) {\n check(ownerName, matchSimpleName);\n check(repoName, matchSimpleName);\n\n if (!testAccess(this.userId, AA_GET_CONTENT, { ownerName, repoName })) {\n this.ready();\n return null;\n }\n\n return catalogs.find(\n { owner: ownerName, name: repoName },\n { fields: { owner: 1, name: 1, active: 1 } },\n );\n }\n\n function publishCatalogHitCount({\n ownerName, repoName, volumeName, filter,\n }) {\n check(ownerName, matchSimpleName);\n check(repoName, matchSimpleName);\n check(volumeName, matchCatalogVolumeName);\n check(filter, String);\n\n const euid = this.userId;\n const vol = findCatalogVolume(euid, { ownerName, repoName, volumeName });\n if (!vol) {\n console.error(`[nog-catalog] Did not find volume \\`${volumeName}\\`.`);\n this.ready();\n return null;\n }\n\n const query = compileQuery(filter);\n return new Counter(volumeName, vol.find(query));\n }\n\n function publishCatalogVolume({\n ownerName, repoName, volumeName, filter,\n }) {\n check(ownerName, matchSimpleName);\n check(repoName, matchSimpleName);\n check(volumeName, matchCatalogVolumeName);\n check(filter, String);\n\n const euid = this.userId;\n const vol = findCatalogVolume(euid, { ownerName, repoName, volumeName });\n if (!vol) {\n console.error(`[nog-catalog] Did not find volume \\`${volumeName}\\`.`);\n this.ready();\n return null;\n }\n\n const query = compileQuery(filter);\n return vol.find(query, {\n sort: { name: 1 },\n limit: 50,\n });\n }\n\n function publishCatalogVolumeStats({\n ownerName, repoName, volumeName, field, limit,\n }) {\n check(ownerName, matchSimpleName);\n check(repoName, matchSimpleName);\n check(volumeName, matchCatalogVolumeName);\n check(field, matchMetaFieldName);\n check(limit, matchPositiveNumber);\n\n const euid = this.userId;\n const volume = findCatalogVolume(euid, {\n ownerName, repoName, volumeName,\n });\n if (!volume) {\n console.error(`[nog-catalog] Did not find volume \\`${volumeName}\\`.`);\n this.ready();\n return null;\n }\n\n const statsName = `${volumeName}.stats`;\n const volumeRaw = volume.rawCollection();\n volume.aggregateSync = Meteor.wrapAsync(volumeRaw.aggregate, volumeRaw);\n\n // XXX The topk may contain spurious counts while the volume is updated,\n // since old entries are added long before new entries are finally removed.\n // The volume, therefore, may contain old and new entries at the same time.\n\n // XXX The stats won't reactively update on the client if the volume\n // changes. We accept this for now. An alternative would be to recompute\n // and resend them every x seconds. Or we could implement logic on the\n // client to resubscribe if the databank state changes. Or this\n // publication could observe something like `databank.active.xMemoHash` to\n // get notified when a volume update completes. We could probably use\n // package `jcbernack:reactive-aggregate` to automate observe.\n\n // `$unwind` has been changed in MongoDB 3.2 to work on scalar values. For\n // MongoDB < 3.2, `$unwind` fails on scalars. `addContentRepoSudo()`\n // forces all values to arrays, so that `$unwind` can be used\n // unconditionally here also with MongoDB < 3.2.\n const topk = volume.aggregateSync([\n { $unwind: `$m.${field}` },\n { $group: { _id: `$m.${field}`, cnt: { $sum: 1 } } },\n { $sort: { cnt: -1 } },\n { $limit: Math.min(limit + 5, 1000) },\n ]);\n\n let nAdded = 0;\n topk.forEach((t) => {\n if (nAdded < limit && t._id != null) {\n this.added(statsName, `${field}:${t._id}`, {\n field, val: t._id, count: t.cnt,\n });\n nAdded += 1;\n }\n });\n\n this.ready();\n return null;\n }\n\n function publishCatalogFso({ repoPath }) {\n check(repoPath, String);\n\n if (!testAccess(this.userId, AA_FSO_READ_REPO, { path: repoPath })) {\n this.ready();\n return null;\n }\n\n return catalogs.find(\n { fsoPath: repoPath },\n { fields: { fsoPath: 1, active: 1 } },\n );\n }\n\n function publishCatalogHitCountFso({ repoPath, volumeName, filter }) {\n check(repoPath, String);\n check(volumeName, matchCatalogVolumeName);\n check(filter, String);\n\n const euid = this.userId;\n const vol = findCatalogVolumeFso(euid, { repoPath, volumeName });\n if (!vol) {\n console.error(`[nog-catalog] Did not find volume \\`${volumeName}\\`.`);\n this.ready();\n return null;\n }\n\n const query = compileQuery(filter);\n return new Counter(volumeName, vol.find(query));\n }\n\n function publishCatalogVolumeFso({ repoPath, volumeName, filter }) {\n check(repoPath, String);\n check(volumeName, matchCatalogVolumeName);\n check(filter, String);\n\n const euid = this.userId;\n const vol = findCatalogVolumeFso(euid, { repoPath, volumeName });\n if (!vol) {\n console.error(`[nog-catalog] Did not find volume \\`${volumeName}\\`.`);\n this.ready();\n return null;\n }\n\n const query = compileQuery(filter);\n return vol.find(query, {\n sort: { name: 1 },\n limit: 50,\n });\n }\n\n function publishCatalogVolumeStatsFso({\n repoPath, volumeName, field, limit,\n }) {\n check(repoPath, String);\n check(volumeName, matchCatalogVolumeName);\n check(field, matchMetaFieldName);\n check(limit, matchPositiveNumber);\n\n const euid = this.userId;\n const vol = findCatalogVolumeFso(euid, { repoPath, volumeName });\n if (!vol) {\n console.error(`[nog-catalog] Did not find volume \\`${volumeName}\\`.`);\n this.ready();\n return null;\n }\n\n const statsName = `${volumeName}.stats`;\n const volRaw = vol.rawCollection();\n vol.aggregateSync = Meteor.wrapAsync(volRaw.aggregate, volRaw);\n\n // XXX The topk may contain spurious counts while the volume is updated,\n // since old entries are added long before new entries are finally removed.\n // The volume, therefore, may contain old and new entries at the same time.\n\n // XXX The stats won't reactively update on the client if the volume\n // changes. We accept this for now. An alternative would be to recompute\n // and resend them every x seconds. Or we could implement logic on the\n // client to resubscribe if the databank state changes. Or this\n // publication could observe something like `databank.active.xMemoHash` to\n // get notified when a volume update completes. We could probably use\n // package `jcbernack:reactive-aggregate` to automate observe.\n\n // `$unwind` has been changed in MongoDB 3.2 to work on scalar values. For\n // MongoDB < 3.2, `$unwind` fails on scalars. `addContentRepoSudo()`\n // forces all values to arrays, so that `$unwind` can be used\n // unconditionally here also with MongoDB < 3.2.\n const topk = vol.aggregateSync([\n { $unwind: `$m.${field}` },\n { $group: { _id: `$m.${field}`, cnt: { $sum: 1 } } },\n { $sort: { cnt: -1 } },\n { $limit: Math.min(limit + 5, 1000) },\n ]);\n\n let nAdded = 0;\n topk.forEach((t) => {\n if (nAdded < limit && t._id != null) {\n this.added(statsName, `${field}:${t._id}`, {\n field, val: t._id, count: t.cnt,\n });\n nAdded += 1;\n }\n });\n\n this.ready();\n return null;\n }\n\n const pubs = {\n // nog-content\n catalog: publishCatalog,\n catalogHitCount: publishCatalogHitCount,\n catalogVolume: publishCatalogVolume,\n catalogVolumeStats: publishCatalogVolumeStats,\n // fso\n catalogFso: publishCatalogFso,\n catalogHitCountFso: publishCatalogHitCountFso,\n catalogVolumeFso: publishCatalogVolumeFso,\n catalogVolumeStatsFso: publishCatalogVolumeStatsFso,\n };\n for (const [name, fn] of _.pairs(pubs)) {\n Meteor.publish(makePubName(namespace, name), fn);\n }\n\n return mod;\n}\n\n\nexport {\n createCatalogServerModule,\n matchCatalogConfig,\n};", "dangerousExampleEn": "1. var md5 = require('md5');\n2. \n3. console.log(md5('password'));\nLine 3: This is weak for the brute-force attack because it uses md5, a weak hash function.", "safeExampleEn": "1. var bcrypt = require('bcrypt');\n2. \n3. bcrypt.hash(\"password\", 13, function(err, hash) {\n4. console.log(hash);\n5. });\nLine 3: This is safe from the brute-force attack because bcrypt is used to create hash data.", "contexts": [{"lineNo": 106, "eventType": "sink", "messageKey": "jschk.FORBIDDEN.WEAK_ALGORITHM.JS.defect", "params": {"arg0": "sha1"}}]}} {"id": "23e0a2cad8165775eab2a72fdd8eb86070e1bd19f15cf278660cd4ed4be79292", "license": {"spdx": ["MIT"], "repo": "mygnet/aif-db", "path": "src/index.js", "repo_head_hexsha": "bc2b2603fc48d674ab8307c3a6581c26e6f60fbb", "stack_hexsha": "6be0d5afed148f30a03d1d22eb4aeea0efee15a7", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of weak cryptographic algorithm", "issueDescriptionEn": "A hash function is a one-way function that receives data of different lengths and maps it to random data of a fixed length. It is commonly used to store user passwords because it always produces the same output for a given input.\nBecause hash can be calculated very quickly, the hash functions, such as MD5 and SHA, may give the illusion of high performance. However they are vulnerable to random brute-force attacks. If you use the hash functions on simple data, they can be saved in the rainbow table, making it insecure. In addition, RC2, RC3, RC4, RC5, RC6, MD4, and DES are also known to be vulnerable.\nThere are many functions used to overcome the disadvantages of MD5 and SHA.\nIn Node.js, bcrypt is one of the functions that is commonly used with outstanding performance and easily replace them. The latest hash algorithms, such as Argon2, PBKDF2, and Scrypt, are also good alternatives. Make sure to add a salt to the hash in SHA-2 i.e. SHA-224, SHA-256, SHA-384, SHA-512.", "issueLineNumber": 32, "entireCode": "import { md5, Aes } from 'aif-cipher'\nimport { split } from 'aif-str'\nimport path from 'path'\nimport fs from 'fs'\nimport shelljs from 'shelljs'\n\nmodule.exports = class DataBase {\n /**\n * DataBase constructor\n * @param {string} dir path where the database file is stored\n * @param {string} name database name\n * @param {string} key secret word for encryption\n * @param {string} table name of the default tab\n */\n constructor(dir, name, key, table) {\n this.key = key || null\n this.id = null\n this.name = this.hash(name)\n this.path = path.join(dir, this.name)\n this.table = table || 'table'\n this.lastError = ''\n if (!fs.existsSync(this.path)) {\n shelljs.mkdir('-p', this.path)\n }\n }\n /**\n * calculates a hash of a data\n * @param {string} data Data\n * @returns 32 character hash string\n */\n hash(data) {\n return this.key ? md5(data + this.key) : data\n }\n /**\n * Generate the identifier in a database hash string\n * @param {string} database identifier id\n * @returns id in database hash format\n */\n idHash(id) {\n id = id || this.id\n if (id) {\n this.id = id\n return this.hash(id)\n }\n return null\n }\n /**\n * Returns the path given an identifier of the database and a table\n * @param {*} [id] Database identifier\n * @param {string} [table] Table name\n * @returns Returns the path\n */\n dir(id, table) {\n id = id || this.id\n if (id) {\n this.id = id\n table = table || this.table\n table = this.hash(table)\n return path.join(this.path, table) + path.sep + split(id + '', 2).join(path.sep)\n }\n return null\n }\n /**\n * Returns the path of a file given the name and identifier of the database\n * @param {string} [name] File name\n * @param {*} [id] Database identifier\n * @returns Returns the path of a file\n */\n file(name, id) {\n id = id || this.id\n name = name || this.table\n name = this.hash(name)\n if (id) {\n this.id = id\n return this.dir(id) + path.sep + name\n }\n return null\n }\n /**\n * Save information in a file in the database path\n * @param {string} data Content\n * @param {string} name File name\n * @returns Returns true if successful\n */\n saveFile(data, name) {\n if (fs.existsSync(content)) {\n data = fs.readFileSync(data, { encoding: 'utf8' })\n }\n data = data || ''\n name = name || this.table\n name = this.hash(name)\n let error = null\n try {\n data = typeof data === 'object' ? JSON.stringify(data) : data\n data = this.key ? Aes.encode(data, this.key) : data\n name = this.dir() + path.sep + name\n fs.writenameSync(name, data, { encoding: 'utf8' })\n } catch (err) {\n this.lastError = err.toString()\n error = err\n }\n return !!error\n }\n /**\n * Retrieves information from a file\n * @param {string} name File name\n * @returns File content\n */\n loadFile(name) {\n name = name || this.table\n name = this.hash(name)\n name = this.dir() + path.sep + name\n let content = null\n let error = null\n if (fs.existsSync(name)) {\n try {\n content = fs.readnameSync(name, { encoding: 'utf8' })\n content = this.key ? Aes.decode(content, this.key) : content\n content = JSON.parse(content)\n } catch (err) {\n this.lastError = err.toString()\n content = null\n error = err\n }\n } else this.lastError = 'database failed to connect ';\n return content\n }\n /**\n *\n * @param {objet} record Object in json format with fields\n * @param {string} table Table name\n * @param {function} callback Function to be invoked to terminate the process\n */\n put(record, table, callback) {\n let id = record._id\n if (typeof record === 'object') {\n if (typeof table === 'function') {\n callback = table\n } else {\n this.table = table || this.table\n }\n if (id) {\n id = id + ''\n const dir = this.dir(id)\n let content = null\n let error = null\n try {\n content = JSON.stringify(record)\n content = this.key ? Aes.encode(content, this.key) : content\n } catch (err) {\n error = err\n }\n if (error) return callback(null, error, id)\n if (!fs.existsSync(dir)) {\n shelljs.mkdir('-p', dir)\n }\n const file = path.join(dir, this.hash(id))\n try {\n fs.writeFileSync(file, content, { encoding: 'utf8' })\n content = id\n } catch (err) {\n error = err\n content = null\n }\n callback(content, error, id)\n } else {\n callback(false, 'A table identifier (._id) is required', id)\n }\n } else {\n callback(false, 'Data object is required', id)\n }\n }\n /**\n * Retrieves a record in json (object) format\n * @param {*} id record identifier\n * @param {string} table Table name\n * @param {function} callback Function that is invoked to return the data\n */\n get(id, table, callback) {\n if (typeof table === 'function') {\n callback = table\n } else {\n this.table = table || this.table\n }\n if (id) {\n id = id + ''\n const file = this.dir(id) + path.sep + this.hash(id)\n let content = null\n let error = null\n if (fs.existsSync(file)) {\n content = fs.readFileSync(file, { encoding: 'utf8' })\n try {\n content = this.key ? Aes.decode(content, this.key) : content\n content = JSON.parse(content)\n } catch (err) {\n content = null\n error = err\n }\n callback(content, error, id)\n } else {\n callback(false, 'Record with identifier does not exist', id)\n }\n }\n }\n /**\n * Process to reorganize and clean the database\n * @param {string} dir path where the database is located\n * @returns\n */\n vacum(dir) {\n if(dir) {\n if (!fs.statSync(dir).isDirectory()) {\n return\n }\n let files = fs.readdirSync(dir)\n if (files.length > 0) {\n files.forEach(file => {\n this.vacum(path.join(dir, file))\n })\n files = fs.readdirSync(dir)\n }\n if (files.length === 0) {\n fs.rmdirSync(dir)\n return\n }\n }\n }\n /**\n * Remove a record from the database\n * @param {*} record identifier id\n * @param {string} table Database name\n * @param {function} callback Function that is invoked at the end of the process\n */\n remove(id, table, callback) {\n if (typeof table === 'function') {\n callback = table\n table = this.table\n }\n table = this.hash(table)\n if (id) {\n id = id + ''\n const file = this.dir(id) + path.sep + this.hash(id)\n if (fs.existsSync(file)) {\n fs.unlinkSync(file)\n this.vacum(path.join(this.path, table))\n callback(true)\n } else {\n callback(false, 'The record with identifier does not exist', id)\n }\n }\n }\n /**\n * Save changes to a record by means of the identifier\n * @param {object} record Data record in json format\n * @param {string} table Table name\n * @param {function} callback Function that is invoked at the end of the process\n */\n save(record, table, callback) {\n if (typeof table === 'function') {\n callback = table\n table = this.table\n }\n this.get(record._id, table, (rs, err) => {\n if (rs) {\n for (const key in rs) {\n if (record[key] !== undefined) {\n rs[key] = record[key]\n }\n }\n this.put(rs, table, callback)\n } else {\n this.put(record, table, callback)\n }\n })\n }\n}", "dangerousExampleEn": "1. var md5 = require('md5');\n2. \n3. console.log(md5('password'));\nLine 3: This is weak for the brute-force attack because it uses md5, a weak hash function.", "safeExampleEn": "1. var bcrypt = require('bcrypt');\n2. \n3. bcrypt.hash(\"password\", 13, function(err, hash) {\n4. console.log(hash);\n5. });\nLine 3: This is safe from the brute-force attack because bcrypt is used to create hash data.", "contexts": [{"lineNo": 32, "eventType": "sink", "messageKey": "jschk.FORBIDDEN.WEAK_ALGORITHM.JS.defect", "params": {"arg0": "md5"}}]}} {"id": "e3553d5bfd315a336e22f0c7bde487f2fb0aeeb3d3a5ceca50df5881123c96ba", "license": {"spdx": ["MIT"], "repo": "Luphia/DValue", "path": "DValue.js", "repo_head_hexsha": "98bc706b9970e8c9a89c42da68f56ddd572c551d", "stack_hexsha": "906582ad4997ff489b6cf4a63eeb9ddf60c72076", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of weak cryptographic algorithm", "issueDescriptionEn": "A hash function is a one-way function that receives data of different lengths and maps it to random data of a fixed length. It is commonly used to store user passwords because it always produces the same output for a given input.\nBecause hash can be calculated very quickly, the hash functions, such as MD5 and SHA, may give the illusion of high performance. However they are vulnerable to random brute-force attacks. If you use the hash functions on simple data, they can be saved in the rainbow table, making it insecure. In addition, RC2, RC3, RC4, RC5, RC6, MD4, and DES are also known to be vulnerable.\nThere are many functions used to overcome the disadvantages of MD5 and SHA.\nIn Node.js, bcrypt is one of the functions that is commonly used with outstanding performance and easily replace them. The latest hash algorithms, such as Argon2, PBKDF2, and Scrypt, are also good alternatives. Make sure to add a salt to the hash in SHA-2 i.e. SHA-224, SHA-256, SHA-384, SHA-512.", "issueLineNumber": 384, "entireCode": "const { isArray } = require('util');\n\nconst sprintf = (function() {\n function get_type(variable) {\n return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();\n }\n function str_repeat(input, multiplier) {\n for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */}\n return output.join('');\n }\n\n var str_format = function() {\n if (!str_format.cache.hasOwnProperty(arguments[0])) {\n str_format.cache[arguments[0]] = str_format.parse(arguments[0]);\n }\n return str_format.format.call(null, str_format.cache[arguments[0]], arguments);\n };\n\n str_format.object_stringify = function(obj, depth, maxdepth, seen) {\n var str = '';\n if (obj != null) {\n switch( typeof(obj) ) {\n case 'function':\n return '[Function' + (obj.name ? ': '+obj.name : '') + ']';\n break;\n case 'object':\n if ( obj instanceof Error) { return '[' + obj.toString() + ']' };\n if (depth >= maxdepth) return '[Object]'\n if (seen) {\n // add object to seen list\n seen = seen.slice(0)\n seen.push(obj);\n }\n if (obj.length != null) { //array\n str += '[';\n var arr = []\n for (var i in obj) {\n if (seen && seen.indexOf(obj[i]) >= 0) arr.push('[Circular]');\n else arr.push(str_format.object_stringify(obj[i], depth+1, maxdepth, seen));\n }\n str += arr.join(', ') + ']';\n } else if ('getMonth' in obj) { // date\n return 'Date(' + obj + ')';\n } else { // object\n str += '{';\n var arr = []\n for (var k in obj) {\n if(obj.hasOwnProperty(k)) {\n if (seen && seen.indexOf(obj[k]) >= 0) arr.push(k + ': [Circular]');\n else arr.push(k +': ' +str_format.object_stringify(obj[k], depth+1, maxdepth, seen));\n }\n }\n str += arr.join(', ') + '}';\n }\n return str;\n break;\n case 'string':\n return '\"' + obj + '\"';\n break;\n }\n }\n return '' + obj;\n }\n\n str_format.format = function(parse_tree, argv) {\n var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length;\n for (i = 0; i < tree_length; i++) {\n node_type = get_type(parse_tree[i]);\n if (node_type === 'string') {\n output.push(parse_tree[i]);\n }\n else if (node_type === 'array') {\n match = parse_tree[i]; // convenience purposes only\n if (match[2]) { // keyword argument\n arg = argv[cursor];\n for (k = 0; k < match[2].length; k++) {\n if (!arg.hasOwnProperty(match[2][k])) {\n throw new Error(sprintf('[sprintf] property \"%s\" does not exist', match[2][k]));\n }\n arg = arg[match[2][k]];\n }\n }\n else if (match[1]) { // positional argument (explicit)\n arg = argv[match[1]];\n }\n else { // positional argument (implicit)\n arg = argv[cursor++];\n }\n\n if (/[^sO]/.test(match[8]) && (get_type(arg) != 'number')) {\n throw new Error(sprintf('[sprintf] expecting number but found %s \"' + arg + '\"', get_type(arg)));\n }\n switch (match[8]) {\n case 'b': arg = arg.toString(2); break;\n case 'c': arg = String.fromCharCode(arg); break;\n case 'd': arg = parseInt(arg, 10); break;\n case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break;\n case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break;\n case 'O': arg = str_format.object_stringify(arg, 0, parseInt(match[7]) || 5); break;\n case 'o': arg = arg.toString(8); break;\n case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break;\n case 'u': arg = Math.abs(arg); break;\n case 'x': arg = arg.toString(16); break;\n case 'X': arg = arg.toString(16).toUpperCase(); break;\n }\n arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg);\n pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' ';\n pad_length = match[6] - String(arg).length;\n pad = match[6] ? str_repeat(pad_character, pad_length) : '';\n output.push(match[5] ? arg + pad : pad + arg);\n }\n }\n return output.join('');\n };\n\n str_format.cache = {};\n\n str_format.parse = function(fmt) {\n var _fmt = fmt, match = [], parse_tree = [], arg_names = 0;\n while (_fmt) {\n if ((match = /^[^\\x25]+/.exec(_fmt)) !== null) {\n parse_tree.push(match[0]);\n }\n else if ((match = /^\\x25{2}/.exec(_fmt)) !== null) {\n parse_tree.push('%');\n }\n else if ((match = /^\\x25(?:([1-9]\\d*)\\$|\\(([^\\)]+)\\))?(\\+)?(0|'[^$])?(-)?(\\d+)?(?:\\.(\\d+))?([b-fosOuxX])/.exec(_fmt)) !== null) {\n if (match[2]) {\n arg_names |= 1;\n var field_list = [], replacement_field = match[2], field_match = [];\n if ((field_match = /^([a-z_][a-z_\\d]*)/i.exec(replacement_field)) !== null) {\n field_list.push(field_match[1]);\n while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {\n if ((field_match = /^\\.([a-z_][a-z_\\d]*)/i.exec(replacement_field)) !== null) {\n field_list.push(field_match[1]);\n }\n else if ((field_match = /^\\[(\\d+)\\]/.exec(replacement_field)) !== null) {\n field_list.push(field_match[1]);\n }\n else {\n throw new Error('[sprintf] ' + replacement_field);\n }\n }\n }\n else {\n throw new Error('[sprintf] ' + replacement_field);\n }\n match[2] = field_list;\n }\n else {\n arg_names |= 2;\n }\n if (arg_names === 3) {\n throw new Error('[sprintf] mixing positional and named placeholders is not (yet) supported');\n }\n parse_tree.push(match);\n }\n else {\n throw new Error('[sprintf] ' + _fmt);\n }\n _fmt = _fmt.substring(match[0].length);\n }\n return parse_tree;\n };\n\n return str_format;\n})();\n\nclass dvalue {\n\tstatic clone(obj) {\n let rs;\n if(typeof obj != 'object') {\n rs = obj;\n }\n else {\n \n if(Array.isArray(obj)) {\n rs = obj.map((k, v) => this.clone(v));\n }\n else {\n rs = Object.keys(obj).reduce((prev, curr) => {\n prev[curr] = this.clone(obj[curr]);\n return prev;\n }, {});\n }\n }\n return rs;\n }\n\n static guid() {\n var s4 = function() {\n return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);\n };\n return s4() + s4() + '-' + s4() + '-' + s4() + '-' +s4() + '-' + s4() + s4() + s4();\n }\n\n static randomID(n) {\n var ID = '';\n var text = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';\n n = parseInt(n);\n if(!(n > 0)) { n = 8; }\n while(ID.length < n) {\n ID = ID.concat(text.charAt(parseInt(Math.random() * text.length)));\n }\n return ID;\n }\n\n static randomCode(n, options) {\n var code = '', tmparr = [], tmpstring, text = ['0123456789', 'abcdefghijklmnopqrstuvwxyz', 'ABCDEFGHIJKLMNOPQRSTUVWXY', '~!@#$%^&*()_+-=,./<>?;:[]{}|\\\\/\\'\"'];\n if(!(n > 0)) { n = 8; }\n options = options || {number: 1, lower: 1, upper: 0, symbol: 0};\n for(var k = 0; k < options.number; k++) { tmparr.push(text[0]); }\n for(var k = 0; k < options.lower; k++) { tmparr.push(text[1]); }\n for(var k = 0; k < options.upper; k++) { tmparr.push(text[2]); }\n for(var k = 0; k < options.symbol; k++) { tmparr.push(text[3]); }\n tmpstring = tmparr.join('');\n while(code.length < n) {\n code = code.concat(tmpstring.charAt(parseInt(Math.random() * tmpstring.length)));\n }\n return code;\n }\n\n static randomPick(arr, n) {\n if(!Array.isArray(arr)) { return []; }\n var tmp = this.clone(arr);\n var rs = [];\n while(tmp.length > 0 && rs.length < n) {\n rs.push(tmp.splice(Math.floor(Math.random() * tmp.length), 1)[0]);\n }\n \n return rs;\n };\n \n static merge() {\n var rs = [];\n for(var k in arguments) {\n if(Array.isArray(arguments[k])) { arguments[k].map(function (v, i) { if(typeof(v) != 'undefined') { rs.push(v); } }); }\n else if(typeof(arguments[k]) != 'undefined') { rs.push(arguments[k]); }\n }\n return rs;\n };\n \n static distinct(arr) {\n if(!Array.isArray(arr)) { return; }\n return arr.filter(function (v, i, self) { return self.indexOf(v) === i; });\n };\n \n static default(config, defaultConfig) {\n if(typeof(defaultConfig) == 'object' && defaultConfig != null) {\n if(config == undefined) { config = Array.isArray(defaultConfig)? []: {}; }\n for(var k in defaultConfig) {\n var v = defaultConfig[k];\n if(typeof(v) == 'object') { config[k] = this.default(config[k], v); }\n else if(config[k] === undefined) { config[k] = v; }\n }\n }\n else {\n if(config == undefined) { config = defaultConfig; }\n }\n \n return config;\n };\n \n static shuffle(arr) {\n var j, x, i;\n for (i = (arr.length - 1); i; i--) {\n j = Math.floor(Math.random() * arr.length);\n x = arr[i];\n arr[i] = arr[j];\n arr[j] = x;\n }\n return arr;\n };\n \n static sprintf(...args) {\n return sprintf(...args);\n }\n \n static displayByte(n, unit) {\n var unit = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];\n var base = 1024;\n var n = parseInt(n) > 0? parseInt(n): 0;\n var pow = parseInt(n) > 0? parseInt(Math.log(n) / Math.log(1024)): 0;\n var v, u;\n if(unit[pow]) {\n u = unit[pow]\n }\n else {\n pow = unit.length - 1;\n u = unit[pow];\n }\n v = parseInt(n / Math.pow(1024, pow) * 100) / 100;\n return [v, u];\n };\n \n static search(arr, obj) {\n if(Array.isArray(obj) && !Array.isArray(arr)) { return this.search(obj, arr); }\n var isMapping = function (obj1, obj2) {\n if(obj2 === undefined) { return false; }\n else if(typeof(obj1) == 'object') {\n for(var k in obj1) {\n if(!isMapping(obj1[k], obj2[k])) { return false; }\n }\n return true;\n }\n else {\n return obj1 == obj2;\n }\n };\n for(var i in arr) {\n if(isMapping(obj, arr[i])) { return arr[i]; }\n }\n };\n \n static multiSearch(arr, obj) {\n if(Array.isArray(obj) && !Array.isArray(arr)) { return this.multiSearch(obj, arr); }\n var result = [];\n var isMapping = function (obj1, obj2) {\n if(obj2 === undefined) { return false; }\n else if(typeof(obj1) == 'object') {\n for(var k in obj1) {\n if(!isMapping(obj1[k], obj2[k])) { return false; }\n }\n return true;\n }\n else {\n return obj1 == obj2;\n }\n };\n for(var i in arr) {\n if(isMapping(obj, arr[i])) { result.push(arr[i]); }\n }\n return result;\n };\n \n static XOR(content, key) {\n if(!Buffer.isBuffer(content) || !Buffer.isBuffer(key)) { return false; }\n var res = [];\n for(var i = 0; i < content.length; i++) {\n res.push(content[i] ^ key[i % key.length]);\n }\n return new Buffer(res);\n };\n \n static CRC32(buffer) {\n var CRCTable = (function() {\n var c = 0, table = new Array(256);\n \n for(var n = 0; n != 256; ++n) {\n c = n;\n c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));\n c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));\n c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));\n c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));\n c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));\n c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));\n c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));\n c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));\n table[n] = c;\n }\n \n return typeof Int32Array !== 'undefined' ? new Int32Array(table) : table;\n })();\n var b, crc, i, len, code;\n if(!Buffer.isBuffer(buffer)) { buffer = new Buffer(new String(buffer)); }\n if(buffer.length > 10000) return CRC32_8(buffer);\n \n for(var crc = -1, i = 0, len = buffer.length - 3; i < len;) {\n crc = (crc >>> 8) ^ CRCTable[(crc ^ buffer[i++])&0xFF];\n crc = (crc >>> 8) ^ CRCTable[(crc ^ buffer[i++])&0xFF];\n crc = (crc >>> 8) ^ CRCTable[(crc ^ buffer[i++])&0xFF];\n crc = (crc >>> 8) ^ CRCTable[(crc ^ buffer[i++])&0xFF];\n }\n while(i < len + 3) { crc = (crc >>> 8) ^ CRCTable[(crc ^ buffer[i++]) & 0xFF]; }\n code = (crc > 0? crc: crc * -1).toString(16);\n while(code.length < 8) { code = '0' + code; }\n return code;\n };\n \n static hashPassword(password) {\n var salt = this.randomID();\n password = password || \"\";\n return {\n hash: require('crypto').createHash('sha1').update(password).update(salt).digest(\"hex\"),\n salt: salt\n };\n };\n static checkPassword(options) {\n options = options || {};\n var password = options.password || \"\";\n var salt = options.salt || \"\";\n var hash = options.hash || \"\";\n return require('crypto').createHash('sha1').update(password).update(salt).digest(\"hex\") == hash;\n };\n}\n\n(function(window) {\n\nmodule.exports = dvalue;\n\nif (typeof exports !== \"undefined\") {\n\texports.dvalue = dvalue;\n}\nelse {\n\twindow.dvalue = dvalue\n\n\tif (typeof define === \"function\" && define.amd) {\n\t\tdefine(function() {\n\t\t\treturn {\n\t\t\t\tdvalue: dvalue\n\t\t\t}\n\t\t})\n\t}\n}\n\n})(typeof window === \"undefined\" ? this : window);", "dangerousExampleEn": "1. var md5 = require('md5');\n2. \n3. console.log(md5('password'));\nLine 3: This is weak for the brute-force attack because it uses md5, a weak hash function.", "safeExampleEn": "1. var bcrypt = require('bcrypt');\n2. \n3. bcrypt.hash(\"password\", 13, function(err, hash) {\n4. console.log(hash);\n5. });\nLine 3: This is safe from the brute-force attack because bcrypt is used to create hash data.", "contexts": [{"lineNo": 384, "eventType": "sink", "messageKey": "jschk.FORBIDDEN.WEAK_ALGORITHM.JS.defect", "params": {"arg0": "sha1"}}]}} {"id": "e9bb8039c1351b5d0683041162d909c431ae54e438ad011d8c0792b7467809ce", "license": {"spdx": ["MIT"], "repo": "highso-fe/frontend-monitor", "path": "app/extend/application.js", "repo_head_hexsha": "94d467dbe3e0aeff9512d9f7d51725a3a83f95b3", "stack_hexsha": "77afab5c821dd7f434735d88568e69f98e6f33b3", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of weak cryptographic algorithm", "issueDescriptionEn": "A hash function is a one-way function that receives data of different lengths and maps it to random data of a fixed length. It is commonly used to store user passwords because it always produces the same output for a given input.\nBecause hash can be calculated very quickly, the hash functions, such as MD5 and SHA, may give the illusion of high performance. However they are vulnerable to random brute-force attacks. If you use the hash functions on simple data, they can be saved in the rainbow table, making it insecure. In addition, RC2, RC3, RC4, RC5, RC6, MD4, and DES are also known to be vulnerable.\nThere are many functions used to overcome the disadvantages of MD5 and SHA.\nIn Node.js, bcrypt is one of the functions that is commonly used with outstanding performance and easily replace them. The latest hash algorithms, such as Argon2, PBKDF2, and Scrypt, are also good alternatives. Make sure to add a salt to the hash in SHA-2 i.e. SHA-224, SHA-256, SHA-384, SHA-512.", "issueLineNumber": 49, "entireCode": "'use strict';\nconst { exec } = require('child_process');\nconst md5 = require('md5');\n\nmodule.exports = {\n // 生成model中间件\n middlewareModel(dbname, modelname) {\n const WebPagesSchema = this.WebReportSchema;\n const conn = this.mongooseDB.get(dbname);\n return conn.model(modelname, WebPagesSchema);\n },\n /* 生成随机字符串 */\n randomString(len) {\n len = len || 7;\n const $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';\n const maxPos = $chars.length;\n let pwd = '';\n for (let i = 0; i < len; i++) {\n pwd += $chars.charAt(Math.floor(Math.random() * maxPos));\n }\n return pwd + Date.now();\n },\n\n /* 本地加密算法 */\n signwx(json) {\n const wxkey = 'ZANEWANGWEI123456AGETEAMABmiliH';\n /* 对json的key值排序 */\n const arr = [];\n const sortJson = {};\n const newJson = json;\n for (const key in json) {\n if (json[key]) {\n arr.push(key);\n }\n }\n arr.sort((a, b) => {\n return a.localeCompare(b);\n });\n for (let i = 0, len = arr.length; i < len; i++) {\n sortJson[arr[i]] = json[arr[i]];\n }\n /* 拼接json为key=val形式 */\n let str = '';\n for (const key in sortJson) {\n str += key + '=' + sortJson[key] + '&';\n }\n str += 'key=' + wxkey;\n /* md5 */\n const md5Str = md5(str);\n const signstr = md5Str.toUpperCase();\n /* 获得有sign参数的json */\n newJson.paySign = signstr;\n return newJson;\n },\n // 返回结果json\n result(jn = {}) {\n return Object.assign({\n code: 1000,\n desc: '成功',\n data: '',\n }, jn);\n },\n format(date, fmt) {\n const o = {\n 'M+': date.getMonth() + 1, // 月份\n 'd+': date.getDate(), // 日\n 'h+': date.getHours(), // 小时\n 'H+': date.getHours() > 12 ? date.getHours() - 12 : date.getHours(),\n 'm+': date.getMinutes(), // 分\n 's+': date.getSeconds(), // 秒\n };\n if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));\n for (const k in o) {\n if (new RegExp('(' + k + ')').test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)));\n }\n return fmt;\n },\n // 重启mongodb服务器\n restartMongodbs(type, ctx, catcherr) {\n if (this.config.shell_restart.mongodb && this.config.shell_restart.mongodb.length) {\n this.config.shell_restart.mongodb.forEach(item => {\n exec(`sh ${item}`, error => {\n if (error) {\n this.logger.info(`重启${type}数据库失败!`);\n return;\n }\n this.logger.info(`重启${type}数据库成功!`);\n ctx.service.errors.saveSysAndDbErrors(type, item, catcherr);\n // 重启servers\n if (this.config.shell_restart.servers && this.config.shell_restart.servers.length) {\n this.config.shell_restart.servers.forEach(item => {\n exec(`sh ${item}`, error => {\n if (error) {\n this.logger.info('重启node.js服务失败!');\n return;\n }\n this.logger.info('重启node.js服务成功!');\n });\n });\n }\n });\n });\n }\n },\n};\n", "dangerousExampleEn": "1. var md5 = require('md5');\n2. \n3. console.log(md5('password'));\nLine 3: This is weak for the brute-force attack because it uses md5, a weak hash function.", "safeExampleEn": "1. var bcrypt = require('bcrypt');\n2. \n3. bcrypt.hash(\"password\", 13, function(err, hash) {\n4. console.log(hash);\n5. });\nLine 3: This is safe from the brute-force attack because bcrypt is used to create hash data.", "contexts": [{"lineNo": 49, "eventType": "sink", "messageKey": "jschk.FORBIDDEN.WEAK_ALGORITHM.JS.defect", "params": {"arg0": "md5"}}]}} {"id": "6c93685a1aa0ae73c3fada52b2d08b06a5dc7bea55c24f5fbcf9fed7782748ad", "license": {"spdx": ["MIT"], "repo": "TimSchlechter/SpecResults.WebApp", "path": "SpecResults.WebApp/src/model/Report.js", "repo_head_hexsha": "c8e9ed79a2d210126429264ce51b009ceec527c9", "stack_hexsha": "7113870e7a202ed560ce75cd025858eaf74f551e", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of weak cryptographic algorithm", "issueDescriptionEn": "A hash function is a one-way function that receives data of different lengths and maps it to random data of a fixed length. It is commonly used to store user passwords because it always produces the same output for a given input.\nBecause hash can be calculated very quickly, the hash functions, such as MD5 and SHA, may give the illusion of high performance. However they are vulnerable to random brute-force attacks. If you use the hash functions on simple data, they can be saved in the rainbow table, making it insecure. In addition, RC2, RC3, RC4, RC5, RC6, MD4, and DES are also known to be vulnerable.\nThere are many functions used to overcome the disadvantages of MD5 and SHA.\nIn Node.js, bcrypt is one of the functions that is commonly used with outstanding performance and easily replace them. The latest hash algorithms, such as Argon2, PBKDF2, and Scrypt, are also good alternatives. Make sure to add a salt to the hash in SHA-2 i.e. SHA-224, SHA-256, SHA-384, SHA-512.", "issueLineNumber": 108, "entireCode": "(function() {\n\t\"use strict\";\n\n\tangular.module(\"app\").factory(\"Report\", [\n\t\tfunction($scope, $routeParams) {\n\t\t\tfunction Report(reportData) {\n\t\t\t\tthis.reportData = reportData;\n\n\t\t\t\t// Create a grouped property for each report item type\n\t\t\t\tthis.features = reportData.features;\n\t\t\t\tthis.scenarios = _.flatten(reportData.features, \"scenarios\");\n\t\t\t\tthis.scenarioBlocks = _.reduce(this.scenarios, function(result, scenario) {\n\t\t\t\t\tresult.push(scenario.given);\n\t\t\t\t\tresult.push(scenario.when);\n\t\t\t\t\tresult.push(scenario.then);\n\t\t\t\t\treturn result;\n\t\t\t\t}, []);\n\t\t\t\tthis.steps = _.reduce(this.scenarioBlocks, function(result, scenarioBlock) {\n\t\t\t\t\tresult.push.apply(result, scenarioBlock.steps);\n\t\t\t\t\treturn result;\n\t\t\t\t}, []);\n\n\t\t\t\tthis.reportItems = _.union(\n\t\t\t\t\tthis.features,\n\t\t\t\t\tthis.scenarios,\n\t\t\t\t\tthis.scenarioBlocks,\n\t\t\t\t\tthis.steps\n\t\t\t\t);\n\n\t\t\t\t// Decorate features\n\t\t\t\t_.forEach(this.reportData.features, function(feature, index) {\n\t\t\t\t\tfeature.id = generateId([feature.title]);\n\t\t\t\t\tfeature.duration = getDuration(feature);\n\t\t\t\t\tfeature.type = \"feature\";\n\n\t\t\t\t\t// Decorate scenarios\n\t\t\t\t\t_.forEach(feature.scenarios, function(scenario, index) {\n\t\t\t\t\t\tscenario.id = generateId([feature.title, scenario.title]);\n\t\t\t\t\t\tscenario.duration = getDuration(scenario);\n\t\t\t\t\t\tscenario.featureId = feature.id;\n\t\t\t\t\t\tscenario.type = \"scenario\";\n\n\t\t\t\t\t\tvar stepNumber = 1;\n\n\t\t\t\t\t\t// Decorate scenario blocks\n\t\t\t\t\t\tvar scenarioblockMap = _.pick(scenario, [\"given\", \"when\", \"then\"]);\n\t\t\t\t\t\t_.forEach(scenarioblockMap, function(scenarioBlock, scenarioBlockType) {\n\t\t\t\t\t\t\tscenarioBlock.id = generateId([feature.title, scenario.title, scenarioBlockType]);\n\t\t\t\t\t\t\tscenarioBlock.duration = getDuration(scenarioBlock);\n\t\t\t\t\t\t\tscenarioBlock.featureId = feature.id;\n\t\t\t\t\t\t\tscenarioBlock.scenarioId = scenario.id;\n\t\t\t\t\t\t\tscenarioBlock.type = \"scenarioBlock\";\n\n\t\t\t\t\t\t\t// Decorate steps\n\t\t\t\t\t\t\t_.forEach(scenarioBlock.steps, function(step, index) {\n\t\t\t\t\t\t\t\tstep.id = generateId([feature.title, scenario.title, scenarioBlockType, index]);\n\t\t\t\t\t\t\t\tstep.duration = getDuration(step);\n\t\t\t\t\t\t\t\tstep.featureId = feature.id;\n\t\t\t\t\t\t\t\tstep.scenarioId = scenario.id;\n\t\t\t\t\t\t\t\tstep.scenarioBlockId = scenarioBlock.id;\n\t\t\t\t\t\t\t\tstep.number = stepNumber++;\n\t\t\t\t\t\t\t\tstep.type = \"step\";\n\n\t\t\t\t\t\t\t\t// Store step's exception on the scenario and scenarioblock.\n\t\t\t\t\t\t\t\t// Assume there can be only one exception in scenario\n\t\t\t\t\t\t\t\tif (step.exception) {\n\t\t\t\t\t\t\t\t\tscenario.exception = step.exception;\n\t\t\t\t\t\t\t\t\tscenarioBlock.exception = step.exception;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t});\n\t\t\t\t\t});\n\t\t\t\t});\n\n\t\t\t\t// Build search index\n\t\t\t\tthis.searchIndex = _.map(this.scenarios, function(scenario) {\n\t\t\t\t\tvar feature = this.findFeatureById(scenario.featureId);\n\t\t\t\t\tvar scenarioblockMap = _.pick(scenario, [\"given\", \"when\", \"then\"]);\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\tfeature: {\n\t\t\t\t\t\t\tid: feature.id,\n\t\t\t\t\t\t\ttitle: feature.title,\n\t\t\t\t\t\t\tdescription: feature.description,\n\t\t\t\t\t\t\ttags: feature.tags\n\t\t\t\t\t\t},\n\t\t\t\t\t\tscenario: {\n\t\t\t\t\t\t\tid: scenario.id,\n\t\t\t\t\t\t\ttitle: scenario.title,\n\t\t\t\t\t\t\ttags: scenario.tags,\n\t\t\t\t\t\t\tresult: scenario.result\n\t\t\t\t\t\t},\n\t\t\t\t\t\tsteps: _.union(\n\t\t\t\t\t\t\tscenario.given.steps,\n\t\t\t\t\t\t\tscenario.when.steps,\n\t\t\t\t\t\t\tscenario.then.steps\n\t\t\t\t\t\t)\n\t\t\t\t\t};\n\t\t\t\t}, this);\n\t\t\t}\n\n\t\t\tfunction getDuration(item) {\n\t\t\t\treturn new Date(item.end_time).getTime() - new Date(item.start_time).getTime();\n\t\t\t}\n\n\t\t\tfunction generateId(values) {\n\t\t\t\tvar str = values.join(\"#####\");\n\t\t\t\treturn md5(str);\n\t\t\t};\n\n\t\t\tReport.prototype = {\n\t\t\t\tconstructor: Report,\n\n\t\t\t\tfindFeatureById: function(id) {\n\t\t\t\t\treturn _.find(this.features, function(feature) {\n\t\t\t\t\t\treturn feature.id === id;\n\t\t\t\t\t});\n\t\t\t\t},\n\n\t\t\t\tfindScenarioById: function(id) {\n\t\t\t\t\treturn _.find(this.scenarios, function(scenario) {\n\t\t\t\t\t\treturn scenario.id === id;\n\t\t\t\t\t});\n\t\t\t\t},\n\n\t\t\t\tfindStepById: function(id) {\n\t\t\t\t\treturn _.find(this.steps, function(step) {\n\t\t\t\t\t\treturn scenario.id === id;\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t};\n\n\n\t\t\treturn Report;\n\t\t}\n\t]);\n})();", "dangerousExampleEn": "1. var md5 = require('md5');\n2. \n3. console.log(md5('password'));\nLine 3: This is weak for the brute-force attack because it uses md5, a weak hash function.", "safeExampleEn": "1. var bcrypt = require('bcrypt');\n2. \n3. bcrypt.hash(\"password\", 13, function(err, hash) {\n4. console.log(hash);\n5. });\nLine 3: This is safe from the brute-force attack because bcrypt is used to create hash data.", "contexts": [{"lineNo": 108, "eventType": "sink", "messageKey": "jschk.FORBIDDEN.WEAK_ALGORITHM.JS.defect", "params": {"arg0": "md5"}}]}} {"id": "534ac63585b2cbf2d3b3ea0f01a611dd4ef8396fb18905ecd9776d841c0d0b83", "license": {"spdx": ["MIT"], "repo": "Uzlopak/fastify", "path": "test/reply-trailers.test.js", "repo_head_hexsha": "de5c95ee1945ec780a672d580b9e775727b27cc1", "stack_hexsha": "e9ae60cdf7b47ac3a7a9addee356e77225223a1e", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of weak cryptographic algorithm", "issueDescriptionEn": "A hash function is a one-way function that receives data of different lengths and maps it to random data of a fixed length. It is commonly used to store user passwords because it always produces the same output for a given input.\nBecause hash can be calculated very quickly, the hash functions, such as MD5 and SHA, may give the illusion of high performance. However they are vulnerable to random brute-force attacks. If you use the hash functions on simple data, they can be saved in the rainbow table, making it insecure. In addition, RC2, RC3, RC4, RC5, RC6, MD4, and DES are also known to be vulnerable.\nThere are many functions used to overcome the disadvantages of MD5 and SHA.\nIn Node.js, bcrypt is one of the functions that is commonly used with outstanding performance and easily replace them. The latest hash algorithms, such as Argon2, PBKDF2, and Scrypt, are also good alternatives. Make sure to add a salt to the hash in SHA-2 i.e. SHA-224, SHA-256, SHA-384, SHA-512.", "issueLineNumber": 86, "entireCode": "'use strict'\n\nconst t = require('tap')\nconst test = t.test\nconst Fastify = require('..')\nconst { Readable } = require('stream')\nconst { createHash } = require('crypto')\n\ntest('send trailers when payload is empty string', t => {\n t.plan(5)\n\n const fastify = Fastify()\n\n fastify.get('/', function (request, reply) {\n reply.trailer('ETag', function (reply, payload) {\n return 'custom-etag'\n })\n reply.send('')\n })\n\n fastify.inject({\n method: 'GET',\n url: '/'\n }, (error, res) => {\n t.error(error)\n t.equal(res.statusCode, 200)\n t.equal(res.headers.trailer, 'etag')\n t.equal(res.trailers.etag, 'custom-etag')\n t.notHas(res.headers, 'content-length')\n })\n})\n\ntest('send trailers when payload is empty buffer', t => {\n t.plan(5)\n\n const fastify = Fastify()\n\n fastify.get('/', function (request, reply) {\n reply.trailer('ETag', function (reply, payload) {\n return 'custom-etag'\n })\n reply.send(Buffer.alloc(0))\n })\n\n fastify.inject({\n method: 'GET',\n url: '/'\n }, (error, res) => {\n t.error(error)\n t.equal(res.statusCode, 200)\n t.equal(res.headers.trailer, 'etag')\n t.equal(res.trailers.etag, 'custom-etag')\n t.notHas(res.headers, 'content-length')\n })\n})\n\ntest('send trailers when payload is undefined', t => {\n t.plan(5)\n\n const fastify = Fastify()\n\n fastify.get('/', function (request, reply) {\n reply.trailer('ETag', function (reply, payload) {\n return 'custom-etag'\n })\n reply.send(undefined)\n })\n\n fastify.inject({\n method: 'GET',\n url: '/'\n }, (error, res) => {\n t.error(error)\n t.equal(res.statusCode, 200)\n t.equal(res.headers.trailer, 'etag')\n t.equal(res.trailers.etag, 'custom-etag')\n t.notHas(res.headers, 'content-length')\n })\n})\n\ntest('send trailers when payload is json', t => {\n t.plan(7)\n\n const fastify = Fastify()\n const data = JSON.stringify({ hello: 'world' })\n const hash = createHash('md5')\n hash.update(data)\n const md5 = hash.digest('hex')\n\n fastify.get('/', function (request, reply) {\n reply.trailer('Content-MD5', function (reply, payload) {\n t.equal(data, payload)\n const hash = createHash('md5')\n hash.update(payload)\n return hash.digest('hex')\n })\n reply.send(data)\n })\n\n fastify.inject({\n method: 'GET',\n url: '/'\n }, (error, res) => {\n t.error(error)\n t.equal(res.statusCode, 200)\n t.equal(res.headers['transfer-encoding'], 'chunked')\n t.equal(res.headers.trailer, 'content-md5')\n t.equal(res.trailers['content-md5'], md5)\n t.notHas(res.headers, 'content-length')\n })\n})\n\ntest('send trailers when payload is stream', t => {\n t.plan(7)\n\n const fastify = Fastify()\n\n fastify.get('/', function (request, reply) {\n reply.trailer('ETag', function (reply, payload) {\n t.same(payload, null)\n return 'custom-etag'\n })\n const stream = Readable.from([JSON.stringify({ hello: 'world' })])\n reply.send(stream)\n })\n\n fastify.inject({\n method: 'GET',\n url: '/'\n }, (error, res) => {\n t.error(error)\n t.equal(res.statusCode, 200)\n t.equal(res.headers['transfer-encoding'], 'chunked')\n t.equal(res.headers.trailer, 'etag')\n t.equal(res.trailers.etag, 'custom-etag')\n t.notHas(res.headers, 'content-length')\n })\n})\n\ntest('removeTrailer', t => {\n t.plan(6)\n\n const fastify = Fastify()\n\n fastify.get('/', function (request, reply) {\n reply.removeTrailer('ETag') // remove nothing\n reply.trailer('ETag', function (reply, payload) {\n return 'custom-etag'\n })\n reply.trailer('Should-Not-Call', function (reply, payload) {\n t.fail('it should not called as this trailer is removed')\n return 'should-not-call'\n })\n reply.removeTrailer('Should-Not-Call')\n reply.send(undefined)\n })\n\n fastify.inject({\n method: 'GET',\n url: '/'\n }, (error, res) => {\n t.error(error)\n t.equal(res.statusCode, 200)\n t.equal(res.headers.trailer, 'etag')\n t.equal(res.trailers.etag, 'custom-etag')\n t.notOk(res.trailers['should-not-call'])\n t.notHas(res.headers, 'content-length')\n })\n})\n\ntest('hasTrailer', t => {\n t.plan(10)\n\n const fastify = Fastify()\n\n fastify.get('/', function (request, reply) {\n t.equal(reply.hasTrailer('ETag'), false)\n reply.trailer('ETag', function (reply, payload) {\n return 'custom-etag'\n })\n t.equal(reply.hasTrailer('ETag'), true)\n reply.trailer('Should-Not-Call', function (reply, payload) {\n t.fail('it should not called as this trailer is removed')\n return 'should-not-call'\n })\n t.equal(reply.hasTrailer('Should-Not-Call'), true)\n reply.removeTrailer('Should-Not-Call')\n t.equal(reply.hasTrailer('Should-Not-Call'), false)\n reply.send(undefined)\n })\n\n fastify.inject({\n method: 'GET',\n url: '/'\n }, (error, res) => {\n t.error(error)\n t.equal(res.statusCode, 200)\n t.equal(res.headers.trailer, 'etag')\n t.equal(res.trailers.etag, 'custom-etag')\n t.notOk(res.trailers['should-not-call'])\n t.notHas(res.headers, 'content-length')\n })\n})\n\ntest('throw error when trailer header name is not allowed', t => {\n const INVALID_TRAILERS = [\n 'transfer-encoding',\n 'content-length',\n 'host',\n 'cache-control',\n 'max-forwards',\n 'te',\n 'authorization',\n 'set-cookie',\n 'content-encoding',\n 'content-type',\n 'content-range',\n 'trailer'\n ]\n t.plan(INVALID_TRAILERS.length + 2)\n\n const fastify = Fastify()\n\n fastify.get('/', function (request, reply) {\n for (const key of INVALID_TRAILERS) {\n try {\n reply.trailer(key, () => {})\n } catch (err) {\n t.equal(err.message, `Called reply.trailer with an invalid header name: ${key}`)\n }\n }\n reply.send('')\n })\n\n fastify.inject({\n method: 'GET',\n url: '/'\n }, (error, res) => {\n t.error(error)\n t.equal(res.statusCode, 200)\n })\n})\n\ntest('throw error when trailer header value is not function', t => {\n const INVALID_TRAILERS_VALUE = [\n undefined,\n null,\n true,\n false,\n 'invalid',\n [],\n new Date(),\n {}\n ]\n t.plan(INVALID_TRAILERS_VALUE.length + 2)\n\n const fastify = Fastify()\n\n fastify.get('/', function (request, reply) {\n for (const value of INVALID_TRAILERS_VALUE) {\n try {\n reply.trailer('invalid', value)\n } catch (err) {\n t.equal(err.message, `Called reply.trailer('invalid', fn) with an invalid type: ${typeof value}. Expected a function.`)\n }\n }\n reply.send('')\n })\n\n fastify.inject({\n method: 'GET',\n url: '/'\n }, (error, res) => {\n t.error(error)\n t.equal(res.statusCode, 200)\n })\n})", "dangerousExampleEn": "1. var md5 = require('md5');\n2. \n3. console.log(md5('password'));\nLine 3: This is weak for the brute-force attack because it uses md5, a weak hash function.", "safeExampleEn": "1. var bcrypt = require('bcrypt');\n2. \n3. bcrypt.hash(\"password\", 13, function(err, hash) {\n4. console.log(hash);\n5. });\nLine 3: This is safe from the brute-force attack because bcrypt is used to create hash data.", "contexts": [{"lineNo": 86, "eventType": "sink", "messageKey": "jschk.FORBIDDEN.WEAK_ALGORITHM.JS.defect", "params": {"arg0": "md5"}}]}} {"id": "f261db1de415f30c379e67265c11bd05c6b36a3e6f1552eb7da714e3df1ebe63", "license": {"spdx": ["MIT"], "repo": "Yotis-Studios/orchestra", "path": "src/pow/ChallengeManager.js", "repo_head_hexsha": "5af5af7b3a1cdb94697fa66f391672ff8468075b", "stack_hexsha": "74d6b30f03a2f0b022d2c14080ced0f2a7ea5a7b", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of weak cryptographic algorithm", "issueDescriptionEn": "A hash function is a one-way function that receives data of different lengths and maps it to random data of a fixed length. It is commonly used to store user passwords because it always produces the same output for a given input.\nBecause hash can be calculated very quickly, the hash functions, such as MD5 and SHA, may give the illusion of high performance. However they are vulnerable to random brute-force attacks. If you use the hash functions on simple data, they can be saved in the rainbow table, making it insecure. In addition, RC2, RC3, RC4, RC5, RC6, MD4, and DES are also known to be vulnerable.\nThere are many functions used to overcome the disadvantages of MD5 and SHA.\nIn Node.js, bcrypt is one of the functions that is commonly used with outstanding performance and easily replace them. The latest hash algorithms, such as Argon2, PBKDF2, and Scrypt, are also good alternatives. Make sure to add a salt to the hash in SHA-2 i.e. SHA-224, SHA-256, SHA-384, SHA-512.", "issueLineNumber": 21, "entireCode": "const md5 = require('md5');\nconst random = require('random');\n\nclass ChallengeManager {\n constructor(config) {\n this.challenges = {}; // Map of IP -> generated challeges\n this.powDifficulty = config.powDifficulty; // Number of zeros required to be in the hash\n this.key = config.accessKey + config.version; // constant string used to generate hash\n }\n generateChallengeFromRequest(req) {\n const ip = req.ip;\n const randInt = random.int(1, 999999);\n this.challenges[ip] = randInt.toString();\n return this.challenges[ip];\n }\n testSolutionForIP(solution, ip) {\n const challenge = this.challenges[ip];\n if (!challenge) {\n return false;\n }\n const hash = md5(this.key + challenge + solution);\n const hashStr = hash.substring(0, this.powDifficulty);\n return hashStr === Array(this.powDifficulty + 1).join('0');\n }\n}\n\nmodule.exports = ChallengeManager;", "dangerousExampleEn": "1. var md5 = require('md5');\n2. \n3. console.log(md5('password'));\nLine 3: This is weak for the brute-force attack because it uses md5, a weak hash function.", "safeExampleEn": "1. var bcrypt = require('bcrypt');\n2. \n3. bcrypt.hash(\"password\", 13, function(err, hash) {\n4. console.log(hash);\n5. });\nLine 3: This is safe from the brute-force attack because bcrypt is used to create hash data.", "contexts": [{"lineNo": 21, "eventType": "sink", "messageKey": "jschk.FORBIDDEN.WEAK_ALGORITHM.JS.defect", "params": {"arg0": "md5"}}]}} {"id": "822ef8043ee7400798b1b0298573de04f846acd2d0afea78c815edaad01ee0d6", "license": {"spdx": ["Apache-2.0"], "repo": "cantina/cantina-assets", "path": "lib/css.js", "repo_head_hexsha": "ea1325f6f7323c010f7ecbca8d9c478f2559d613", "stack_hexsha": "893279a3050d38024773e778250aa72a206d66df", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of weak cryptographic algorithm", "issueDescriptionEn": "A hash function is a one-way function that receives data of different lengths and maps it to random data of a fixed length. It is commonly used to store user passwords because it always produces the same output for a given input.\nBecause hash can be calculated very quickly, the hash functions, such as MD5 and SHA, may give the illusion of high performance. However they are vulnerable to random brute-force attacks. If you use the hash functions on simple data, they can be saved in the rainbow table, making it insecure. In addition, RC2, RC3, RC4, RC5, RC6, MD4, and DES are also known to be vulnerable.\nThere are many functions used to overcome the disadvantages of MD5 and SHA.\nIn Node.js, bcrypt is one of the functions that is commonly used with outstanding performance and easily replace them. The latest hash algorithms, such as Argon2, PBKDF2, and Scrypt, are also good alternatives. Make sure to add a salt to the hash in SHA-2 i.e. SHA-224, SHA-256, SHA-384, SHA-512.", "issueLineNumber": 93, "entireCode": "var path = require('path')\n , fs = require('fs')\n , mkdirp = require('mkdirp')\n , rimraf = require('rimraf')\n , crypto = require('crypto')\n , sqwish = require('sqwish')\n , dish = require('dish')\n , async = require('async')\n ;\n\nmodule.exports = function (app) {\n var settings\n , namespaces\n , styles\n , reset = []\n , api = {}\n , prefixer = app.require('./prefix');\n\n // Helper to run all css modifiers.\n api.optimize = function optimize (cb) {\n app.log('optimizing css ...');\n\n settings = app.conf.get('assets:css') || {};\n namespaces = Object.keys(settings);\n styles = app.conf.get('styles') || [];\n\n // Prime reset with external styles.\n styles.forEach(function (style) {\n if (style.match(/^(\\/\\/)|(http)/)) {\n reset.push(style);\n }\n });\n\n // Setup namespaces.\n app.assets.css = {};\n namespaces.forEach(function (namespace) {\n app.assets.css[namespace] = {};\n });\n\n async.series([\n api.aggregateAll,\n api.prefixAll,\n api.minifyAll,\n api.cacheAll,\n api.serveAll\n ], cb);\n };\n\n // Aggregate files into one.\n api.aggregateAll = function (cb) {\n async.forEachSeries(namespaces, api.aggregate, cb);\n };\n api.aggregate = function aggregate (namespace, cb) {\n var conf = app.conf.get('assets:css:' + namespace);\n if (conf.aggregate) {\n app.log('- aggregating `' + namespace + '` css ...');\n var files = {}\n , content = ''\n , hash = null\n , dirs = conf.dirs || []\n ;\n\n async.series([\n // Collect stylesheets for this namespace.\n function (next) {\n var match = conf.match;\n if (match) {\n match = new RegExp('(' + match.join(')|(') + ')');\n }\n var exclude = conf.exclude;\n if (exclude) {\n exclude = new RegExp('(' + exclude.join(')|(') + ')');\n }\n\n // Look in specified dirs. Push empty string to look in app.root too.\n if (dirs.indexOf('') < 0) dirs.push('');\n dirs.forEach(function (dir) {\n styles.forEach(function (key) {\n if ((!match || key.match(match)) && (!exclude || !exclude.test(key))) {\n var file = path.join((conf.root || app.root), dir, 'public', key);\n if (fs.existsSync(file)) {\n files[key] = file;\n }\n }\n });\n });\n\n next();\n },\n\n // Create build hash out of file contents.\n function (next) {\n var md5 = crypto.createHash('md5');\n async.reduce(\n Object.keys(files),\n '',\n function (memo, key, cb) {\n var file = files[key];\n if (!file) return cb(new Error('Could not find stylesheet for key: ' + key));\n fs.readFile(file, 'utf8', function (err, file) {\n if (err) return cb(err);\n cb(err, memo + file);\n });\n },\n function (err, result) {\n if (err) return next(err);\n hash = md5.update(result).digest('hex');\n app.assets.css[namespace].hash = hash;\n next();\n }\n );\n },\n\n // Check cache.\n function (next) {\n // Skip if no cache mechanism, or it's disabled.\n if (!app.cache) return next();\n if (!app.conf.get('assets:css:' + namespace + ':cache')) return next();\n\n // Look up in cache.\n var cacheKey = 'assets:' + app.assets.css[namespace].hash;\n app.cache.get(cacheKey, function (err, result) {\n if (err) return next(err);\n\n // If no result, continue to build.\n if (!result) return next();\n\n // Set content. Flag as from cache to skip further processing.\n app.assets.css[namespace].content = result.data;\n app.assets.css[namespace].fromCache = true;\n next();\n });\n },\n\n // Concatenate stylesheets.\n function (next) {\n if (app.assets.css[namespace].fromCache) return next();\n\n async.forEachSeries(Object.keys(files), function (key, done) {\n var file = files[key]\n , dir;\n\n fs.readFile(file, 'utf8', function (err, css) {\n if (err) return done(err);\n\n // Deal with relative urls in vendor stylesheets.\n // @todo: make this optional/regex-based? /vendor/ is too specific.\n if (key.indexOf('/vendor/') === 0) {\n dir = path.dirname(key);\n css = css.replace(/url\\(['\"]?([^\\)'\"]*)['\"]?\\)/gi, function (match, url, offset) {\n if (url.indexOf('data:') < 0) {\n return 'url(\"' + path.normalize(dir + '/' + url) + '\")';\n }\n return match;\n });\n }\n\n // Add to aggregate.\n content += '/* ' + key + ' */\\n';\n content += css + '\\n\\n';\n\n app.assets.css[namespace].content = content;\n done();\n });\n }, next);\n }\n ], function (err) {\n if (err) return cb(err);\n\n // Override conf styles with the aggregate.\n reset.push('/assets/css/' + app.assets.css[namespace].hash + '-' + namespace + '.css');\n app.conf.reset('styles', reset);\n cb();\n });\n }\n else {\n cb();\n }\n };\n\n // Auto-prefix stylesheets.\n api.prefixAll = function (cb) {\n async.forEachSeries(namespaces, api.prefix, cb);\n };\n api.prefix = function prefix (namespace, cb) {\n if (app.assets.css[namespace].fromCache) return cb();\n\n if (app.conf.get('assets:css:' + namespace + ':prefix') && app.assets.css[namespace].content) {\n app.log('- prefixing `' + namespace + '` css ...');\n app.assets.css[namespace].content = prefixer(app.assets.css[namespace].content);\n }\n cb();\n };\n\n // Minify contents.\n api.minifyAll = function (cb) {\n async.forEachSeries(namespaces, api.minify, cb);\n };\n api.minify = function minify (namespace, cb) {\n if (app.assets.css[namespace].fromCache) return cb();\n\n if (app.conf.get('assets:css:' + namespace + ':minify') && app.assets.css[namespace].content) {\n app.log('- minifying `' + namespace + '` css ...');\n app.assets.css[namespace].content = sqwish.minify(app.assets.css[namespace].content);\n }\n cb();\n };\n\n // Cache contents.\n api.cacheAll = function (cb) {\n async.forEachSeries(namespaces, api.cache, cb);\n };\n api.cache = function cache (namespace, cb) {\n // Skip if no cache mechanism, or if we already loaded from the cache.\n if (!app.cache) return cb();\n if (app.assets.css[namespace].fromCache) return cb();\n\n // Cache the content.\n if (app.conf.get('assets:css:' + namespace + ':cache') && app.assets.css[namespace].content) {\n var cacheKey = 'assets:' + app.assets.css[namespace].hash\n , cacheTags = {\n assets: ['*', 'css', namespace, namespace + ':css']\n }\n ;\n\n // Set the cache.\n app.log('- caching `' + namespace + '` css ...');\n app.cache.set(cacheKey, app.assets.css[namespace].content, cacheTags, cb);\n }\n else {\n cb();\n }\n };\n\n // Serve file.\n api.serveAll = function (cb) {\n async.forEachSeries(namespaces, api.serve, cb);\n };\n api.serve = function serve (namespace, cb) {\n if (app.conf.get('assets:css:' + namespace + ':serve') && app.assets.css[namespace].content) {\n app.log('- serving `' + namespace + '` css ' + (app.assets.css[namespace].fromCache ? '(from cache)' : '') + ' ...');\n app.middleware.get(-1200, '/assets/css/' + app.assets.css[namespace].hash + '-' + namespace + '.css', dish(app.assets.css[namespace].content, {\n headers: {\n 'Content-Type': 'text/css'\n }\n }));\n }\n cb();\n };\n\n return api;\n};", "dangerousExampleEn": "1. var md5 = require('md5');\n2. \n3. console.log(md5('password'));\nLine 3: This is weak for the brute-force attack because it uses md5, a weak hash function.", "safeExampleEn": "1. var bcrypt = require('bcrypt');\n2. \n3. bcrypt.hash(\"password\", 13, function(err, hash) {\n4. console.log(hash);\n5. });\nLine 3: This is safe from the brute-force attack because bcrypt is used to create hash data.", "contexts": [{"lineNo": 93, "eventType": "sink", "messageKey": "jschk.FORBIDDEN.WEAK_ALGORITHM.JS.defect", "params": {"arg0": "md5"}}]}} {"id": "99389d1048002af7d0f2b6eaedbc1487063d123b6095e3dd8a0be3fadcb00b0c", "license": {"spdx": ["MIT"], "repo": "leizongmin/node-doc-cn", "path": "tool/utils.js", "repo_head_hexsha": "d522babe95c1a90b6d2f8c5010c4f155daede921", "stack_hexsha": "a61f4f131976228eee042288ae1c374dfd2c5461", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of weak cryptographic algorithm", "issueDescriptionEn": "A hash function is a one-way function that receives data of different lengths and maps it to random data of a fixed length. It is commonly used to store user passwords because it always produces the same output for a given input.\nBecause hash can be calculated very quickly, the hash functions, such as MD5 and SHA, may give the illusion of high performance. However they are vulnerable to random brute-force attacks. If you use the hash functions on simple data, they can be saved in the rainbow table, making it insecure. In addition, RC2, RC3, RC4, RC5, RC6, MD4, and DES are also known to be vulnerable.\nThere are many functions used to overcome the disadvantages of MD5 and SHA.\nIn Node.js, bcrypt is one of the functions that is commonly used with outstanding performance and easily replace them. The latest hash algorithms, such as Argon2, PBKDF2, and Scrypt, are also good alternatives. Make sure to add a salt to the hash in SHA-2 i.e. SHA-224, SHA-256, SHA-384, SHA-512.", "issueLineNumber": 27, "entireCode": "/**\n * 工具函数\n */\n\nvar crypto = require('crypto');\n\n\n/**\n * 转换为标准换行符\n *\n * @param {String} text\n * @return {String}\n */\nexports.standardLineBreak = function (text) {\n return text.split(/\\n/).map(function (line) {\n return line.replace(/\\r$/, '');\n }).join('\\n');\n};\n\n/**\n * 32位MD5加密\n *\n * @param {string} text 文本\n * @return {string}\n */\nexports.md5 = function (text) {\n return crypto.createHash('md5').update(text).digest('hex');\n};", "dangerousExampleEn": "1. var md5 = require('md5');\n2. \n3. console.log(md5('password'));\nLine 3: This is weak for the brute-force attack because it uses md5, a weak hash function.", "safeExampleEn": "1. var bcrypt = require('bcrypt');\n2. \n3. bcrypt.hash(\"password\", 13, function(err, hash) {\n4. console.log(hash);\n5. });\nLine 3: This is safe from the brute-force attack because bcrypt is used to create hash data.", "contexts": [{"lineNo": 27, "eventType": "sink", "messageKey": "jschk.FORBIDDEN.WEAK_ALGORITHM.JS.defect", "params": {"arg0": "md5"}}]}} {"id": "fb93876c57a36a26ed7e20ead1be9ed1887ba291ced04cf8dee6f3f95cace566", "license": {"spdx": ["MIT"], "repo": "paperlesspost/grunt-hashres", "path": "tasks/hashresHelper.js", "repo_head_hexsha": "2d5f0d379bae64275545d085c162792397fe987b", "stack_hexsha": "ffdcf98cd01eb597ad1d43d1fe0ac4a22055e06a", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of weak cryptographic algorithm", "issueDescriptionEn": "A hash function is a one-way function that receives data of different lengths and maps it to random data of a fixed length. It is commonly used to store user passwords because it always produces the same output for a given input.\nBecause hash can be calculated very quickly, the hash functions, such as MD5 and SHA, may give the illusion of high performance. However they are vulnerable to random brute-force attacks. If you use the hash functions on simple data, they can be saved in the rainbow table, making it insecure. In addition, RC2, RC3, RC4, RC5, RC6, MD4, and DES are also known to be vulnerable.\nThere are many functions used to overcome the disadvantages of MD5 and SHA.\nIn Node.js, bcrypt is one of the functions that is commonly used with outstanding performance and easily replace them. The latest hash algorithms, such as Argon2, PBKDF2, and Scrypt, are also good alternatives. Make sure to add a salt to the hash in SHA-2 i.e. SHA-224, SHA-256, SHA-384, SHA-512.", "issueLineNumber": 40, "entireCode": "/*\n * grunt-hashres\n * https://github.com/luismahou/grunt-hashres\n *\n * Copyright (c) 2012 Luismahou\n * Licensed under the MIT license.\n */\n\nvar fs = require('fs'),\n path = require('path'),\n utils = require('./hashresUtils');\n\nvar setupDefaultOptions = function(options) {\n return {\n files: Array.isArray(options.files) ? options.files : [options.files],\n out: Array.isArray(options.out) ? options.out: [options.out],\n encoding: (options.encoding || 'utf8'),\n fileNameFormat: (options.fileNameFormat || '${hash}.${name}.cache.${ext}'),\n renameFiles: (options.renameFiles === undefined ? true : false),\n manifestName: options.manifestName || \"FileManifest\",\n manifestFile: options.manifestFile || \"manifest.js\",\n writeManifest: options.writeManifest || false,\n baseDir: options.baseDir || null,\n httpDir: options.httpDir || null\n };\n};\n\nvar buildHashMapping = function(grunt, options) {\n var nameToHashedName = {},\n formatter = null;\n\n formatter = utils.compileFormat(options.fileNameFormat);\n\n // Renaming the files using a unique name\n grunt.file.expand(options.files).forEach(function(f) {\n var fileName = path.basename(f), md5, lastIndex, renamed;\n if (options.baseDir) {\n fileName = f.replace(options.baseDir, options.httpDir || '');\n }\n md5 = utils.md5(f).slice(0, 8);\n lastIndex = fileName.lastIndexOf('.');\n renamed = formatter({\n hash: md5,\n name: fileName.slice(0, lastIndex),\n ext: fileName.slice(lastIndex + 1, fileName.length)\n });\n\n // Mapping the original name with hashed one for later use.\n nameToHashedName[fileName] = renamed;\n\n // Renaming the file\n if(options.renameFiles) {\n fs.renameSync(f, path.resolve(path.dirname(f), renamed));\n }\n grunt.log.write(f + ' ').ok(renamed);\n });\n\n return nameToHashedName;\n};\n\nvar writeManifest = function(grunt, options, nameToHashedName) {\n grunt.log.ok('writing manifest to ' + options.manifestFile);\n grunt.file.write(options.manifestFile, options.manifestName + \" = \" + JSON.stringify(nameToHashedName, null, \" \") + \";\", options.encoding);\n};\n\nexports.hashAndSub = function(grunt, options) { //files, out, encoding, fileNameFormat) {\n options = setupDefaultOptions(options);\n var files = options.files,\n out = options.out,\n encoding = options.encoding,\n fileNameFormat = options.fileNameFormat,\n renameFiles = options.renameFiles,\n nameToHashedName = {};\n\n grunt.log.ok('out: ' + out);\n grunt.log.debug('Using encoding ' + encoding);\n grunt.log.debug('Using fileNameFormat ' + fileNameFormat);\n grunt.log.debug(renameFiles ? 'Renaming files' : 'Not renaming files');\n\n nameToHashedName = buildHashMapping(grunt, options);\n\n // Substituting references to the given files with the hashed ones.\n grunt.file.expand(out).forEach(function(f) {\n var outContents = fs.readFileSync(f, encoding);\n for (var name in nameToHashedName) {\n grunt.log.debug('Substituting ' + name + ' by ' + nameToHashedName[name]);\n outContents = outContents.replace(name, nameToHashedName[name]);\n }\n grunt.log.debug('Saving the updated contents of the outination file');\n fs.writeFileSync(f, outContents, encoding);\n });\n\n if (options.writeManifest) {\n writeManifest(grunt, options, nameToHashedName);\n }\n};", "dangerousExampleEn": "1. var md5 = require('md5');\n2. \n3. console.log(md5('password'));\nLine 3: This is weak for the brute-force attack because it uses md5, a weak hash function.", "safeExampleEn": "1. var bcrypt = require('bcrypt');\n2. \n3. bcrypt.hash(\"password\", 13, function(err, hash) {\n4. console.log(hash);\n5. });\nLine 3: This is safe from the brute-force attack because bcrypt is used to create hash data.", "contexts": [{"lineNo": 40, "eventType": "sink", "messageKey": "jschk.FORBIDDEN.WEAK_ALGORITHM.JS.defect", "params": {"arg0": "md5"}}]}} {"id": "caa6c0f5923ef3bc5a01e8c7020405a303415812dbaa172021930f51494113c3", "license": {"spdx": ["MIT"], "repo": "frochaol/PasswordGenerator", "path": "js/function.js", "repo_head_hexsha": "882c45b04efba335cd1afcc6d0cb84b23a02c878", "stack_hexsha": "59fa67b0fce774c08e56ef084b4e4def07ddbabd", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of weak cryptographic algorithm", "issueDescriptionEn": "A hash function is a one-way function that receives data of different lengths and maps it to random data of a fixed length. It is commonly used to store user passwords because it always produces the same output for a given input.\nBecause hash can be calculated very quickly, the hash functions, such as MD5 and SHA, may give the illusion of high performance. However they are vulnerable to random brute-force attacks. If you use the hash functions on simple data, they can be saved in the rainbow table, making it insecure. In addition, RC2, RC3, RC4, RC5, RC6, MD4, and DES are also known to be vulnerable.\nThere are many functions used to overcome the disadvantages of MD5 and SHA.\nIn Node.js, bcrypt is one of the functions that is commonly used with outstanding performance and easily replace them. The latest hash algorithms, such as Argon2, PBKDF2, and Scrypt, are also good alternatives. Make sure to add a salt to the hash in SHA-2 i.e. SHA-224, SHA-256, SHA-384, SHA-512.", "issueLineNumber": 33, "entireCode": "function convertPassword(x) {\n // start at 22 because the password will have a lenght of 10 letters\n var finalWord = '';\n for (let step = 22; step < x.length; step++) {\n const element = x.charAt(step);\n var word = '';\n // added key letters to complete passwords restrictions\n switch (step) {\n case 22:\n word = '#';\n break;\n case 24:\n word = 'F';\n break;\n case 31:\n word = '%';\n break; \n default:\n word = x.charAt(step);\n break;\n }\n finalWord = finalWord + word;\n }\n return finalWord;\n}\n\nfunction generateKey() \n{\n var test = document.getElementById(\"keyword\").value;\n var entity = document.getElementById(\"entity\").value;\n var conc = test+entity\n // -- Convert text to md5\n md5hash = md5(conc);\n var result = convertPassword(md5hash);\n document.getElementById(\"generated\").value = result; \n document.getElementById(\"result\").innerHTML = 'The key was generated' ;\n}\n\nfunction clearText() {\n document.getElementById(\"keyword\").value = '';\n document.getElementById(\"entity\").value = '';\n document.getElementById(\"generated\").value = '';\n document.getElementById(\"result\").innerHTML = '' ;\n}\n", "dangerousExampleEn": "1. var md5 = require('md5');\n2. \n3. console.log(md5('password'));\nLine 3: This is weak for the brute-force attack because it uses md5, a weak hash function.", "safeExampleEn": "1. var bcrypt = require('bcrypt');\n2. \n3. bcrypt.hash(\"password\", 13, function(err, hash) {\n4. console.log(hash);\n5. });\nLine 3: This is safe from the brute-force attack because bcrypt is used to create hash data.", "contexts": [{"lineNo": 33, "eventType": "sink", "messageKey": "jschk.FORBIDDEN.WEAK_ALGORITHM.JS.defect", "params": {"arg0": "md5"}}]}} {"id": "81639a04dbc26196b8c7279261d4ca12d9f8af50cd3206a82196da29908c131d", "license": {"spdx": ["MIT"], "repo": "paulogdm/bimp", "path": "lib/transform.js", "repo_head_hexsha": "a3af9f4635e2b9d58227e347ecfa9a451882b268", "stack_hexsha": "dc50620e5d69a34c70e568d4ddf1d079b4a0934e", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of weak cryptographic algorithm", "issueDescriptionEn": "A hash function is a one-way function that receives data of different lengths and maps it to random data of a fixed length. It is commonly used to store user passwords because it always produces the same output for a given input.\nBecause hash can be calculated very quickly, the hash functions, such as MD5 and SHA, may give the illusion of high performance. However they are vulnerable to random brute-force attacks. If you use the hash functions on simple data, they can be saved in the rainbow table, making it insecure. In addition, RC2, RC3, RC4, RC5, RC6, MD4, and DES are also known to be vulnerable.\nThere are many functions used to overcome the disadvantages of MD5 and SHA.\nIn Node.js, bcrypt is one of the functions that is commonly used with outstanding performance and easily replace them. The latest hash algorithms, such as Argon2, PBKDF2, and Scrypt, are also good alternatives. Make sure to add a salt to the hash in SHA-2 i.e. SHA-224, SHA-256, SHA-384, SHA-512.", "issueLineNumber": 33, "entireCode": "require(\"now-env\");\nconst { SECRET, WHITELIST } = process.env;\nconst { send } = require(\"micro\");\nconst { parse } = require(\"url\");\n\nconst md5 = require(\"md5\");\nconst sharp = require(\"sharp\");\nconst decodeUrl = require(\"decodeurl\");\n\nconst sendImage = require(\"./send-image\");\n\nconst combineTransformers = transformers => (req, res, buffer) => {\n return transformers.reduce((stream, transform) => {\n return transform(parse(req.url, true).query, stream);\n }, sharp(buffer));\n};\n\nconst createMicroHandle = (provider, transformer, { onError }) => async (\n req,\n res\n) => {\n const {\n pathname,\n query: { s }\n } = parse(req.url, true);\n\n const path = decodeUrl(pathname.substring(1));\n const lastIndex =\n req.url.lastIndexOf(\"&s=\") >= 0\n ? req.url.lastIndexOf(\"&s=\")\n : req.url.lastIndexOf(\"?s=\");\n const signedURL = req.url.slice(0, lastIndex);\n const hash = md5(SECRET + signedURL);\n const whitelistRegEx = new RegExp(WHITELIST, \"g\");\n\n if (req.url === \"/favicon.ico\") {\n return send(res, 204);\n }\n\n if (!path) {\n return send(res, 404, \"Not found\");\n }\n\n if (SECRET && hash !== s && SECRET) {\n const err = new Error(\"Invalid `signed` value\");\n err.statusCode = 400;\n throw err;\n }\n\n if (WHITELIST && !whitelistRegEx.test(path)) {\n const err = new Error(\"URL not whitelisted\");\n err.statusCode = 400;\n throw err;\n }\n\n try {\n const { contentType, file } = await provider(path);\n const image = transformer(req, res, file);\n return sendImage(req, res, image, {\n \"Content-Type\": contentType\n });\n } catch (err) {\n if (onError) {\n return onError(req, res, err);\n } else {\n console.log(err);\n return send(res, 500, \"Internal error\");\n }\n }\n};\n\nmodule.exports = {\n combineTransformers,\n createMicroHandle\n};", "dangerousExampleEn": "1. var md5 = require('md5');\n2. \n3. console.log(md5('password'));\nLine 3: This is weak for the brute-force attack because it uses md5, a weak hash function.", "safeExampleEn": "1. var bcrypt = require('bcrypt');\n2. \n3. bcrypt.hash(\"password\", 13, function(err, hash) {\n4. console.log(hash);\n5. });\nLine 3: This is safe from the brute-force attack because bcrypt is used to create hash data.", "contexts": [{"lineNo": 33, "eventType": "sink", "messageKey": "jschk.FORBIDDEN.WEAK_ALGORITHM.JS.defect", "params": {"arg0": "md5"}}]}} {"id": "0cc73891694f8dafc0476bf2dfda2bac4023dd67c079c78105b2353f27179d54", "license": {"spdx": ["MIT"], "repo": "EnoahNetzach/wilkins", "path": "src/common/hash.js", "repo_head_hexsha": "4e983eeeee43f918f76a10a9f7ca32a26289735f", "stack_hexsha": "65c46b93e40b73348c4027fb74e8c3c4edcc901b", "match": "repo_path"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of weak cryptographic algorithm", "issueDescriptionEn": "A hash function is a one-way function that receives data of different lengths and maps it to random data of a fixed length. It is commonly used to store user passwords because it always produces the same output for a given input.\nBecause hash can be calculated very quickly, the hash functions, such as MD5 and SHA, may give the illusion of high performance. However they are vulnerable to random brute-force attacks. If you use the hash functions on simple data, they can be saved in the rainbow table, making it insecure. In addition, RC2, RC3, RC4, RC5, RC6, MD4, and DES are also known to be vulnerable.\nThere are many functions used to overcome the disadvantages of MD5 and SHA.\nIn Node.js, bcrypt is one of the functions that is commonly used with outstanding performance and easily replace them. The latest hash algorithms, such as Argon2, PBKDF2, and Scrypt, are also good alternatives. Make sure to add a salt to the hash in SHA-2 i.e. SHA-224, SHA-256, SHA-384, SHA-512.", "issueLineNumber": 18, "entireCode": "/*\n * common.js: Internal helper and utility functions for wilkins\n *\n * (C) 2010 \n * MIT LICENCE\n *\n */\n\nvar crypto = require('crypto')\n\n//\n// ### function hash (str)\n// #### @str {string} String to hash.\n// Utility function for creating unique ids\n// e.g. Profiling incoming HTTP requests on the same tick\n//\nmodule.exports = function (str) {\n return crypto.createHash('sha1').update(str).digest('hex')\n}", "dangerousExampleEn": "1. var md5 = require('md5');\n2. \n3. console.log(md5('password'));\nLine 3: This is weak for the brute-force attack because it uses md5, a weak hash function.", "safeExampleEn": "1. var bcrypt = require('bcrypt');\n2. \n3. bcrypt.hash(\"password\", 13, function(err, hash) {\n4. console.log(hash);\n5. });\nLine 3: This is safe from the brute-force attack because bcrypt is used to create hash data.", "contexts": [{"lineNo": 18, "eventType": "sink", "messageKey": "jschk.FORBIDDEN.WEAK_ALGORITHM.JS.defect", "params": {"arg0": "sha1"}}]}} {"id": "e6408dd6d49ae70ea0077a1faaf35f646094cec1a231cc7e66c288e224502153", "license": {"spdx": ["MIT"], "repo": "Peppy-Health/bull", "path": "lib/repeatable.js", "repo_head_hexsha": "b8ca885b47698edc848e9876763a17e6aee4a586", "stack_hexsha": "6a3c3400a1d70bbbd93de6c0cb0f92e0b88bf0a1", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of weak cryptographic algorithm", "issueDescriptionEn": "A hash function is a one-way function that receives data of different lengths and maps it to random data of a fixed length. It is commonly used to store user passwords because it always produces the same output for a given input.\nBecause hash can be calculated very quickly, the hash functions, such as MD5 and SHA, may give the illusion of high performance. However they are vulnerable to random brute-force attacks. If you use the hash functions on simple data, they can be saved in the rainbow table, making it insecure. In addition, RC2, RC3, RC4, RC5, RC6, MD4, and DES are also known to be vulnerable.\nThere are many functions used to overcome the disadvantages of MD5 and SHA.\nIn Node.js, bcrypt is one of the functions that is commonly used with outstanding performance and easily replace them. The latest hash algorithms, such as Argon2, PBKDF2, and Scrypt, are also good alternatives. Make sure to add a salt to the hash in SHA-2 i.e. SHA-224, SHA-256, SHA-384, SHA-512.", "issueLineNumber": 49, "entireCode": "'use strict';\n\nconst _ = require('lodash');\nconst parser = require('cron-parser');\nconst crypto = require('crypto');\n\nconst Job = require('./job');\n\nmodule.exports = function(Queue) {\n Queue.prototype.nextRepeatableJob = function(\n name,\n data,\n opts,\n skipCheckExists\n ) {\n const client = this.client;\n const repeat = opts.repeat;\n const prevMillis = opts.prevMillis || 0;\n\n if (!prevMillis && opts.jobId) {\n repeat.jobId = opts.jobId;\n }\n\n const currentCount = repeat.count ? repeat.count + 1 : 1;\n\n if (!_.isUndefined(repeat.limit) && currentCount > repeat.limit) {\n return Promise.resolve();\n }\n\n let now = Date.now();\n now = prevMillis < now ? now : prevMillis;\n\n const nextMillis = getNextMillis(now, repeat);\n if (nextMillis) {\n const jobId = repeat.jobId ? repeat.jobId + ':' : ':';\n const repeatJobKey = getRepeatKey(name, repeat, jobId);\n\n const createNextJob = () => {\n return client\n .zadd(this.keys.repeat, nextMillis, repeatJobKey)\n .then(() => {\n //\n // Generate unique job id for this iteration.\n //\n const customId = getRepeatJobId(\n name,\n jobId,\n nextMillis,\n md5(repeatJobKey)\n );\n now = Date.now();\n const delay = nextMillis - now;\n\n return Job.create(\n this,\n name,\n data,\n _.defaultsDeep(\n {\n repeat: {\n count: currentCount\n },\n jobId: customId,\n delay: delay < 0 ? 0 : delay,\n timestamp: now,\n prevMillis: nextMillis\n },\n opts\n )\n );\n });\n };\n\n if (skipCheckExists) {\n return createNextJob();\n }\n\n // Check that the repeatable job hasn't been removed\n // TODO: a lua script would be better here\n return client\n .zscore(this.keys.repeat, repeatJobKey)\n .then(repeatableExists => {\n // The job could have been deleted since this check\n if (repeatableExists) {\n return createNextJob();\n }\n return Promise.resolve();\n });\n } else {\n return Promise.resolve();\n }\n };\n\n Queue.prototype.removeRepeatable = function(name, repeat) {\n if (typeof name !== 'string') {\n repeat = name;\n name = Job.DEFAULT_JOB_NAME;\n }\n\n return this.isReady().then(() => {\n const jobId = repeat.jobId ? repeat.jobId + ':' : ':';\n const repeatJobKey = getRepeatKey(name, repeat, jobId);\n const repeatJobId = getRepeatJobId(name, jobId, '', md5(repeatJobKey));\n const queueKey = this.keys[''];\n return this.client.removeRepeatable(\n this.keys.repeat,\n this.keys.delayed,\n repeatJobId,\n repeatJobKey,\n queueKey\n );\n });\n };\n\n Queue.prototype.removeRepeatableByKey = function(repeatJobKey) {\n const repeatMeta = this._keyToData(repeatJobKey);\n const queueKey = this.keys[''];\n\n const jobId = repeatMeta.id ? repeatMeta.id + ':' : ':';\n const repeatJobId = getRepeatJobId(\n repeatMeta.name || Job.DEFAULT_JOB_NAME,\n jobId,\n '',\n md5(repeatJobKey)\n );\n\n return this.isReady().then(() => {\n return this.client.removeRepeatable(\n this.keys.repeat,\n this.keys.delayed,\n repeatJobId,\n repeatJobKey,\n queueKey\n );\n });\n };\n\n Queue.prototype._keyToData = function(key) {\n const data = key.split(':');\n\n return {\n key: key,\n name: data[0],\n id: data[1] || null,\n endDate: parseInt(data[2]) || null,\n tz: data[3] || null,\n cron: data[4]\n };\n };\n\n Queue.prototype.getRepeatableJobs = function(start, end, asc) {\n const key = this.keys.repeat;\n start = start || 0;\n end = end || -1;\n return (asc\n ? this.client.zrange(key, start, end, 'WITHSCORES')\n : this.client.zrevrange(key, start, end, 'WITHSCORES')\n ).then(result => {\n const jobs = [];\n for (let i = 0; i < result.length; i += 2) {\n const data = this._keyToData(result[i]);\n jobs.push({\n key: data.key,\n name: data.name,\n id: data.id,\n endDate: data.endDate,\n tz: data.cron ? data.tz : null,\n cron: data.cron || null,\n every: !data.cron ? parseInt(data.tz) : null,\n next: parseInt(result[i + 1])\n });\n }\n return jobs;\n });\n };\n\n Queue.prototype.getRepeatableCount = function() {\n return this.client.zcard(this.toKey('repeat'));\n };\n\n function getRepeatJobId(name, jobId, nextMillis, namespace) {\n return 'repeat:' + md5(name + jobId + namespace) + ':' + nextMillis;\n }\n\n function getRepeatKey(name, repeat, jobId) {\n const endDate = repeat.endDate\n ? new Date(repeat.endDate).getTime() + ':'\n : ':';\n const tz = repeat.tz ? repeat.tz + ':' : ':';\n const suffix = repeat.cron ? tz + repeat.cron : String(repeat.every);\n\n return name + ':' + jobId + endDate + suffix;\n }\n\n function getNextMillis(millis, opts) {\n if (opts.cron && opts.every) {\n throw new Error(\n 'Both .cron and .every options are defined for this repeatable job'\n );\n }\n\n if (opts.every) {\n return Math.floor(millis / opts.every) * opts.every + opts.every;\n }\n\n const currentDate =\n opts.startDate && new Date(opts.startDate) > new Date(millis)\n ? new Date(opts.startDate)\n : new Date(millis);\n const interval = parser.parseExpression(\n opts.cron,\n _.defaults(\n {\n currentDate\n },\n opts\n )\n );\n\n try {\n return interval.next().getTime();\n } catch (e) {\n // Ignore error\n }\n }\n\n function md5(str) {\n return crypto\n .createHash('md5')\n .update(str)\n .digest('hex');\n }\n};", "dangerousExampleEn": "1. var md5 = require('md5');\n2. \n3. console.log(md5('password'));\nLine 3: This is weak for the brute-force attack because it uses md5, a weak hash function.", "safeExampleEn": "1. var bcrypt = require('bcrypt');\n2. \n3. bcrypt.hash(\"password\", 13, function(err, hash) {\n4. console.log(hash);\n5. });\nLine 3: This is safe from the brute-force attack because bcrypt is used to create hash data.", "contexts": [{"lineNo": 34, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "34"}}, {"lineNo": 49, "eventType": "sink", "messageKey": "jschk.FORBIDDEN.WEAK_ALGORITHM.JS.defect", "params": {"arg0": "md5"}}]}} {"id": "ee971fa74b074f5959547aca2952a6ad76660a08c26f27646a0fe5ff69de9594", "license": {"spdx": ["MIT"], "repo": "pouladzade/snack", "path": "libs/deploy.js", "repo_head_hexsha": "af1929cfdc25dfe831fdab095cf0d57017d0c53b", "stack_hexsha": "707f2abd939a9aa64a0685b9439f56a05dbade4a", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of weak cryptographic algorithm", "issueDescriptionEn": "A hash function is a one-way function that receives data of different lengths and maps it to random data of a fixed length. It is commonly used to store user passwords because it always produces the same output for a given input.\nBecause hash can be calculated very quickly, the hash functions, such as MD5 and SHA, may give the illusion of high performance. However they are vulnerable to random brute-force attacks. If you use the hash functions on simple data, they can be saved in the rainbow table, making it insecure. In addition, RC2, RC3, RC4, RC5, RC6, MD4, and DES are also known to be vulnerable.\nThere are many functions used to overcome the disadvantages of MD5 and SHA.\nIn Node.js, bcrypt is one of the functions that is commonly used with outstanding performance and easily replace them. The latest hash algorithms, such as Argon2, PBKDF2, and Scrypt, are also good alternatives. Make sure to add a salt to the hash in SHA-2 i.e. SHA-224, SHA-256, SHA-384, SHA-512.", "issueLineNumber": 75, "entireCode": "\n'use strict'\n\nlet contracts = require('burrow-contracts')\nvar fs = require('fs')\nconst schema = require('./schema').Schema\nvar Linker = require('./link')\nvar md5 = require('md5')\n\nvar Link = new Linker()\nlet project_path = schema.project_path\nlet counter = 0\nlet contractManager = null\nlet linkOrder = null\nlet byteCodeHash = ''\nlet prevLinkOrder = null\n\nmodule.exports = class Deploy {\n constructor (connectionUrl) {\n this.connectionUrl = connectionUrl\n }\n\n _deployCallb (error, contract) {\n try {\n if (error) {\n console.log(\"Error : Contract didn't deploy!!!!!!!!.\")\n } else {\n let str = JSON.stringify(contract, null, 4)\n linkOrder[counter].byteCodeHash = byteCodeHash\n linkOrder[counter].address = contract.address\n let log_file = fs.createWriteStream(project_path + schema.migration + schema.migration_output + linkOrder[counter].contractName + '.json', { flags: 'w' })\n log_file.write(str, 'utf-8')\n log_file.close()\n console.log('Address : ' + contract.address + '\\n')\n console.log(linkOrder[counter].contractName + ' has been successfully deployed! \\n')\n counter++\n\n if (linkOrder.length > counter) { deploy() } else { Deploy._saveLinkOrder() }\n }\n } catch (ex) {\n console.log(ex)\n throw ex\n }\n }\n\n deployAll (link_order, account_name, isForce) {\n try {\n let account_path\n let link_order_path = schema.project_path + schema.build + schema.link_order_file\n if (fs.existsSync(link_order_path)) {\n prevLinkOrder = JSON.parse(fs.readFileSync(link_order_path, 'utf-8'))\n }\n\n linkOrder = link_order\n if (!account_name) account_path = project_path + schema.accounts + schema.default_account\n else account_path = project_path + schema.accounts + '/' + accountName\n\n contractManager = contracts.newContractManagerDev(this.connectionUrl, JSON.parse(fs.readFileSync(account_path, 'utf-8')))\n this._deploy(isForce)\n } catch (ex) {\n console.log(ex)\n throw ex\n }\n }\n\n _deploy (isForce) {\n try {\n console.log(counter + 1 + ')' + this._createDependencyString() + '\\n')\n let byte_code = Link.link(linkOrder[counter].contractName, linkOrder[counter].dependencies, linkOrder)\n\n if (isForce || this._hasContractChanged(byte_code, linkOrder[counter].contractName)) {\n console.log(byte_code + '\\n')\n let contract_obj = JSON.parse(fs.readFileSync(project_path + schema.build + '/' + linkOrder[counter].contractName + '.json', 'utf-8'))\n let ContractFactory = contractManager.newContractFactory(contract_obj.abi)\n byteCodeHash = md5(byte_code)\n ContractFactory.new({ data: byte_code }, this._deployCallb)\n } else {\n console.log('There is no changes in ' + linkOrder[counter].contractName + '\\n')\n counter++\n\n if (linkOrder.length > counter) { this._deploy() } else { Deploy._saveLinkOrder() }\n }\n } catch (ex) {\n console.log(ex)\n throw ex\n }\n }\n\n _createDependencyString () {\n try {\n let str = linkOrder[counter].contractName + ' : '\n for (let i = 0; i < linkOrder[counter].dependencies.length; i++) { str += ' => ' + linkOrder[counter].dependencies[i] }\n\n return str\n } catch (ex) {\n console.log(ex)\n throw ex\n }\n }\n\n _hasContractChanged (byte_code, contract_name) {\n try {\n if (prevLinkOrder == null) {\n return true\n }\n let byte_code_hash = md5(byte_code)\n for (let i = 0; i < prevLinkOrder.length; i++) {\n if (prevLinkOrder[i].contractName == contract_name && prevLinkOrder[i].byteCodeHash == byte_code_hash) {\n linkOrder[counter].address = prevLinkOrder[i].address\n linkOrder[counter].byteCodeHash = byte_code_hash\n return false\n }\n };\n return true\n } catch (ex) {\n console.log(ex)\n throw ex\n }\n }\n\n static _saveLinkOrder () {\n try {\n let str_link_order = JSON.stringify(linkOrder, null, 4)\n let link_file = fs.createWriteStream(schema.project_path + schema.build + schema.link_order_file, { flags: 'w' })\n link_file.write(str_link_order, 'utf-8')\n link_file.close()\n } catch (ex) {\n console.log(ex)\n throw ex\n }\n }\n}", "dangerousExampleEn": "1. var md5 = require('md5');\n2. \n3. console.log(md5('password'));\nLine 3: This is weak for the brute-force attack because it uses md5, a weak hash function.", "safeExampleEn": "1. var bcrypt = require('bcrypt');\n2. \n3. bcrypt.hash(\"password\", 13, function(err, hash) {\n4. console.log(hash);\n5. });\nLine 3: This is safe from the brute-force attack because bcrypt is used to create hash data.", "contexts": [{"lineNo": 71, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "71"}}, {"lineNo": 75, "eventType": "sink", "messageKey": "jschk.FORBIDDEN.WEAK_ALGORITHM.JS.defect", "params": {"arg0": "md5"}}]}} {"id": "b3296effa8a611c7938ce114a8e0bce00aa449ed80598e448bc24bd01d1dc1b6", "license": {"spdx": ["MIT"], "repo": "adobe-rnd/epsagon-node", "path": "src/triggers/aws_lambda.js", "repo_head_hexsha": "3114849f4849f44122ce45c823cb909c25e11fc5", "stack_hexsha": "11f194d7f09aed96bf17ae58d105982f0fd8bc32", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of weak cryptographic algorithm", "issueDescriptionEn": "A hash function is a one-way function that receives data of different lengths and maps it to random data of a fixed length. It is commonly used to store user passwords because it always produces the same output for a given input.\nBecause hash can be calculated very quickly, the hash functions, such as MD5 and SHA, may give the illusion of high performance. However they are vulnerable to random brute-force attacks. If you use the hash functions on simple data, they can be saved in the rainbow table, making it insecure. In addition, RC2, RC3, RC4, RC5, RC6, MD4, and DES are also known to be vulnerable.\nThere are many functions used to overcome the disadvantages of MD5 and SHA.\nIn Node.js, bcrypt is one of the functions that is commonly used with outstanding performance and easily replace them. The latest hash algorithms, such as Argon2, PBKDF2, and Scrypt, are also good alternatives. Make sure to add a salt to the hash in SHA-2 i.e. SHA-224, SHA-256, SHA-384, SHA-512.", "issueLineNumber": 200, "entireCode": "/**\n * @fileoverview Trigger creation for aws-Lambda function invocations\n */\nconst uuid4 = require('uuid4');\nconst md5 = require('md5');\nJSON.sortify = require('json.sortify');\nconst tryRequire = require('../try_require.js');\nconst serverlessEvent = require('../proto/event_pb.js');\nconst errorCode = require('../proto/error_code_pb.js');\nconst eventInterface = require('../event.js');\nconst utils = require('../utils');\nconst resourceUtils = require('../resource_utils/sqs_utils.js');\n\nconst AWS = tryRequire('aws-sdk');\n\n/**\n * Fills the common fields for a trigger event\n * @param {proto.event_pb.Event} trigger The trigger whose fields are being filled\n * @param {string} resourceType The type of the resource that initiated the trigger\n */\nfunction fillCommonFields(trigger, resourceType) {\n trigger.setStartTime(utils.createTimestamp());\n trigger.setDuration(utils.createTimestampFromTime(0));\n trigger.setOrigin('trigger');\n trigger.getResource().setType(resourceType);\n trigger.setErrorCode(errorCode.ErrorCode.OK);\n}\n\n/**\n * Initializes an event representing a trigger to the lambda caused by JSON (invoke)\n * @param {object} event The event the Lambda was triggered with\n * @param {proto.event_pb.Event} trigger An Event to initialize as the trigger\n * @param {object} context The context the Lambda was triggered with\n */\nfunction createJSONTrigger(event, trigger, context) {\n const resource = trigger.getResource();\n trigger.setId(`trigger-${uuid4()}`);\n resource.setName(`trigger-${context.functionName}`);\n resource.setOperation('Event');\n eventInterface.addToMetadata(trigger, {}, {\n data: JSON.stringify(event),\n });\n}\n\n/**\n * Initializes an event representing a trigger to the lambda caused by S3\n * @param {object} event The event the lambda was triggered with\n * @param {proto.event_pb.Event} trigger An Event to initialize as the trigger\n */\nfunction createS3Trigger(event, trigger) {\n const resource = trigger.getResource();\n trigger.setId(event.Records[0].responseElements['x-amz-request-id']);\n resource.setName(event.Records[0].s3.bucket.name);\n resource.setOperation(event.Records[0].eventName);\n eventInterface.addToMetadata(trigger, {\n region: `${event.Records[0].awsRegion}`,\n request_parameters: JSON.stringify(event.Records[0].requestParameters),\n user_identity: JSON.stringify(event.Records[0].userIdentity),\n object_key: `${event.Records[0].s3.object.key}`,\n object_size: `${event.Records[0].s3.object.size}`,\n object_etag: `${event.Records[0].s3.object.eTag}`,\n 'x-amz-request-id': `${event.Records[0].responseElements['x-amz-request-id']}`,\n });\n}\n\n/**\n * Initializes an event representing a trigger to the lambda caused by Kinesis\n * @param {object} event The event the lambda was triggered with\n * @param {proto.event_pb.Event} trigger An Event to initialize as the trigger\n */\nfunction createKinesisTrigger(event, trigger) {\n const resource = trigger.getResource();\n trigger.setId(event.Records[0].eventID);\n resource.setName(event.Records[0].eventSourceARN.split('/').pop());\n resource.setOperation(event.Records[0].eventName.replace('aws:kinesis:', ''));\n eventInterface.addToMetadata(trigger, {\n region: event.Records[0].awsRegion,\n invoke_identity: event.Records[0].invokeIdentityArn,\n sequence_number: event.Records[0].kinesis.sequenceNumber,\n partition_key: event.Records[0].kinesis.partitionKey,\n });\n}\n\n/**\n * Initializes an event representing a trigger to the lambda caused by SNS\n * @param {object} event The event the lambda was triggered with\n * @param {proto.event_pb.Event} trigger An Event to initialize as the trigger\n */\nfunction createSNSTrigger(event, trigger) {\n const resource = trigger.getResource();\n trigger.setId(event.Records[0].Sns.MessageId);\n resource.setName(event.Records[0].EventSubscriptionArn.split(':').slice(-2)[0]);\n resource.setOperation(event.Records[0].Sns.Type);\n eventInterface.addToMetadata(trigger, {\n 'Notification Subject': event.Records[0].Sns.Subject,\n }, {\n 'Notification Message': event.Records[0].Sns.Message,\n });\n}\n\n/**\n * Initializes an event representing a trigger to the lambda caused by SQS\n * @param {object} event The event the lambda was triggered with\n * @param {proto.event_pb.Event} trigger An Event to initialize as the trigger\n */\nfunction createSQSTrigger(event, trigger) {\n const resource = trigger.getResource();\n trigger.setId(event.Records[0].messageId);\n resource.setName(event.Records[0].eventSourceARN.split(':').slice(-1)[0]);\n resource.setOperation('ReceiveMessage');\n eventInterface.addToMetadata(trigger, {\n 'MD5 Of Message Body': event.Records[0].md5OfBody,\n Attributes: event.Records[0].attributes,\n 'Message Attributes': event.Records[0].messageAttributes,\n }, {\n 'Message Body': event.Records[0].body,\n });\n const snsData = resourceUtils.getSNSTrigger(event.Records);\n if (snsData != null) {\n eventInterface.addToMetadata(trigger, { 'SNS Trigger': snsData });\n }\n}\n\n/**\n * Initializes an event representing a trigger to the lambda caused by API Trigger\n * @param {object} event The event the lambda was triggered with\n * @param {proto.event_pb.Event} trigger An Event to initialize as the trigger\n */\nfunction createAPIGatewayTrigger(event, trigger) {\n const resource = trigger.getResource();\n trigger.setId(event.requestContext.requestId);\n resource.setName(event.headers.Host || event.requestContext.apiId);\n resource.setOperation(event.httpMethod);\n eventInterface.addToMetadata(trigger, {\n stage: event.requestContext.stage,\n query_string_parameters: JSON.stringify(event.queryStringParameters),\n path_parameters: JSON.stringify(event.pathParameters),\n path: event.resource,\n }, {\n body: JSON.stringify(event.body),\n headers: JSON.stringify(event.headers),\n requestContext: JSON.stringify(event.requestContext),\n });\n}\n\n/**\n * Initializes an event representing a trigger to the lambda caused by No-Proxy API Trigger\n * @param {object} event The event the lambda was triggered with\n * @param {proto.event_pb.Event} trigger An Event to initialize as the trigger\n */\nfunction createNoProxyAPIGatewayTrigger(event, trigger) {\n const resource = trigger.getResource();\n trigger.setId(event.context['request-id']);\n resource.setName(event.params.header.Host || event.context['api-id']);\n resource.setOperation(event.context['http-method']);\n eventInterface.addToMetadata(trigger, {\n stage: event.context.stage,\n query_string_parameters: JSON.stringify(event.params.querystring),\n path_parameters: JSON.stringify(event.params.path),\n path: event.context['resource-path'],\n }, {\n body: JSON.stringify(event['body-json']),\n headers: JSON.stringify(event.params.header),\n });\n}\n\n/**\n * Initializes an event representing a trigger to the lambda caused by Events\n * @param {object} event The event the lambda was triggered with\n * @param {proto.event_pb.Event} trigger An Event to initialize as the trigger\n */\nfunction createEventsTrigger(event, trigger) {\n const resource = trigger.getResource();\n trigger.setId(event.id);\n resource.setName(event.resources[0].split('/').pop());\n resource.setOperation(event['detail-type']);\n eventInterface.addToMetadata(trigger, {\n region: event.region,\n detail: JSON.stringify(event.detail),\n account: event.account,\n });\n}\n\n/**\n * Initializes an event representing a trigger to the lambda caused by DynamoDB\n * @param {object} event The event the lambda was triggered with\n * @param {proto.event_pb.Event} trigger An Event to initialize as the trigger\n */\nfunction createDynamoDBTrigger(event, trigger) {\n const resource = trigger.getResource();\n const record = event.Records[0];\n let itemHash = '';\n if (AWS) {\n // in case of a delete - hash only the key.\n const item = (\n record.eventName === 'REMOVE' ?\n AWS.DynamoDB.Converter.unmarshall(record.dynamodb.Keys) :\n AWS.DynamoDB.Converter.unmarshall(record.dynamodb.NewImage)\n );\n itemHash = md5(JSON.sortify(item));\n }\n trigger.setId(record.eventID);\n resource.setName(record.eventSourceARN.split('/')[1]);\n resource.setOperation(record.eventName);\n eventInterface.addToMetadata(trigger, {\n region: record.awsRegion,\n sequence_number: record.dynamodb.SequenceNumber,\n item_hash: itemHash,\n });\n}\n\n/**\n * Initializes an event representing a trigger to the lambda caused by API Trigger\n * @param {object} event The event the lambda was triggered with\n * @param {proto.event_pb.Event} trigger An Event to initialize as the trigger\n */\nfunction createElbTrigger(event, trigger) {\n const resource = trigger.getResource();\n trigger.setId(`elb-${uuid4()}`);\n resource.setName(event.headers.host);\n resource.setOperation(event.httpMethod);\n eventInterface.addToMetadata(trigger, {\n query_string_parameters: JSON.stringify(event.queryStringParameters),\n target_group_arn: event.requestContext.elb.targetGroupArn,\n path: event.path,\n }, {\n body: JSON.stringify(event.body),\n headers: JSON.stringify(event.headers),\n });\n}\n\n\n/**\n * Initializes an event representing a trigger to the lambda caused by Cognito\n * @param {object} event The event the lambda was triggered with\n * @param {proto.event_pb.Event} trigger An Event to initialize as the trigger\n */\nfunction createCognitoTrigger(event, trigger) {\n const resource = trigger.getResource();\n trigger.setId(`cognito-${uuid4()}`);\n resource.setName(event.userPoolId);\n resource.setOperation(event.triggerSource);\n eventInterface.addToMetadata(trigger, {\n username: event.userName,\n region: event.region,\n }, {\n caller_context: event.callerContext,\n request: event.request,\n response: event.response,\n });\n}\n\nconst resourceTypeToFactoryMap = {\n s3: createS3Trigger,\n json: createJSONTrigger,\n kinesis: createKinesisTrigger,\n events: createEventsTrigger,\n sns: createSNSTrigger,\n sqs: createSQSTrigger,\n api_gateway: createAPIGatewayTrigger,\n api_gateway_no_proxy: createNoProxyAPIGatewayTrigger,\n dynamodb: createDynamoDBTrigger,\n elastic_load_balancer: createElbTrigger,\n cognito: createCognitoTrigger,\n};\n\n\n/**\n * Creates an {@link proto.event_pb.Event} describing the lambda trigger\n * @param {object} event The event the lambda was triggered with\n * @param {object} context The context the lambda was triggered with\n * @return {proto.event_pb.Event} The trigger of the lambda\n */\nmodule.exports.createFromEvent = function createFromEvent(event, context) {\n let triggerService = 'json';\n if (event) {\n if ('Records' in event) {\n if ('EventSource' in event.Records[0]) {\n triggerService = event.Records[0].EventSource.split(':').pop();\n }\n\n if ('eventSource' in event.Records[0]) {\n triggerService = event.Records[0].eventSource.split(':').pop();\n }\n } else if ('source' in event && event.source) {\n triggerService = event.source.split('.').pop();\n } else if (('requestContext' in event) && ('elb' in event.requestContext)) {\n triggerService = 'elastic_load_balancer';\n } else if ('httpMethod' in event) {\n triggerService = 'api_gateway';\n } else if (('context' in event) && ('http-method' in event.context)) {\n triggerService = 'api_gateway_no_proxy';\n } else if ('dynamodb' in event) {\n triggerService = 'dynamodb';\n } else if ('userPoolId' in event) {\n triggerService = 'cognito';\n }\n }\n\n const resource = new serverlessEvent.Resource();\n const trigger = new serverlessEvent.Event();\n trigger.setResource(resource);\n resourceTypeToFactoryMap[triggerService](event, trigger, context);\n fillCommonFields(trigger, triggerService);\n return trigger;\n};", "dangerousExampleEn": "1. var md5 = require('md5');\n2. \n3. console.log(md5('password'));\nLine 3: This is weak for the brute-force attack because it uses md5, a weak hash function.", "safeExampleEn": "1. var bcrypt = require('bcrypt');\n2. \n3. bcrypt.hash(\"password\", 13, function(err, hash) {\n4. console.log(hash);\n5. });\nLine 3: This is safe from the brute-force attack because bcrypt is used to create hash data.", "contexts": [{"lineNo": 193, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "193"}}, {"lineNo": 200, "eventType": "sink", "messageKey": "jschk.FORBIDDEN.WEAK_ALGORITHM.JS.defect", "params": {"arg0": "md5"}}]}} {"id": "ddf9bbd4d5f3d17d6b07fd2e3081b790b8a9497780df7084589a8b369a5d851b", "license": {"spdx": ["Apache-2.0"], "repo": "zhaoxiaqian/car-bjpermit", "path": "doc/usefull/sign.js", "repo_head_hexsha": "7ed181977afbed7b4d86ea4b602de477be4a244b", "stack_hexsha": "5b4144afb2bc5040f77831c03a5aaf5d64096a3f", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of weak cryptographic algorithm", "issueDescriptionEn": "A hash function is a one-way function that receives data of different lengths and maps it to random data of a fixed length. It is commonly used to store user passwords because it always produces the same output for a given input.\nBecause hash can be calculated very quickly, the hash functions, such as MD5 and SHA, may give the illusion of high performance. However they are vulnerable to random brute-force attacks. If you use the hash functions on simple data, they can be saved in the rainbow table, making it insecure. In addition, RC2, RC3, RC4, RC5, RC6, MD4, and DES are also known to be vulnerable.\nThere are many functions used to overcome the disadvantages of MD5 and SHA.\nIn Node.js, bcrypt is one of the functions that is commonly used with outstanding performance and easily replace them. The latest hash algorithms, such as Argon2, PBKDF2, and Scrypt, are also good alternatives. Make sure to add a salt to the hash in SHA-2 i.e. SHA-224, SHA-256, SHA-384, SHA-512.", "issueLineNumber": 15, "entireCode": "bridge.callHandler('isLogin', '',function(response){\n var lsLogin = response.isLogin;\n if(lsLogin == 'false'){\n bridge.callHandler('showLoginView', '');\n }else if(response.isLogin == 'true'){\n //var userId = response.userid;\n var app_id=\"d584542d105322\";\n var app_secret =\"abeed7c94b550b6946\";\n var phone = response.phoneNum;\n var nick =response.deviceid;\n var openid = phone;\n var gender=0;\n var tmp = Math.round(new Date().getTime()/1000).toString();\n var timestamp = tmp.substr(0,10);\n var sign =md5(app_id+app_secret+gender+nick+phone+openid+timestamp);\n //测试\n bridge.callHandler('pushViewController', {'type':100,'url':'https://dev.quanmin110.com/h5/80/bjjj/nuoche.html?app_id='+app_id+'&phone='+phone+'&nick='+nick+'&openid='+openid+'&gender='+gender+'×tamp='+timestamp+'&sign='+sign});\n //正式\n bridge.callHandler('pushViewController', {'type':100,'url':'https://api.quanmin110.com/h5/80/bjjj/nuoche.html?app_id='+app_id+'&phone='+phone+'&nick='+nick+'&openid='+openid+'&gender='+gender+'×tamp='+timestamp+'&sign='+sign});\n }\n});", "dangerousExampleEn": "1. var md5 = require('md5');\n2. \n3. console.log(md5('password'));\nLine 3: This is weak for the brute-force attack because it uses md5, a weak hash function.", "safeExampleEn": "1. var bcrypt = require('bcrypt');\n2. \n3. bcrypt.hash(\"password\", 13, function(err, hash) {\n4. console.log(hash);\n5. });\nLine 3: This is safe from the brute-force attack because bcrypt is used to create hash data.", "contexts": [{"lineNo": 5, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "5"}}, {"lineNo": 15, "eventType": "sink", "messageKey": "jschk.FORBIDDEN.WEAK_ALGORITHM.JS.defect", "params": {"arg0": "md5"}}]}} {"id": "2014910dde53b65a481e2a0ddc6e5720951dbfd550de7035b131df089a1d2fc5", "license": {"spdx": ["MIT"], "repo": "khietvo-agilityio/sapphire-express", "path": "lib/redisStore.js", "repo_head_hexsha": "2f7258db4429fd3e25a979e6c5a82dbfb14409c6", "stack_hexsha": "9f04ba08e0fcddb34c7d0d165034e656669942e4", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of weak cryptographic algorithm", "issueDescriptionEn": "A hash function is a one-way function that receives data of different lengths and maps it to random data of a fixed length. It is commonly used to store user passwords because it always produces the same output for a given input.\nBecause hash can be calculated very quickly, the hash functions, such as MD5 and SHA, may give the illusion of high performance. However they are vulnerable to random brute-force attacks. If you use the hash functions on simple data, they can be saved in the rainbow table, making it insecure. In addition, RC2, RC3, RC4, RC5, RC6, MD4, and DES are also known to be vulnerable.\nThere are many functions used to overcome the disadvantages of MD5 and SHA.\nIn Node.js, bcrypt is one of the functions that is commonly used with outstanding performance and easily replace them. The latest hash algorithms, such as Argon2, PBKDF2, and Scrypt, are also good alternatives. Make sure to add a salt to the hash in SHA-2 i.e. SHA-224, SHA-256, SHA-384, SHA-512.", "issueLineNumber": 29, "entireCode": "var events = require('events');\nvar CONFIG = require('./config').CONFIG;\nvar Q = require('q');\nvar redis = require('redis');\nvar uuid = require('node-uuid');\nvar crypto = require('crypto');\n\n// use config to setup parameters\nvar redisClient = redis.createClient();\n\nvar Session = new Class(\n{\n\tinitialize : function(sessionId)\n\t{\n\t\tthis.sessionId = sessionId;\n\t\tthis.session = null;\n\t\tdata = null;\n\t},\n\n\tload : function()\n\t{\n\t\tif (this.session) return Q(this.session);\n\n\t\tif (!this.sessionId)\n\t\t{\n\t\t\tthis.sessionId = uuid.v4();\n\t\t\tdata = JSON.stringify({});\n\n\t\t\tvar md5sum = crypto.createHash('md5');\n\t\t\tmd5sum.update(data);\n\t\t\tthis.hash = md5sum.digest('hex');\n\n\t\t\tthis.session = {};\n\t\t\treturn Q(this.session);\n\t\t}\n\n\t\tvar deferred = Q.defer();\n\t\tredisClient.get(this.sessionId, function(err, data)\n\t\t{\n\t\t\tif (data == null)\n\t\t\t{\n\t\t\t\tthis.sessionId = uuid.v4();\n\t\t\t\tdata = JSON.stringify({});\n\t\t\t\tthis.session = {};\n\t\t\t}\n\n\t\t\tvar md5sum = crypto.createHash('md5');\n\t\t\tmd5sum.update(data);\n\t\t\tthis.hash = md5sum.digest('hex');\n\n\t\t\tthis.session = JSON.parse(data);\n\n\t\t\tredisClient.expire(this.sessionId, CONFIG.sessionExpire?CONFIG.sessionExpire:(60 * 60 * 24));\n\n\t\t\tdeferred.resolve(this.session);\n\t\t}.bind(this));\n\n\t\treturn deferred.promise;\n\t},\n\n\tgetSessionId : function()\n\t{\n\t\treturn this.sessionId;\n\t},\n\n\tset : function(name, value)\n\t{\n\t\tthis.session[name] = value;\n\t},\n\n\tupdate : function(session)\n\t{\n\t\tthis.session = session;\n\t\tredisClient.set(this.sessionId, JSON.stringify(this.session));\n\t\tredisClient.expire(this.sessionId, CONFIG.sessionExpire?CONFIG.sessionExpire:(60 * 60 * 24));\n\t},\n\n\tsave : function()\n\t{\n\t\tdata = JSON.stringify(this.session);\n\n\t\tvar md5sum = crypto.createHash('md5');\n\t\tmd5sum.update(data);\n\t\tvar hash = md5sum.digest('hex');\n\n\t\tif (hash != this.hash)\n\t\t{\n\t\t\tthis.update(this.session);\n\t\t}\n\t}\n});\n\nSession.implement(events.EventEmitter.prototype);\n\nmodule.exports = function(req, res, sessionId)\n{\n\treturn new Session(sessionId);\n};\n", "dangerousExampleEn": "1. var md5 = require('md5');\n2. \n3. console.log(md5('password'));\nLine 3: This is weak for the brute-force attack because it uses md5, a weak hash function.", "safeExampleEn": "1. var bcrypt = require('bcrypt');\n2. \n3. bcrypt.hash(\"password\", 13, function(err, hash) {\n4. console.log(hash);\n5. });\nLine 3: This is safe from the brute-force attack because bcrypt is used to create hash data.", "contexts": [{"lineNo": 24, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "25"}}, {"lineNo": 29, "eventType": "sink", "messageKey": "jschk.FORBIDDEN.WEAK_ALGORITHM.JS.defect", "params": {"arg0": "md5"}}]}} {"id": "c917b5bcfd0daf5697263e6929f0abebe6d47f14aa39ac591c619c9655595f79", "license": {"spdx": ["Apache-2.0"], "repo": "422314646/network_homework", "path": "config/utils.js", "repo_head_hexsha": "81fa41ebfce29acc639c4694c534f967d8239ce4", "stack_hexsha": "a3874b4ea175ae9ab7e1fac85e8b99214e189576", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of weak cryptographic algorithm", "issueDescriptionEn": "A hash function is a one-way function that receives data of different lengths and maps it to random data of a fixed length. It is commonly used to store user passwords because it always produces the same output for a given input.\nBecause hash can be calculated very quickly, the hash functions, such as MD5 and SHA, may give the illusion of high performance. However they are vulnerable to random brute-force attacks. If you use the hash functions on simple data, they can be saved in the rainbow table, making it insecure. In addition, RC2, RC3, RC4, RC5, RC6, MD4, and DES are also known to be vulnerable.\nThere are many functions used to overcome the disadvantages of MD5 and SHA.\nIn Node.js, bcrypt is one of the functions that is commonly used with outstanding performance and easily replace them. The latest hash algorithms, such as Argon2, PBKDF2, and Scrypt, are also good alternatives. Make sure to add a salt to the hash in SHA-2 i.e. SHA-224, SHA-256, SHA-384, SHA-512.", "issueLineNumber": 3, "entireCode": "function setParamSign(params) {\n if (params) {\n var sign = md5(params);\n if (typeof params == \"string\") {\n params += (\"&sign=\" + sign);\n }\n else {\n params[\"sign\"] = sign;\n }\n }\n return sign;\n}\nfunction jsonSort(jsonObj) {\n var arr=[];\n for(var key in jsonObj){\n arr.push(key)\n }\n arr.sort();\n var str='';\n for(var i in arr){\n str +=jsonObj[arr[i]]\n }\n\n return str\n}\nfunction getDate(){\n\n var myDate = new Date();\n //获取当前年\n var year = myDate.getFullYear();\n //获取当前月\n var month = myDate.getMonth() + 1;\n //获取当前日\n var date = myDate.getDate();\n var h = myDate.getHours(); //获取当前小时数(0-23)\n var m = myDate.getMinutes(); //获取当前分钟数(0-59)\n var s = myDate.getSeconds();\n //获取当前时间\n var now = year + '-' + conver(month) + \"-\" + conver(date) + \" \" + conver(h) + ':' + conver(m) + \":\" + conver(s);\n return now;\n}\nfunction conver(s) {\n return s < 10 ? '0' + s : s;\n}", "dangerousExampleEn": "1. var md5 = require('md5');\n2. \n3. console.log(md5('password'));\nLine 3: This is weak for the brute-force attack because it uses md5, a weak hash function.", "safeExampleEn": "1. var bcrypt = require('bcrypt');\n2. \n3. bcrypt.hash(\"password\", 13, function(err, hash) {\n4. console.log(hash);\n5. });\nLine 3: This is safe from the brute-force attack because bcrypt is used to create hash data.", "contexts": [{"lineNo": 2, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "2"}}, {"lineNo": 3, "eventType": "sink", "messageKey": "jschk.FORBIDDEN.WEAK_ALGORITHM.JS.defect", "params": {"arg0": "md5"}}]}} {"id": "8567047a10bde138d44a8ca1570cf8de25b245ce0407c142fb5991ad41670ab2", "license": {"spdx": ["MIT"], "repo": "daggerml/stack-deploy", "path": "index.js", "repo_head_hexsha": "14784f34dcb165008f14f6cffc663ea0bf9f9303", "stack_hexsha": "14b2e7a230fe2a75af08e3fdcca6a6a02df6f9c1", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of weak cryptographic algorithm", "issueDescriptionEn": "A hash function is a one-way function that receives data of different lengths and maps it to random data of a fixed length. It is commonly used to store user passwords because it always produces the same output for a given input.\nBecause hash can be calculated very quickly, the hash functions, such as MD5 and SHA, may give the illusion of high performance. However they are vulnerable to random brute-force attacks. If you use the hash functions on simple data, they can be saved in the rainbow table, making it insecure. In addition, RC2, RC3, RC4, RC5, RC6, MD4, and DES are also known to be vulnerable.\nThere are many functions used to overcome the disadvantages of MD5 and SHA.\nIn Node.js, bcrypt is one of the functions that is commonly used with outstanding performance and easily replace them. The latest hash algorithms, such as Argon2, PBKDF2, and Scrypt, are also good alternatives. Make sure to add a salt to the hash in SHA-2 i.e. SHA-224, SHA-256, SHA-384, SHA-512.", "issueLineNumber": 322, "entireCode": "// Generated by CoffeeScript 2.5.1\n(function() {\n var CfnError, CfnExit, CfnTool, CfnTransformer, GetOpts, VERSION, assert, completions, fn, fs, log, os, path, sq, yaml,\n indexOf = [].indexOf;\n\n fs = require('fs');\n\n os = require('os');\n\n path = require('path');\n\n sq = require('shell-quote');\n\n GetOpts = require('./lib/GetOpts');\n\n yaml = require('js-yaml');\n\n ({\n strict: assert\n } = require('assert'));\n\n completions = require('./lib/completions');\n\n fn = require('./lib/fn');\n\n log = require('./lib/log');\n\n CfnError = require('./lib/CfnError');\n\n CfnExit = require('./lib/CfnExit');\n\n CfnTransformer = require('./lib/cfn-transformer');\n\n ({\n version: VERSION\n } = require('./package.json'));\n\n CfnTool = class CfnTool {\n constructor() {\n this.options = new GetOpts({\n alias: {\n bucket: 'b',\n continue: 'c',\n help: 'h',\n keep: 'k',\n linter: 'l',\n parameters: 'P',\n profile: 'p',\n quiet: 'q',\n region: 'r',\n tags: 't',\n verbose: 'v',\n version: 'V'\n },\n boolean: ['continue', 'help', 'keep', 'quiet', 'verbose', 'version'],\n string: {\n bucket: '',\n linter: '',\n parameters: '\"= ...\"',\n profile: '',\n region: '',\n tags: '\"= ...\"'\n },\n positional: {\n command: null,\n template: '',\n stackname: ''\n },\n complete: {\n bucket: completions.none,\n continue: completions.none,\n linter: completions.none,\n parameters: completions.none,\n profile: completions.profile,\n region: completions.region,\n tags: completions.none,\n template: completions.none,\n stackname: completions.none\n },\n unknown: (x) => {\n return this.abort(new CfnError(`unknown option: '${x}'`));\n }\n });\n this.defaultOptionsSpec = ['help', 'version', 'command'];\n this.optionsSpecs = {\n deploy: ['bucket', 'continue', 'help', 'keep', 'linter', 'parameters', 'profile', 'quiet', 'region', 'tags', 'verbose', 'command', 'template', 'stackname'],\n transform: ['help', 'linter', 'profile', 'quiet', 'region', 'verbose', 'command', 'template'],\n update: ['help', 'parameters', 'profile', 'quiet', 'region', 'verbose', 'command', 'stackname']\n };\n this.opts = {};\n this.allCmds = Object.keys(this.optionsSpecs);\n }\n\n exit(status = 0) {\n this.exitStatus = status;\n this.sideEffects = log.sideEffects();\n throw new CfnExit(status);\n }\n\n quit(msg, status = 0) {\n log.console(msg);\n return this.exit(status);\n }\n\n abort(e) {\n var body;\n if (e.code === 'ENOENT') {\n e = new CfnError(e.message);\n }\n body = e instanceof CfnError ? e.body : e.body || e.stack;\n log.error(e.message, {body});\n return this.exit(1);\n }\n\n usageCmd(prog, cmd) {\n var lpad, opts;\n this.options.configure((cmd ? this.optionsSpecs[cmd] : this.defaultOptionsSpec), this.env);\n lpad = function(x) {\n return ` ${x}`;\n };\n opts = this.options.usage().map(lpad).join(\"\\n\");\n cmd = cmd ? ` ${cmd}` : '';\n opts = opts ? `\\n${opts}` : '';\n return `${prog}${cmd}${opts}`;\n }\n\n usage(prog, cmd, status) {\n var manp, text, ucmd;\n manp = [prog].concat(cmd ? [cmd] : []).join('-');\n ucmd = fn.partial(this.usageCmd, this, prog);\n text = cmd ? ucmd(cmd) : [null].concat(this.allCmds).map(ucmd).join(\"\\n\\n\");\n return this.quit(`${text}\n\nSee the manpage:\n* cmd: man ${manp}\n* url: http://htmlpreview.github.io/?https://github.com/daggerml/cfn-tool/blob/${VERSION}/man/${manp}.html`, status);\n }\n\n version() {\n return this.quit(VERSION);\n }\n\n setAwsEnv(opts) {\n var r1, r2;\n if (opts.region) {\n (this.env.AWS_REGION = this.env.AWS_DEFAULT_REGION = opts.region);\n }\n if (opts.profile) {\n (this.env.AWS_PROFILE = opts.profile);\n }\n [r1, r2] = [this.env.AWS_REGION, this.env.AWS_DEFAULT_REGION];\n if ((r2 && !r1) || (r1 && r2 && r1 !== r2)) {\n this.env.AWS_REGION = r2;\n }\n if (r1 && !r2) {\n this.env.AWS_DEFAULT_REGION = r1;\n }\n return opts;\n }\n\n setLogLevel(opts) {\n log.level((function() {\n switch (false) {\n case !opts.verbose:\n return 'verbose';\n case !opts.quiet:\n return 'error';\n default:\n return 'info';\n }\n })());\n return opts;\n }\n\n //----------------------------------------------------------------------------\n // PUBLIC API\n //----------------------------------------------------------------------------\n test(f) {\n var e;\n fn.testing(true);\n try {\n return f();\n } catch (error) {\n e = error;\n if (e.name === 'CfnExit') {\n return fn.testing(false) || this;\n } else {\n return this.test(() => {\n return this.abort(e);\n });\n }\n }\n }\n\n prod(f) {\n var e;\n try {\n return f();\n } catch (error) {\n e = error;\n if (e.name === 'CfnExit') {\n return process.exit(e.status);\n } else {\n return this.prod(() => {\n return this.abort(e);\n });\n }\n }\n }\n\n complete(argv, env) {\n var $0, c, cl, command, cp, i, left, len, prefix, prev, ref, right, spec, suffix, words, x;\n this.env = env;\n log.level('console');\n [$0, prefix, prev] = argv.slice(2);\n cl = this.env.COMP_LINE;\n cp = parseInt(this.env.COMP_POINT);\n suffix = cl.slice(cp).match(/[^ ]*/);\n left = cl.slice(0, cp - prefix.length);\n right = cl.slice(cp + suffix.length);\n words = sq.parse([left, right].filter(function(x) {\n return x;\n }).join(' ')).slice(1);\n command = words[0];\n if ($0 === prev && words.length < 2) {\n this.options.configure(this.defaultOptionsSpec, this.env, false);\n this.quit(completions.list(prefix, this.allCmds.concat(this.options.completeOpt(words))));\n } else if ((spec = this.optionsSpecs[command])) {\n this.options.configure(spec, this.env, false);\n this.opts = this.options.completeOpt();\n if (indexOf.call(this.opts, prev) >= 0) {\n if ((c = this.options.master.complete[prev.replace(/^-+/, '')])) {\n this.quit(c(prefix));\n }\n }\n if (prefix.startsWith('-')) {\n this.quit(completions.list(prefix, this.options.completeOpt(words)));\n }\n this.opts = this.options.parse(words, {\n noenv: true\n });\n ref = this.options.config.positional;\n for (i = 0, len = ref.length; i < len; i++) {\n x = ref[i];\n if (this.opts[x]) {\n continue;\n }\n if ((c = this.options.master.complete[x])) {\n this.quit(c(prefix));\n }\n }\n this.quit();\n }\n return this.quit(completions.file(prefix));\n }\n\n cli(argv, env) {\n var cfn, cmdKnown, haveOverride, i, k, len, mkparams, params, paramsfile, prog, ref, ref1, ref2, ref3, ref4, res, spec, v, x;\n this.env = env;\n if ((spec = this.optionsSpecs[argv[2]])) {\n this.options.configure(spec);\n } else {\n this.options.configure(this.defaultOptionsSpec);\n }\n prog = log.PROG;\n argv = argv.slice(2);\n this.opts = this.setLogLevel(this.setAwsEnv(this.options.parse(argv)));\n this.opts.tmpdir = fn.tmpdir('cfn-tool-', this.opts.keep);\n cmdKnown = (ref = this.opts.command, indexOf.call(this.allCmds, ref) >= 0) || !this.opts.command;\n fn.assertOk(cmdKnown, `unknown command: '${this.opts.command}'`);\n switch (false) {\n case !this.opts.help:\n this.usage(prog, this.opts.command);\n break;\n case !this.opts.version:\n this.version();\n break;\n case !!this.opts.command:\n this.usage(prog, null, 1);\n }\n this.options.validateArgs(this.opts);\n switch (this.opts.command) {\n case 'transform':\n Object.assign(this.opts, {\n dovalidate: false,\n dopackage: false,\n bucket: 'example-bucket',\n s3bucket: 'example-bucket'\n });\n log.verbose('preparing template');\n cfn = new CfnTransformer({opts: this.opts});\n res = cfn.writeTemplate(this.opts.template);\n log.console(fs.readFileSync(res.tmpPath).toString('utf-8').trimRight());\n break;\n case 'deploy':\n Object.assign(this.opts, {\n dovalidate: true,\n dopackage: true,\n s3bucket: this.opts.bucket\n });\n log.info('preparing templates');\n cfn = new CfnTransformer({opts: this.opts});\n res = cfn.writeTemplate(this.opts.template);\n if (res.nested.length > 1) {\n if (!this.opts.bucket) {\n throw new CfnError('bucket required for nested stacks');\n }\n log.info('uploading templates to S3');\n fn.execShell(fn.shprintf(`aws s3 sync --size-only %{%S} %{%S}`, this.opts.tmpdir, `s3://${this.opts.bucket}`));\n }\n mkparams = (x) => {\n var f, p;\n if (x) {\n p = JSON.stringify(sq.parse(x).map(function(x) {\n var k, v;\n [k, v] = fn.split(x, '=', 2);\n return {\n ParameterKey: k,\n ParameterValue: v\n };\n }));\n f = `${path.join(this.opts.tmpdir, fn.md5(p))}-params.json`;\n fs.writeFileSync(f, p);\n return `file://${f}`;\n }\n };\n log.info('deploying stack');\n fn.execShell(fn.shprintf(`aws cloudformation deploy --template-file %{%S} --stack-name %{%S} --capabilities CAPABILITY_NAMED_IAM CAPABILITY_IAM CAPABILITY_AUTO_EXPAND %{--s3-bucket %S }%{--parameter-overrides %S }%{--tags %A}`, res.tmpPath, this.opts.stackname, this.opts.bucket, mkparams(this.opts.parameters), this.opts.tags));\n log.info('done -- no errors');\n break;\n case 'update':\n res = JSON.parse(fn.execShell(`aws cloudformation describe-stacks --stack-name '${this.opts.stackname}'`));\n params = res != null ? (ref1 = res.Stacks) != null ? (ref2 = ref1[0]) != null ? (ref3 = ref2.Parameters) != null ? ref3.reduce(function(xs, x) {\n var k;\n k = x.ParameterKey;\n return fn.assoc(xs, k, {\n ParameterKey: k,\n UsePreviousValue: true\n });\n }, {}) : void 0 : void 0 : void 0 : void 0;\n fn.assertOk(Object.keys(params).length, `stack '${this.opts.stackname}' has no parameters`);\n haveOverride = null;\n if (this.opts.parameters) {\n ref4 = sq.parse(this.opts.parameters) || [];\n for (i = 0, len = ref4.length; i < len; i++) {\n x = ref4[i];\n [k, v] = fn.split(x, '=', 2);\n fn.assertOk(k && v, `parameter: expected =: got '${x}'`);\n fn.assertOk(params[k], `stack '${this.opts.stackname}' has no parameter '${k}'`);\n haveOverride = params[k] = {\n ParameterKey: k,\n ParameterValue: v\n };\n }\n }\n fn.assertOk(haveOverride, 'parameter overrides required');\n params = JSON.stringify(fn.objVals(params));\n paramsfile = `${path.join(this.opts.tmpdir, fn.md5(params))}-params.json`;\n fs.writeFileSync(paramsfile, params);\n paramsfile = `file://${paramsfile}`;\n fn.execShell(fn.shprintf(`aws cloudformation update-stack --stack-name %{%S} --parameters %{%S} --capabilities CAPABILITY_IAM CAPABILITY_NAMED_IAM CAPABILITY_AUTO_EXPAND --use-previous-template`, this.opts.stackname, paramsfile));\n fn.execShell(fn.shprintf(`aws cloudformation wait stack-update-complete --stack-name %{%S}`, this.opts.stackname));\n log.info('done -- no errors');\n }\n return this.quit();\n }\n\n };\n\n module.exports = CfnTool;\n\n}).call(this);\n\n//# sourceMappingURL=index.js.map", "dangerousExampleEn": "1. var md5 = require('md5');\n2. \n3. console.log(md5('password'));\nLine 3: This is weak for the brute-force attack because it uses md5, a weak hash function.", "safeExampleEn": "1. var bcrypt = require('bcrypt');\n2. \n3. bcrypt.hash(\"password\", 13, function(err, hash) {\n4. console.log(hash);\n5. });\nLine 3: This is safe from the brute-force attack because bcrypt is used to create hash data.", "contexts": [{"lineNo": 313, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "313"}}, {"lineNo": 322, "eventType": "sink", "messageKey": "jschk.FORBIDDEN.WEAK_ALGORITHM.JS.defect", "params": {"arg0": "md5"}}]}} {"id": "bffb5200e96a87e8cbd5e0d9ae55150389a8526e08e3bbc2a45fe86cfc5eb3a5", "license": {"spdx": ["MIT"], "repo": "dallasclark/digital-data-manager", "path": "src/integrations/AdSpire.js", "repo_head_hexsha": "7c1e92b7284172f201905a670734514575ea3c06", "stack_hexsha": "c6ab53ad1fba8c22b84b13fe9e5f520550e29d6a", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of weak cryptographic algorithm", "issueDescriptionEn": "A hash function is a one-way function that receives data of different lengths and maps it to random data of a fixed length. It is commonly used to store user passwords because it always produces the same output for a given input.\nBecause hash can be calculated very quickly, the hash functions, such as MD5 and SHA, may give the illusion of high performance. However they are vulnerable to random brute-force attacks. If you use the hash functions on simple data, they can be saved in the rainbow table, making it insecure. In addition, RC2, RC3, RC4, RC5, RC6, MD4, and DES are also known to be vulnerable.\nThere are many functions used to overcome the disadvantages of MD5 and SHA.\nIn Node.js, bcrypt is one of the functions that is commonly used with outstanding performance and easily replace them. The latest hash algorithms, such as Argon2, PBKDF2, and Scrypt, are also good alternatives. Make sure to add a salt to the hash in SHA-2 i.e. SHA-224, SHA-256, SHA-384, SHA-512.", "issueLineNumber": 244, "entireCode": "import cleanObject from '@segmentstream/utils/cleanObject'\nimport { getProp } from '@segmentstream/utils/dotProp'\nimport ipToLong from '@segmentstream/utils/ipToLong'\nimport normalizeString from '@segmentstream/utils/normalizeString'\nimport md5 from 'crypto-js/md5'\nimport Integration from '../Integration'\nimport {\n VIEWED_PAGE,\n VIEWED_PRODUCT_DETAIL,\n VIEWED_PRODUCT_LISTING,\n COMPLETED_TRANSACTION,\n VIEWED_CART\n} from '../events/semanticEvents'\n\nfunction mapLineItems (lineItems) {\n lineItems = lineItems || []\n return lineItems.map((lineItem) => {\n const product = lineItem.product || {}\n product.category = product.category || []\n return cleanObject({\n pid: product.id,\n pname: product.name,\n cid: product.categoryId,\n cname: product.category[product.category.length - 1],\n price: product.unitSalePrice,\n quantity: lineItem.quantity || 1,\n currency: product.currency,\n variant_id: product.skuCode\n })\n })\n}\n\nclass AdSpire extends Integration {\n constructor (digitalData, options) {\n const optionsWithDefaults = Object.assign({\n siteId: ''\n }, options)\n\n super(digitalData, optionsWithDefaults)\n\n this.addTag({\n type: 'script',\n attr: {\n src: `//track.adspire.io/code/${options.siteId}/`\n }\n })\n }\n\n getEnrichableEventProps (event) {\n switch (event.name) {\n case VIEWED_PAGE:\n return ['page.type']\n case VIEWED_PRODUCT_DETAIL:\n return ['product']\n case COMPLETED_TRANSACTION:\n return ['transaction', 'user.email', 'user.firstName', 'user.lastName']\n case VIEWED_PRODUCT_LISTING:\n return ['listing.categoryId', 'listing.category']\n case VIEWED_CART:\n return ['cart']\n default:\n return []\n }\n }\n\n getEventValidationConfig (event) {\n const config = {\n [VIEWED_PAGE]: {\n fields: ['page.type'],\n validations: {\n errors: ['required'],\n warnings: ['string']\n }\n },\n [VIEWED_PRODUCT_DETAIL]: {\n fields: [\n 'product.id',\n 'product.name',\n 'product.categoryId',\n 'product.category',\n 'product.unitSalePrice',\n 'product.currency',\n 'product.url',\n 'product.imageUrl'\n ],\n validations: {\n 'product.id': {\n errors: ['required'],\n warnings: ['string']\n },\n 'product.name': {\n warnings: ['required', 'string']\n },\n 'product.categoryId': {\n warnings: ['required', 'string']\n },\n 'product.category': {\n warnings: ['required', 'array']\n },\n 'product.unitSalePrice': {\n warnings: ['required', 'numeric']\n },\n 'product.currency': {\n warnings: ['required', 'string']\n },\n 'product.url': {\n warnings: ['required', 'string']\n },\n 'product.imageUrl': {\n warnings: ['required', 'string']\n }\n }\n },\n [VIEWED_PRODUCT_LISTING]: {\n fields: [\n 'listing.categoryId',\n 'listing.category'\n ],\n validations: {\n 'listing.categoryId': {\n warnings: ['required', 'string']\n },\n 'listing.category': {\n warnings: ['required', 'array']\n }\n }\n },\n [VIEWED_CART]: {\n fields: [\n 'cart.lineItems[].product.id',\n 'cart.lineItems[].product.name',\n 'cart.lineItems[].product.categoryId',\n 'cart.lineItems[].product.category',\n 'cart.lineItems[].product.unitSalePrice',\n 'cart.lineItems[].product.currency',\n 'cart.lineItems[].quantity'\n ],\n validations: {\n 'cart.lineItems[].product.id': {\n errors: ['required'],\n warnings: ['string']\n },\n 'cart.lineItems[].product.name': {\n warnings: ['required', 'string']\n },\n 'cart.lineItems[].product.categoryId': {\n warnings: ['required', 'string']\n },\n 'cart.lineItems[].product.category': {\n warnings: ['required', 'array']\n },\n 'cart.lineItems[].product.unitSalePrice': {\n warnings: ['required', 'numeric']\n },\n 'cart.lineItems[].product.currency': {\n warnings: ['required', 'string']\n },\n 'cart.lineItems[].quantity': {\n warnings: ['required', 'numeric']\n }\n }\n },\n [COMPLETED_TRANSACTION]: {\n fields: [\n 'transaction.orderId',\n 'transaction.total',\n 'transaction.isFirst',\n 'transaction.vouchers',\n 'transaction.lineItems[].product.id',\n 'transaction.lineItems[].product.name',\n 'transaction.lineItems[].product.categoryId',\n 'transaction.lineItems[].product.category',\n 'transaction.lineItems[].product.unitSalePrice',\n 'transaction.lineItems[].product.currency',\n 'transaction.lineItems[].quantity',\n 'user.email',\n 'user.firstName',\n 'user.lastName'\n ],\n validations: {\n 'transaction.orderId': {\n errors: ['required'],\n warnings: ['string']\n },\n 'transaction.total': {\n warnings: ['required', 'numeric']\n },\n 'transaction.lineItems[].product.id': {\n warnings: ['required', 'string']\n },\n 'transaction.lineItems[].product.name': {\n warnings: ['required', 'string']\n },\n 'transaction.lineItems[].product.categoryId': {\n warnings: ['required', 'string']\n },\n 'transaction.lineItems[].product.category': {\n warnings: ['required', 'array']\n },\n 'transaction.lineItems[].product.unitSalePrice': {\n warnings: ['required', 'numeric']\n },\n 'transaction.lineItems[].product.currency': {\n warnings: ['required', 'string']\n },\n 'transaction.lineItems[].quantity': {\n warnings: ['required', 'numeric']\n },\n 'transaction.isFirst': {\n warnings: ['boolean']\n },\n 'transaction.vouchers': {\n warning: ['array']\n }\n }\n }\n }\n\n return config[event.name]\n }\n\n getSemanticEvents () {\n return [\n VIEWED_PAGE,\n VIEWED_PRODUCT_DETAIL,\n VIEWED_PRODUCT_LISTING,\n COMPLETED_TRANSACTION,\n VIEWED_CART\n ]\n }\n\n initialize () {\n window.adspire_track = window.adspire_track || []\n }\n\n isLoaded () {\n return !!window.adspire_code_loaded\n }\n\n getEmailMd5 (event) {\n const email = getProp(event, 'user.email')\n if (email) {\n const emailNorm = normalizeString(email)\n const emailMd5 = md5(emailNorm).toString()\n return emailMd5\n }\n return undefined\n }\n\n trackEvent (event) {\n const methods = {\n [VIEWED_PAGE]: 'onViewedPage',\n [VIEWED_PRODUCT_DETAIL]: 'onViewedProductDetail',\n [COMPLETED_TRANSACTION]: 'onCompletedTransaction',\n [VIEWED_PRODUCT_LISTING]: 'onViewedProductListing',\n [VIEWED_CART]: 'onViewedCart'\n }\n\n const method = methods[event.name]\n if (method) {\n this[method](event)\n }\n }\n\n onViewedPage (event) {\n this.pageTracked = false\n\n const { page } = event\n const ip = getProp(event, 'context.ip')\n\n if (ip) {\n window.adspire_ip = ipToLong(ip)\n }\n\n if (page && page.type === 'home') {\n this.onViewedHome()\n }\n\n if (!this.pageTracked) {\n setTimeout(() => {\n if (!this.pageTracked) {\n this.onViewedOther()\n }\n }, 100)\n }\n }\n\n onViewedHome () {\n window.adspire_track.push({\n TypeOfPage: 'general'\n })\n this.pageTracked = true\n }\n\n onViewedOther () {\n window.adspire_track.push({\n TypeOfPage: 'other'\n })\n this.pageTracked = true\n }\n\n onViewedProductListing (event) {\n const cid = getProp(event, 'listing.categoryId')\n let cname\n const category = getProp(event, 'listing.category')\n if (category && Array.isArray(category)) {\n cname = category[category.length - 1]\n }\n\n window.adspire_track.push(cleanObject({\n TypeOfPage: 'category',\n Category: { cid, cname }\n }))\n this.pageTracked = true\n }\n\n onViewedProductDetail (event) {\n const product = event.product || {}\n const cid = product.categoryId\n const category = product.category || []\n const cname = category[category.length - 1]\n\n window.adspire_track.push(cleanObject({\n TypeOfPage: 'product',\n Category: { cid, cname },\n Product: {\n pid: product.id,\n pname: product.name,\n url: product.url,\n picture: product.imageUrl,\n price: product.unitSalePrice,\n currency: product.currency,\n variant_id: product.skuCode\n }\n }))\n this.pageTracked = true\n }\n\n onViewedCart (event) {\n const cart = event.cart || {}\n\n window.adspire_track.push({\n TypeOfPage: 'basket',\n Basket: mapLineItems(cart.lineItems)\n })\n this.pageTracked = true\n }\n\n onCompletedTransaction (event) {\n const transaction = event.transaction || {}\n const user = event.user || {}\n transaction.vouchers = transaction.vouchers || []\n\n window.adspire_track.push({\n TypeOfPage: 'confirm',\n Order: cleanObject({\n id: transaction.orderId,\n totalprice: transaction.total,\n coupon: transaction.vouchers.join(','),\n usermail: (transaction.isFirst) ? 'new' : 'old',\n name: user.firstName,\n lastname: user.lastName,\n email: this.getEmailMd5(event)\n }),\n OrderItems: mapLineItems(transaction.lineItems)\n })\n this.pageTracked = true\n }\n}\n\nexport default AdSpire", "dangerousExampleEn": "1. var md5 = require('md5');\n2. \n3. console.log(md5('password'));\nLine 3: This is weak for the brute-force attack because it uses md5, a weak hash function.", "safeExampleEn": "1. var bcrypt = require('bcrypt');\n2. \n3. bcrypt.hash(\"password\", 13, function(err, hash) {\n4. console.log(hash);\n5. });\nLine 3: This is safe from the brute-force attack because bcrypt is used to create hash data.", "contexts": [{"lineNo": 242, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "242"}}, {"lineNo": 244, "eventType": "sink", "messageKey": "jschk.FORBIDDEN.WEAK_ALGORITHM.JS.defect", "params": {"arg0": "md5"}}]}} {"id": "342af2889784c88fddefd6f1531d62bf4d7816548333acb7d28435fbe139ff99", "license": {"spdx": ["MIT"], "repo": "lafin/node-cloudfoundry-apps-manager", "path": "lib/index.js", "repo_head_hexsha": "0294311e4ca7156cfe37492facaa7d4b6a6e769d", "stack_hexsha": "b95414311888d29a48f76c673eb3db78ffad8944", "match": "repo_path"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Use of weak cryptographic algorithm", "issueDescriptionEn": "A hash function is a one-way function that receives data of different lengths and maps it to random data of a fixed length. It is commonly used to store user passwords because it always produces the same output for a given input.\nBecause hash can be calculated very quickly, the hash functions, such as MD5 and SHA, may give the illusion of high performance. However they are vulnerable to random brute-force attacks. If you use the hash functions on simple data, they can be saved in the rainbow table, making it insecure. In addition, RC2, RC3, RC4, RC5, RC6, MD4, and DES are also known to be vulnerable.\nThere are many functions used to overcome the disadvantages of MD5 and SHA.\nIn Node.js, bcrypt is one of the functions that is commonly used with outstanding performance and easily replace them. The latest hash algorithms, such as Argon2, PBKDF2, and Scrypt, are also good alternatives. Make sure to add a salt to the hash in SHA-2 i.e. SHA-224, SHA-256, SHA-384, SHA-512.", "issueLineNumber": 96, "entireCode": "/* jshint -W079,-W059 */\n\nvar request = require('request'),\n async = require('async'),\n JSZip = require('jszip'),\n crypto = require('crypto'),\n FormData = require('form-data'),\n yaml = require('js-yaml');\n\nvar defaultHeaders = function (type, token) {\n return {\n 'Accept': 'application/json',\n 'Authorization': type + ' ' + token,\n 'Content-Type': 'application/json'\n };\n};\n\nvar type = null,\n token = null,\n appGuid = null,\n domainGuid = null,\n routeGuid = null,\n resourcesRemoteFile = null,\n dataRemoteFile = null,\n resourceMatched = null,\n manifest = null;\n\nvar getUrl = function (params, handler) {\n return 'http' + (params.endpoints.ssl ? 's' : '') + '://' + params.endpoints[handler];\n};\n\nvar login = function (params, callback) {\n if (!params) {\n return callback('Not enough parameters');\n }\n request({\n method: 'POST',\n url: getUrl(params, 'login') + '/oauth/token',\n headers: {\n 'Accept': 'application/json',\n 'Authorization': 'Basic Y2Y6',\n 'Content-Type': 'application/x-www-form-urlencoded'\n },\n form: {\n 'grant_type': 'password',\n 'username': params.username,\n 'password': \n }\n }, function (error, response, body) {\n if (error) {\n return callback(error);\n }\n try {\n body = JSON.parse(body);\n } catch (e) {\n body = null;\n }\n if (!body) {\n return callback('Authorization error');\n }\n return callback(null, {\n 'type': body.token_type,\n 'token': body.access_token\n });\n });\n};\n\nfunction getSession(params, callback) {\n return async.memoize(login)(params, function (error, data) {\n type = data.type;\n token = data.token;\n return callback(null, data);\n });\n}\n\nvar resources = function (params, callback) {\n if (!params) {\n return callback('Not enough parameters');\n }\n request({\n method: 'GET',\n url: params.appFile,\n encoding: null\n }, function (error, response, body) {\n if (error || response.statusCode !== 200) {\n return callback('Can not get file');\n }\n dataRemoteFile = body;\n var zip = new JSZip(body),\n resources = [];\n for (var i in zip.files) {\n if (zip.files.hasOwnProperty(i) && zip.files[i].dir === false) {\n var file = zip.files[i],\n name = file.name,\n buffer = zip.file(name).asText(),\n sha1 = crypto.createHash('sha1');\n if (name.substr(name.lastIndexOf('/') + 1) === 'manifest.yml') {\n manifest = yaml.safeLoad(buffer);\n }\n resources.push({\n 'fn': name,\n 'size': file._data.uncompressedSize,\n 'sha1': sha1.update(buffer).digest('hex')\n });\n }\n }\n callback(null, resources);\n });\n};\n\nfunction getResources(params, callback) {\n return async.memoize(resources)(params, function (error, data) {\n resourcesRemoteFile = data;\n return callback(null, true);\n });\n}\n\nfunction checkApp(params, callback) {\n if (!params) {\n return callback('Not enough parameters');\n }\n var functionName = arguments.callee.name;\n request({\n method: 'GET',\n url: getUrl(params, 'api') + '/v2/spaces/' + params.spaceGuid + '/apps',\n headers: defaultHeaders(type, token),\n qs: {\n 'q': 'name:' + params.appName,\n 'inline-relations-depth': 1\n }\n }, function (error, response, body) {\n if (error) {\n return callback(error);\n }\n if (response.statusCode === 401) {\n return callback('Authorization error');\n }\n try {\n body = JSON.parse(body);\n } catch (e) {\n body = null;\n }\n if (response.statusCode >= 400) {\n return callback(functionName + ': ' + (body && body.hasOwnProperty('description') ? body.description : 'Unknown error'));\n }\n if (body && body.hasOwnProperty('total_results')) {\n if (body.total_results) {\n for (var i = 0; i < body.resources.length; i++) {\n appGuid = body.resources[i].metadata.guid;\n return callback(null, appGuid);\n }\n } else {\n return callback(null, false);\n }\n }\n return callback('Check app fail');\n });\n}\n\nfunction createApp(params, callback) {\n if (!params) {\n return callback('Not enough parameters');\n }\n var functionName = arguments.callee.name;\n var bodyParams = {\n 'name': params.appName,\n 'space_guid': params.spaceGuid\n };\n if (manifest && manifest.applications) {\n var applications = manifest.applications;\n for (var a = 0; a < applications.length; a++) {\n var application = applications[a];\n if (application.memory) {\n bodyParams.memory = parseInt(application.memory, 10);\n }\n if (application.instances) {\n bodyParams.instances = parseInt(application.instances, 10);\n }\n if (application.disk_quota) {\n bodyParams.disk_quota = parseInt(application.disk_quota, 10);\n }\n if (application.buildpack) {\n bodyParams.buildpack = application.buildpack;\n }\n }\n }\n for (var i in params) {\n if (~['instances', 'memory', 'disk_quota', 'buildpack'].indexOf(i)) {\n bodyParams[i] = params[i];\n }\n }\n request({\n method: appGuid ? 'PUT' : 'POST',\n url: getUrl(params, 'api') + '/v2/apps' + (appGuid ? '/' + appGuid : ''),\n headers: defaultHeaders(type, token),\n qs: {\n 'async': 'true'\n },\n body: JSON.stringify(bodyParams)\n }, function (error, response, body) {\n if (error) {\n return callback(error);\n }\n if (response.statusCode === 401) {\n return callback('Authorization error');\n }\n try {\n body = JSON.parse(body);\n } catch (e) {\n body = null;\n }\n if (response.statusCode >= 400) {\n return callback(functionName + ': ' + (body && body.hasOwnProperty('description') ? body.description : 'Unknown error'));\n }\n if (body && body.metadata && body.metadata.guid && response.statusCode === 201) {\n appGuid = body.metadata.guid;\n return callback(null, appGuid);\n }\n return callback('Create app fail');\n });\n}\n\nfunction checkPrivateDomain(params, callback) {\n if (!params) {\n return callback('Not enough parameters');\n }\n var functionName = arguments.callee.name;\n request({\n method: 'GET',\n url: getUrl(params, 'api') + '/v2/organizations/' + params.orgGuid + '/private_domains',\n headers: defaultHeaders(type, token)\n }, function (error, response, body) {\n if (error) {\n return callback(error);\n }\n if (response.statusCode === 401) {\n return callback('Authorization error');\n }\n try {\n body = JSON.parse(body);\n } catch (e) {\n body = null;\n }\n if (response.statusCode >= 400) {\n return callback(functionName + ': ' + (body && body.hasOwnProperty('description') ? body.description : 'Unknown error'));\n }\n if (body && !body.total_results && response.statusCode === 200) {\n return callback(null, true);\n }\n return callback('Private domain fail');\n });\n}\n\nfunction checkSharedDomain(params, callback) {\n if (!params) {\n return callback('Not enough parameters');\n }\n var functionName = arguments.callee.name;\n request({\n method: 'GET',\n url: getUrl(params, 'api') + '/v2/shared_domains',\n headers: defaultHeaders(type, token)\n }, function (error, response, body) {\n if (error) {\n return callback(error);\n }\n if (response.statusCode === 401) {\n return callback('Authorization error');\n }\n try {\n body = JSON.parse(body);\n } catch (e) {\n body = null;\n }\n if (response.statusCode >= 400) {\n return callback(functionName + ': ' + (body && body.hasOwnProperty('description') ? body.description : 'Unknown error'));\n }\n if (body && body.total_results && response.statusCode === 200) {\n domainGuid = body.resources[0].metadata.guid;\n return callback(null, domainGuid);\n }\n return callback('Shared domain fail');\n });\n}\n\nfunction checkRoute(params, callback) {\n if (!params) {\n return callback('Not enough parameters');\n }\n var functionName = arguments.callee.name;\n request({\n method: 'GET',\n url: getUrl(params, 'api') + '/v2/routes',\n headers: defaultHeaders(type, token),\n qs: {\n 'q': 'host:' + params.appName + ';domain_guid:' + domainGuid,\n 'inline-relations-depth': 1\n }\n }, function (error, response, body) {\n if (error) {\n return callback(error);\n }\n if (response.statusCode === 401) {\n return callback('Authorization error');\n }\n try {\n body = JSON.parse(body);\n } catch (e) {\n body = null;\n }\n if (response.statusCode >= 400) {\n return callback(functionName + ': ' + (body && body.hasOwnProperty('description') ? body.description : 'Unknown error'));\n }\n if (body && response.statusCode === 200) {\n if (body.total_results) {\n for (var i = 0; i < body.resources.length; i++) {\n routeGuid = body.resources[i].metadata.guid;\n return callback(null, routeGuid);\n }\n } else {\n return callback(null, false);\n }\n }\n return callback('Check route fail');\n });\n}\n\nfunction createRoute(params, callback) {\n if (!params) {\n return callback('Not enough parameters');\n }\n var functionName = arguments.callee.name;\n request({\n method: 'POST',\n url: getUrl(params, 'api') + '/v2/routes',\n headers: defaultHeaders(type, token),\n qs: {\n 'async': 'true',\n 'inline-relations-depth': 1\n },\n body: JSON.stringify({\n 'host': params.appName,\n 'domain_guid': domainGuid,\n 'space_guid': params.spaceGuid\n })\n }, function (error, response, body) {\n if (error) {\n return callback(error);\n }\n if (response.statusCode === 401) {\n return callback('Authorization error');\n }\n try {\n body = JSON.parse(body);\n } catch (e) {\n body = null;\n }\n if (response.statusCode >= 400) {\n return callback(functionName + ': ' + (body && body.hasOwnProperty('description') ? body.description : 'Unknown error'));\n }\n if (body && body.metadata && body.metadata.guid && response.statusCode === 201) {\n routeGuid = body.metadata.guid;\n return callback(null, routeGuid);\n }\n return callback('Create route fail');\n });\n}\n\nfunction acceptRoute(params, callback) {\n if (!params) {\n return callback('Not enough parameters');\n }\n var functionName = arguments.callee.name;\n request({\n method: 'PUT',\n url: getUrl(params, 'api') + '/v2/apps/' + appGuid + '/routes/' + routeGuid,\n headers: defaultHeaders(type, token),\n body: JSON.stringify({\n 'host': params.appName,\n 'domain_guid': domainGuid,\n 'space_guid': params.spaceGuid\n })\n }, function (error, response, body) {\n if (error) {\n return callback(error);\n }\n if (response.statusCode === 401) {\n return callback('Authorization error');\n }\n try {\n body = JSON.parse(body);\n } catch (e) {\n body = null;\n }\n if (response.statusCode >= 400) {\n return callback(functionName + ': ' + (body && body.hasOwnProperty('description') ? body.description : 'Unknown error'));\n }\n if (body && body.metadata && body.metadata.guid && response.statusCode === 201) {\n if (body.metadata.guid === appGuid) {\n return callback(null, true);\n }\n }\n return callback('Accept route fail');\n });\n}\n\nfunction checkResources(params, callback) {\n if (!params) {\n return callback('Not enough parameters');\n }\n var functionName = arguments.callee.name;\n request({\n method: 'PUT',\n url: getUrl(params, 'api') + '/v2/resource_match',\n headers: defaultHeaders(type, token),\n body: JSON.stringify(resourcesRemoteFile)\n }, function (error, response, body) {\n if (error) {\n return callback(error);\n }\n if (response.statusCode === 401) {\n return callback('Authorization error');\n }\n try {\n body = JSON.parse(body);\n } catch (e) {\n body = null;\n }\n if (response.statusCode >= 400) {\n return callback(functionName + ': ' + (body && body.hasOwnProperty('description') ? body.description : 'Unknown error'));\n }\n if (response.statusCode === 200) {\n resourceMatched = body;\n return callback(null, true);\n }\n return callback('Chech resource fail');\n });\n}\n\nfunction uploadApp(params, callback) {\n if (!params) {\n return callback('Not enough parameters');\n }\n var functionName = arguments.callee.name;\n var form = new FormData(),\n CRLF = '\\r\\n',\n length = dataRemoteFile.length,\n filename = params.appFile.substr(params.appFile.lastIndexOf('/') + 1),\n options = {\n header: CRLF + [\n '--' + form.getBoundary(),\n 'Content-Disposition: form-data; name=\"application\"; filename=\"' + filename + '\"',\n 'Content-Type: application/zip',\n 'Content-Length: ' + length,\n 'Content-Transfer-Encoding: binary'\n ].join(CRLF) + CRLF + CRLF,\n knownLength: length\n };\n\n form.append('async', 'true');\n form.append('resources', JSON.stringify(resourceMatched));\n form.append('application', dataRemoteFile, options);\n\n form.getLength(function () {\n var req = request({\n method: 'PUT',\n url: getUrl(params, 'api') + '/v2/apps/' + appGuid + '/bits',\n headers: {\n 'Accept': 'application/json',\n 'Authorization': type + ' ' + token\n },\n qs: {\n 'async': 'true'\n },\n formData: {\n 'async': 'true',\n 'resources': JSON.stringify(resourceMatched),\n 'application': dataRemoteFile\n }\n }, function (error, response, body) {\n if (error) {\n return callback(error);\n }\n if (response.statusCode === 401) {\n return callback('Authorization error');\n }\n try {\n body = JSON.parse(body);\n } catch (e) {\n body = null;\n }\n if (response.statusCode >= 400) {\n return callback(functionName + ': ' + (body && body.hasOwnProperty('description') ? body.description : 'Unknown error'));\n }\n if (body && body.metadata && body.metadata.guid && response.statusCode === 201) {\n return callback(null, body.metadata.guid);\n }\n return callback('Upload fail');\n });\n req._form = form;\n });\n}\n\nfunction checkJob(params, callback) {\n if (!params) {\n return callback('Not enough parameters');\n }\n var functionName = arguments.callee.name;\n request({\n method: 'GET',\n url: getUrl(params, 'api') + '/v2/jobs/' + params.uploadJobGuid,\n headers: defaultHeaders(type, token)\n }, function (error, response, body) {\n if (error) {\n return callback(error);\n }\n if (response.statusCode === 401) {\n return callback('Authorization error');\n }\n try {\n body = JSON.parse(body);\n } catch (e) {\n body = null;\n }\n if (response.statusCode >= 400) {\n return callback(functionName + ': ' + (body && body.hasOwnProperty('description') ? body.description : 'Unknown error'));\n }\n if (body && body.metadata && body.metadata.hasOwnProperty('guid') && response.statusCode === 200) {\n return callback(null, body.metadata.guid === '0');\n }\n return callback('Check job fail');\n });\n}\n\nfunction changeStatusApp(params, callback) {\n if (!params) {\n return callback('Not enough parameters');\n }\n var functionName = arguments.callee.name;\n request({\n method: 'PUT',\n url: getUrl(params, 'api') + '/v2/apps/' + appGuid,\n headers: defaultHeaders(type, token),\n qs: {\n 'async': 'true',\n 'inline-relations-depth': 1\n },\n body: JSON.stringify({\n 'state': params.status ? params.status : 'STARTED'\n })\n }, function (error, response, body) {\n if (error) {\n return callback(error);\n }\n if (response.statusCode === 401) {\n return callback('Authorization error');\n }\n try {\n body = JSON.parse(body);\n } catch (e) {\n body = null;\n }\n if (response.statusCode >= 400) {\n return callback(functionName + ': ' + (body && body.hasOwnProperty('description') ? body.description : 'Unknown error'));\n }\n if (body && body.metadata && body.metadata.hasOwnProperty('guid') && response.statusCode === 201) {\n if (body.metadata.guid === appGuid) {\n return callback(null, true);\n }\n }\n return callback('Change status app fail');\n });\n}\n\nfunction checkInstance(params, callback) {\n if (!params) {\n return callback('Not enough parameters');\n }\n var functionName = arguments.callee.name;\n request({\n method: 'GET',\n url: getUrl(params, 'api') + '/v2/apps/' + appGuid + '/instances',\n headers: defaultHeaders(type, token)\n }, function (error, response, body) {\n if (error) {\n return callback(error);\n }\n if (response.statusCode === 401) {\n return callback('Authorization error');\n }\n try {\n body = JSON.parse(body);\n } catch (e) {\n body = null;\n }\n if (response.statusCode >= 400) {\n return callback(functionName + ': ' + (body && body.hasOwnProperty('description') ? body.description : 'Unknown error'));\n }\n if (response.statusCode === 200) {\n return callback(null, true);\n }\n return callback('Chech instance fail');\n });\n}\n\nfunction deleteApp(params, callback) {\n if (!params) {\n return callback('Not enough parameters');\n }\n var functionName = arguments.callee.name;\n request({\n method: 'DELETE',\n url: getUrl(params, 'api') + '/v2/apps/' + appGuid,\n headers: defaultHeaders(type, token),\n qs: {\n 'async': 'true',\n 'recursive': 'true'\n }\n }, function (error, response, body) {\n if (error) {\n return callback(error);\n }\n if (response.statusCode === 401) {\n return callback('Authorization error');\n }\n if (response.statusCode >= 400) {\n return callback(functionName + ': ' + (body && body.hasOwnProperty('description') ? body.description : 'Unknown error'));\n }\n return callback(null, response.statusCode === 204);\n });\n}\n\nfunction checkStat(params, callback) {\n if (!params) {\n return callback('Not enough parameters');\n }\n var functionName = arguments.callee.name;\n request({\n method: 'GET',\n url: getUrl(params, 'api') + '/v2/apps/' + appGuid + '/stats',\n headers: defaultHeaders(type, token)\n }, function (error, response, body) {\n if (error) {\n return callback(error);\n }\n if (response.statusCode === 401) {\n return callback('Authorization error');\n }\n try {\n body = JSON.parse(body);\n } catch (e) {\n body = null;\n }\n if (response.statusCode >= 400) {\n return callback(functionName + ': ' + (body && body.hasOwnProperty('description') ? body.description : 'Unknown error'));\n }\n if (response.statusCode === 200) {\n var successRun = 0,\n url = null;\n if (body) {\n for (var i in body) {\n if (body.hasOwnProperty(i) && body[i].state === 'RUNNING') {\n url = body[i].stats.uris.length ? body[i].stats.uris[0] : null;\n ++successRun;\n }\n }\n }\n return callback(null, Object.keys(body).length === successRun ? url : false);\n }\n return callback('Chech instance fail');\n });\n}\n\nfunction reset(callback) {\n appGuid = null;\n callback();\n}\n\nexports = module.exports = {\n install: function (params, callback) {\n async.series([\n function (callback) {\n reset(callback);\n },\n function (callback) {\n getResources(params, callback);\n },\n function (callback) {\n getSession(params, callback);\n },\n function (callback) {\n checkApp(params, function (error, result) {\n if (result) {\n params.status = 'STOPPED';\n return changeStatusApp(params, callback);\n }\n return callback(null, true);\n });\n },\n function (callback) {\n createApp(params, callback);\n },\n function (callback) {\n checkPrivateDomain(params, callback);\n },\n function (callback) {\n checkSharedDomain(params, callback);\n },\n function (callback) {\n checkRoute(params, function (error, result) {\n if (result) {\n return callback(error, result);\n }\n return createRoute(params, callback);\n });\n },\n function (callback) {\n acceptRoute(params, callback);\n },\n function (callback) {\n checkResources(params, callback);\n },\n function (callback) {\n uploadApp(params, function (error, data) {\n if (error) {\n return callback(arguments);\n }\n var maxLoopCount = 10;\n params.uploadJobGuid = data;\n var sameCallback = function (error, data) {\n if (data) {\n return callback(null, true);\n } else {\n --maxLoopCount;\n if (maxLoopCount) {\n setTimeout(function () {\n checkJob(params, sameCallback);\n }, 2000);\n } else {\n return callback('Infinity loop check job');\n }\n }\n };\n checkJob(params, sameCallback);\n });\n },\n function (callback) {\n params.status = 'STARTED';\n changeStatusApp(params, callback);\n },\n function (callback) {\n var maxLoopCount = 10;\n var sameCallback = function () {\n return checkStat(params, function (error, data) {\n if (data) {\n return callback(null, data);\n } else {\n --maxLoopCount;\n if (maxLoopCount) {\n setTimeout(function () {\n checkInstance(params, sameCallback);\n }, 2000);\n } else {\n return callback('Infinity loop check status');\n }\n }\n });\n };\n return checkInstance(params, sameCallback);\n }\n ], function (error, results) {\n callback(error ? new Error(error) : null, results[results.length - 1]);\n });\n },\n uninstall: function (params, callback) {\n async.series([\n function (callback) {\n reset(callback);\n },\n function (callback) {\n getSession(params, callback);\n },\n function (callback) {\n checkApp(params, function (error, result) {\n if (!error && result) {\n return deleteApp(params, callback);\n }\n return callback(arguments);\n });\n }\n ], function (error, results) {\n callback(error ? new Error(error) : null, results[results.length - 1]);\n });\n }\n};", "dangerousExampleEn": "1. var md5 = require('md5');\n2. \n3. console.log(md5('password'));\nLine 3: This is weak for the brute-force attack because it uses md5, a weak hash function.", "safeExampleEn": "1. var bcrypt = require('bcrypt');\n2. \n3. bcrypt.hash(\"password\", 13, function(err, hash) {\n4. console.log(hash);\n5. });\nLine 3: This is safe from the brute-force attack because bcrypt is used to create hash data.", "contexts": [{"lineNo": 92, "eventType": "source", "messageKey": "synz.COMMON.branch.true.assumed", "params": {"arg0": "92"}}, {"lineNo": 96, "eventType": "sink", "messageKey": "jschk.FORBIDDEN.WEAK_ALGORITHM.JS.defect", "params": {"arg0": "sha1"}}]}} {"id": "b27f78e3eb2f0dbc0dfd02960d5cf503483bf864cd676c9e7208648a90fb5a33", "license": {"spdx": ["Apache-2.0"], "repo": "fkling/flow-typestrip", "path": "__tests__/type-object-method-syntax-test.js", "repo_head_hexsha": "484d1749c9bab2b9e58732d42465ea955dde1f0f", "stack_hexsha": "c882d62ffb7164d5b015041ed4b1c5224af63276", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Remote code execution", "issueDescriptionEn": "The Remote code execution checker finds code that uses eval() function.\nWhen the eval function is called, the parser runs dynamically, thus causing a slowdown.\nThe dynamic execution of code also can be exploited to run a malicious code.As the eval() function works at the global level of scope, its execution may affect external variables.\nDo not use the eval() function. If you need to, use a closure to restrict external variables and then call the eval() function.", "issueLineNumber": 41, "entireCode": "/**\n * Copyright 2013 Facebook, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\njest.autoMockOff();\n\ndescribe('static type object-method syntax', function() {\n var flowStrip;\n var esnext;\n var transform;\n\n beforeEach(function() {\n flowStrip = require('../');\n esnext = require('esnext');\n transform = function(sourceArray) {\n return esnext.compile(flowStrip.compile(sourceArray.join('\\n')).code).code;\n };\n });\n\n describe('param type annotations', function() {\n it('strips single param annotation', function() {\n var code = transform([\n 'var foo = {',\n ' bar(param1: bool) {',\n ' return param1;',\n ' }',\n '};',\n ]);\n eval(code);\n expect(foo.bar(42)).toBe(42);\n });\n\n it('strips multiple param annotations', function() {\n var code = transform([\n 'var foo = {',\n ' bar(param1: bool, param2: number) {',\n ' return [param1, param2];',\n ' }',\n '};'\n ]);\n eval(code);\n expect(foo.bar(true, 42)).toEqual([true, 42]);\n });\n\n it('strips higher-order param annotations', function() {\n var code = transform([\n 'var foo = {',\n ' bar(param1: (_:bool) => number) {',\n ' return param1;',\n ' }',\n '};'\n ]);\n eval(code);\n\n var callback = function(param) {\n return param ? 42 : 0;\n };\n expect(foo.bar(callback)).toBe(callback);\n });\n\n it('strips annotated params next to non-annotated params', function() {\n var code = transform([\n 'var foo = {',\n ' bar(param1, param2: number) {',\n ' return [param1, param2];',\n ' }',\n '}',\n ]);\n eval(code);\n expect(foo.bar('p1', 42)).toEqual(['p1', 42]);\n });\n\n it('strips annotated params before a rest parameter', function() {\n var code = transform([\n 'var foo = {',\n ' bar(param1: number, ...args) {',\n ' return [param1, args];',\n ' }',\n '}',\n ]);\n eval(code);\n expect(foo.bar(42, 43, 44)).toEqual([42, [43, 44]]);\n });\n\n it('strips annotated rest parameter', function() {\n var code = transform([\n 'var foo = {',\n ' bar(param1: number, ...args: Array): Array {',\n ' return [param1, args];',\n ' }',\n '}',\n ]);\n eval(code);\n expect(foo.bar(42, 43, 44)).toEqual([42, [43, 44]]);\n });\n });\n\n describe('return type annotations', function() {\n it('strips function return types', function() {\n var code = transform([\n 'var foo = {',\n ' bar(param1:number): () => number {',\n ' return function() { return param1; };',\n ' }',\n '}',\n ]);\n eval(code);\n expect(foo.bar(42)()).toBe(42);\n });\n });\n\n describe('parametric type annotation', function() {\n // TODO: Fix esprima parsing for these cases\n /*\n it('strips parametric type annotations', function() {\n // TODO: Doesnt parse\n var code = transform([\n 'var foo = {',\n ' bar(param1) {',\n ' return param1;',\n ' }',\n '}',\n ]);\n eval(code);\n expect(foo.bar(42)).toBe(42);\n });\n\n it('strips multi-parameter type annotations', function() {\n // TODO: Doesnt parse\n var code = transform([\n 'var foo = {',\n ' bar(param1) {',\n ' return param1;',\n ' }',\n '}',\n ]):\n eval(code);\n expect(foo.bar(42)).toBe(42);\n });\n */\n });\n});", "dangerousExampleEn": "1. /** example 1 */\n2. JSONData = '{\"color\" : new Date()}';\n3. document.writeln(eval('('+JSONData + ')').color);\n4. \n5. /** example 2*/\n6. var dateFn = \"Date(1971,3,8)\";\n7. var myDate;\n8. eval(\"myDate = new \" + dateFn + \";\");\n9. \n10. /** example 3*/\n11. var a = 1;\n12. eval(\"var a = 2\");\n13. alert(a) // 2\nLine 3: eval() function is used.", "safeExampleEn": "1. /** example 1 */\n2. JSONData = '{\"color\" : new Date()}';\n3. testObject = JSONData.parseJSON();\n4. document.writeln(testObject.color);\n5. \n6. /** example 2*/\n7. var dateFn = \"Date(1971,3,8)\";\n8. var myDate;\n9. myDate = new dateFn;\n10. \n11. /** example 3*/\n12. var a = 1;\n13. (function() {\n14. eval(\"var a = 2\");\n15. }());\n16. alert(a) // 1;\nLine 3: Use parseJSON instead of the eval() to parse JSON data.\nLine 8: Do not use the eval() function.\nLine 12: Call eval() function with function closure, which is not effected by external variables.", "contexts": [{"lineNo": 41, "eventType": "sink", "messageKey": "jschk.FORBIDDEN.EVAL_FUNCTION.JS.defect", "params": {}}]}} {"id": "b123f6fa837d8849486919cef6ec9b2561e220e029c43ba9523b5fcb986afb70", "license": {"spdx": ["BSD-3-Clause"], "repo": "isabella232/v8", "path": "test/mjsunit/lazy-inner-functions.js", "repo_head_hexsha": "30ef8e33f3a199a27ca8512bcee314c9522d03f6", "stack_hexsha": "3d8c448ce1976014728326d408327e8dc995f704", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Remote code execution", "issueDescriptionEn": "The Remote code execution checker finds code that uses eval() function.\nWhen the eval function is called, the parser runs dynamically, thus causing a slowdown.\nThe dynamic execution of code also can be exploited to run a malicious code.As the eval() function works at the global level of scope, its execution may affect external variables.\nDo not use the eval() function. If you need to, use a closure to restrict external variables and then call the eval() function.", "issueLineNumber": 9, "entireCode": "// Copyright 2016 the V8 project authors. All rights reserved.\n// Use of this source code is governed by a BSD-style license that can be\n// found in the LICENSE file.\n\n(function TestLazyInnerFunctionCallsEval() {\n var i = (function eager_outer() {\n var a = 41; // Should be context-allocated\n function lazy_inner() {\n return eval(\"a\");\n }\n return lazy_inner;\n })();\n assertEquals(41, i());\n})();", "dangerousExampleEn": "1. /** example 1 */\n2. JSONData = '{\"color\" : new Date()}';\n3. document.writeln(eval('('+JSONData + ')').color);\n4. \n5. /** example 2*/\n6. var dateFn = \"Date(1971,3,8)\";\n7. var myDate;\n8. eval(\"myDate = new \" + dateFn + \";\");\n9. \n10. /** example 3*/\n11. var a = 1;\n12. eval(\"var a = 2\");\n13. alert(a) // 2\nLine 3: eval() function is used.", "safeExampleEn": "1. /** example 1 */\n2. JSONData = '{\"color\" : new Date()}';\n3. testObject = JSONData.parseJSON();\n4. document.writeln(testObject.color);\n5. \n6. /** example 2*/\n7. var dateFn = \"Date(1971,3,8)\";\n8. var myDate;\n9. myDate = new dateFn;\n10. \n11. /** example 3*/\n12. var a = 1;\n13. (function() {\n14. eval(\"var a = 2\");\n15. }());\n16. alert(a) // 1;\nLine 3: Use parseJSON instead of the eval() to parse JSON data.\nLine 8: Do not use the eval() function.\nLine 12: Call eval() function with function closure, which is not effected by external variables.", "contexts": [{"lineNo": 9, "eventType": "sink", "messageKey": "jschk.FORBIDDEN.EVAL_FUNCTION.JS.defect", "params": {}}]}} {"id": "f7dab17eb8e42a764897c9151d46c55805d4da6c7df63c668e9ab1b011bc75c3", "license": {"spdx": ["MIT"], "repo": "onsetsu/active-collection-prototype", "path": "lib/babelsberg/standalone/examples/cassowary/layout.js", "repo_head_hexsha": "1bf691fcf25b381efb3d7774e76e6cdd16865cd6", "stack_hexsha": "acd0cad1fa4c6c28282cbaa3b7717437f84f707b", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Remote code execution", "issueDescriptionEn": "The Remote code execution checker finds code that uses eval() function.\nWhen the eval function is called, the parser runs dynamically, thus causing a slowdown.\nThe dynamic execution of code also can be exploited to run a malicious code.As the eval() function works at the global level of scope, its execution may affect external variables.\nDo not use the eval() function. If you need to, use a closure to restrict external variables and then call the eval() function.", "issueLineNumber": 49, "entireCode": "contentLoaded(window, function() {\n\tvar consoleLog = console.log;\n\tconsole.log = function (args) {\n\t\tconsoleLog.apply(console, arguments);\n\t\tvar c = document.getElementById('console');\n\t\tc.textContent = \"Console\\n\" + args + \"\\n\" + \n\t\t\t\tc.textContent.slice(\"Console\\n\".length, c.textContent.indexOf(\"\\n\", 500));\n\t};\n\n\t// setup canvas\n\tvar canvas = new fabric.Canvas('canvas');\n\tfabric.Object.prototype.transparentCorners = false;\n\t\n\tvar red = new fabric.Rect({\n\t\twidth: 200, height: 100, left: 0, top: 50, angle: 0,\n\t\tfill: 'rgba(255,0,0,0.5)'\n\t});\n\t\n\tvar green = new fabric.Rect({\n\t\twidth: 100, height: 100, left: 350, top: 250, angle: 0,\n\t\tfill: 'rgba(0,255,0,0.5)'\n\t});\n\t\n\tvar blue = new fabric.Rect({\n\t\twidth: 50, height: 100, left: 275, top: 350, angle: 0,\n\t\tfill: 'rgba(0,0,255,0.5)'\n\t});\n\t\n\tvar yellow = new fabric.Rect({\n\t\twidth: 50, height: 100, left: 75, top: 350, angle: 0,\n\t\tfill: 'rgba(255,255,0,0.5)'\n\t});\n\t\n\twindow.rects = {\n\t\tred: red,\n\t\tgreen: green,\n\t\tblue: blue,\n\t\tyellow: yellow\n\t};\n\n\t//setup default solver\n\tbbb.defaultSolver = new ClSimplexSolver();\n\t\n\t// code editor\n\tvar codeEditor = document.getElementById('code');\n\tvar solverSelect = document.getElementById('solver');\n\t\n\tvar editorCallback = function() {\n\t\tbbb.defaultSolver = new (eval(solverSelect.value))();\n\t\t\n\t\tsetTimeout(function () {\n\t\t\t// remove old constraints\n\t\t\tObject.keys(window.rects).each(function(name) {\n\t\t\t\tbbb.unconstrainAll(window.rects[name]);\n\t\t\t});\n\n\t\t\tcodeEditor.style.border = \"3px solid green\";\n\t\t\ttry {\n\t\t\t\tBabelsberg.execute(this.value, window.rects);\n\t\t\t} catch (e) {\n\t\t\t\tcodeEditor.style.border = \"3px solid red\";\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t\t\n\t\t\t// rerender for immediate changes\n\t\t\tcanvas.renderAll();\n\t\t}.bind(this), 100);\n\t};\n\t\n\tcodeEditor.onkeyup = editorCallback;\n\n\tcodeEditor.value =\n\t\"always: {\\n\" +\n\t\"\tthis.red.top == this.green.top;\\n\" +\n\t\"}\\n\" +\n\t\"always: {\\n\" +\n\t\"\tthis.red.left + this.green.left == 500;\\n\" +\n\t\"}\\n\" +\n\t\"always: {\\n\" +\n\t\"\tthis.red.top == this.yellow.top;\\n\" +\n\t\"}\\n\" +\n\t\"always: {\\n\" +\n\t\"\tthis.red.left == this.yellow.left;\\n\" +\n\t\"}\\n\" +\n\t\"always: {\\n\" +\n\t\"\tthis.yellow.angle == this.yellow.top;\\n\" +\n\t\"}\\n\" +\n\t\"always: {\\n\" +\n\t\"\tthis.blue.angle >= 90;\\n\" +\n\t\"}\\n\" +\n\t\"always: {\\n\" +\n\t\"\tthis.blue.angle <= 270;\\n\" +\n\t\"}\\n\";\n\teditorCallback.call(codeEditor);\n\n\tcanvas.add(red, green, blue, yellow);\n\n\tsolverSelect.onchange = (function () {\n\t\teditorCallback.call(codeEditor);\n\t});\n\t\n\t// update controls of rects moved by constraints\n\tvar setControls = function() {\n\t\t[\"red\", \"green\", \"blue\", \"yellow\"].each(function(name) {\n\t\t\twindow.rects[name].setCoords();\n\t\t});\n\t\tfabric.util.requestAnimFrame(setControls);\n\t};\n\tfabric.util.requestAnimFrame(setControls);\n});", "dangerousExampleEn": "1. /** example 1 */\n2. JSONData = '{\"color\" : new Date()}';\n3. document.writeln(eval('('+JSONData + ')').color);\n4. \n5. /** example 2*/\n6. var dateFn = \"Date(1971,3,8)\";\n7. var myDate;\n8. eval(\"myDate = new \" + dateFn + \";\");\n9. \n10. /** example 3*/\n11. var a = 1;\n12. eval(\"var a = 2\");\n13. alert(a) // 2\nLine 3: eval() function is used.", "safeExampleEn": "1. /** example 1 */\n2. JSONData = '{\"color\" : new Date()}';\n3. testObject = JSONData.parseJSON();\n4. document.writeln(testObject.color);\n5. \n6. /** example 2*/\n7. var dateFn = \"Date(1971,3,8)\";\n8. var myDate;\n9. myDate = new dateFn;\n10. \n11. /** example 3*/\n12. var a = 1;\n13. (function() {\n14. eval(\"var a = 2\");\n15. }());\n16. alert(a) // 1;\nLine 3: Use parseJSON instead of the eval() to parse JSON data.\nLine 8: Do not use the eval() function.\nLine 12: Call eval() function with function closure, which is not effected by external variables.", "contexts": [{"lineNo": 49, "eventType": "sink", "messageKey": "jschk.FORBIDDEN.EVAL_FUNCTION.JS.defect", "params": {}}]}} {"id": "76c90fc053e640630273108fafd9d67c423843c61b6013673c919f1b8e656ff3", "license": {"spdx": ["MIT"], "repo": "rekysenjaya/wordcloud", "path": "assets/js/index.js", "repo_head_hexsha": "851a27b5ca4720164eec41f5e0946846c6e903df", "stack_hexsha": "c6b5c3cc0042c0241d3c8db0a7aa0255f74dc67a", "match": "exact_blob"}, "input": {"fileExtension": ".js", "programmingLanguage": "JavaScript", "issueNameEn": "Remote code execution", "issueDescriptionEn": "The Remote code execution checker finds code that uses eval() function.\nWhen the eval function is called, the parser runs dynamically, thus causing a slowdown.\nThe dynamic execution of code also can be exploited to run a malicious code.As the eval() function works at the global level of scope, its execution may affect external variables.\nDo not use the eval() function. If you need to, use a closure to restrict external variables and then call the eval() function.", "issueLineNumber": 184, "entireCode": "'use strict';\n\n\nvar maskCanvas;\n\njQuery(function ($) {\n var $form = $('#form');\n var $canvas = $('#canvas');\n var $htmlCanvas = $('#html-canvas');\n var $canvasContainer = $('#canvas-container');\n var $loading = $('#loading');\n\n var $list = $('#input-list');\n var $options = $('#config-option');\n var $width = $('#config-width');\n var $height = $('#config-height');\n var $mask = $('#config-mask');\n var $dppx = $('#config-dppx');\n var $css = $('#config-css');\n var $webfontLink = $('#link-webfont');\n \n console.log($form)\n\n if (!WordCloud.isSupported) {\n $('#not-supported').prop('hidden', false);\n $form.find('textarea, input, select, button').prop('disabled', true);\n return;\n }\n\n var $box = $('