Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Write JS Rules #504

Closed
31 of 32 tasks
cfabianski opened this issue Feb 6, 2023 · 1 comment
Closed
31 of 32 tasks

Write JS Rules #504

cfabianski opened this issue Feb 6, 2023 · 1 comment
Assignees
Labels
enhancement New feature or request
Milestone

Comments

@cfabianski
Copy link
Collaborator

cfabianski commented Feb 6, 2023

Analytics and logging libraries currently unsupported

Analytics libraries we support for Ruby but that we won't support for JS yet:

Code Snippets Examples

Loggers

const users = []

function generateUsername(firstname, surname) {
    return `${firstname[0]}-${surname}`.toLowerCase();
}

arr.forEach(element => {
	const username = generateUsername(user.firstname, user.surname);

	users.push({
		email: user.email,
		first_name: user.firstname,
		username
	})
});

console.log("user successfully connected", user.email);
console.table(users)

// Winston specific
const ctx = {
	{ 
		user: {
			email: "",
		}
	}
};

// catch the sensitive information from the context
logger.child({ context: ctx }).info('Order "1234" was processed successfully'); 

const childLogger = logger.child({ context: ctx });
childLogger.info('Order "1234" was processed successfully'); 

logger.log({
  level: 'info',
  message: 'user successfully connected' + user.email
});

// constructor function
function Person () {
    this.name = 'John',
    this.age = 23,
}

// create objects
const person1 = new Person();
const person2 = new Person();

// access properties
console.log(person1.name);  // John
console.log(person2.name);  // John

Cookies

const session = require('cookie-session')
const express = require('express')
const app = express()

app.use(session({
	...
  cookie: {
    secure: true, // Ensures the browser only sends the cookie over HTTPS.
    httpOnly: true, // Ensures the cookie is sent only over HTTP(S), not client JavaScript, helping to protect against cross-site scripting attacks.
    domain: 'example.com', // indicates the domain of the cookie; use it to compare against the domain of the server in which the URL is being requested. If they match, then check the path attribute next.
    path: 'foo/bar', // indicates the path of the cookie; use it to compare against the request path. If this and domain match, then send the cookie in the request.
    expires: expiryDate // use to set expiration date for persistent cookies.
  }
}))


// ...

const cookieConfig = {
  httpOnly: true, // to disable accessing cookie via client side js
  //secure: true, // to force https (if you use it)
  maxAge: 1000000, // ttl in seconds (remove this option and cookie will die when browser is closed)
  signed: true // if you use the secret with cookieParser
};
app.get('/set', (req, res) => {
  res.cookie('test', user.email, cookieConfig);
});

Links

File Generation

fs.writeFile('<filename>', <content>, callback);
fs.appendFile('<filename>', <content>, callback);

//

const users = []

function generateUsername(firstname, surname) {
    return `${firstname[0]}-${surname}`.toLowerCase();
}

arr.forEach(element => {
	const username = generateUsername(user.firstname, user.surname);

	users.push({
		email: user.email,
		first_name: user.firstname,
		username
	})
});

const fs = require("fs");

fs.writeFile("data.csv", data, "utf-8", (err) => {
  if (err) console.log(err);
  else console.log("Data saved");
});

Session / Local Storage

localStorage.setItem("User email", user.email)

Sentry

Sentry.configureScope(scope => {
  scope.setExtra('email', user.email);
  scope.setTag('user_email', user.email);
  scope.setUser({ email: user.email });
  // scope.clear();
});

Sentry.addBreadcrumb({
  message: 'My Breadcrumb',
  // ...
});

Sentry.captureMessage('Hello, world!');
Sentry.captureException(new Error('Good bye'));
Sentry.captureEvent({
  message: 'Manual',
  stacktrace: [
    // ...
  ],
});

Exceptions

throw new CustomError(`Error with ${user.email}`)
throw `${user.email}`

reject('Error with user ' + user.email);

Promise.reject(new Error('fail' + user.email))

Weak Encryption

var crypto = require('crypto');

var key = 'secret key';
var encrypted = crypto.createHmac('sha1', key).update(user.password)
var hashmd5 = crypto.createHash('md5').update(user.password)

var encrypted = crypto.createHmac('sha1', key).update(password)
var hashmd5 = crypto.createHash('md5').update(password)

// Should use BCrypt or Scrypt for encrypting password

SSL Verification

const express = require('express')
const app = express()
const helmet = require('helmet')
app.use(helmet())

// import express from "express";
// import { express } from "express";
// const express = require('express')

// 
app.use(helmet.hsts()); // default configuration
app.use(helmet.hsts("<max-age>", "<includeSubdomains>")); // custom configuration

Links

JWT

var jwt = require('jsonwebtoken');
var token = jwt.sign({ user: { email: 'bar' }}, 'shhhhh');

var token = jwt.sign({ foo: 'bar' }, privateKey, { algorithm: 'RS256' });
jwt.sign({ foo: 'bar' }, privateKey, { algorithm: 'RS256' }, function(err, token) {
  console.log(token);
});

Links

HTTP Get/Post

Detect Insecure URL + Insecure params

import axios from 'axios';
//const axios = require('axios'); // legacy way
axios.get(`http://example.com/user?email=${user.email}`)
  .then(function (response) {
    // handle success
    console.log(response);
  });

axios.get('http://example.com/user', {
    params: {
      email: user.email
    }
  })
  .then(function (response) {
    console.log(response);
  });

const response = await axios.get('http://example.com/user?email=' + user.email);
// GET request for remote image in node.js
axios({
  method: 'get',
  url: 'http://example.com',
})
  .then(function (response) {
    response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
  });
import fetch from 'node-fetch';

const response = await fetch('https://github.com/');

Detect Insecure URL

axios.post('http://example.com/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
// Send a POST request
axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});
import fetch from 'node-fetch';

const user = { email:  "", gender: "" };

const response = await fetch('http://httpbin.org/post', {
	method: 'post',
	body: JSON.stringify(user),
	headers: {'Content-Type': 'application/json'}
import fetch from 'node-fetch';
const params = new URLSearchParams();
params.append('email', user.email);

const response = await fetch('https://httpbin.org/post', {method: 'POST', body: params});

Functions

function getUserAccount() {
  return axios.get('/user/12345');
}
@elsapet
Copy link
Contributor

elsapet commented Feb 17, 2023

Closing as all pertinent tasks have been completed.

Tasks listed that we are not handling now:

  • SSL Verification - this is not feasible to do
  • Snippet support (e.g. <script> tags in HTML files) for logging/analytics library detection
  • Less popular logging/analytics libraries, some of which we handle for Ruby

@elsapet elsapet closed this as completed Feb 17, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

4 participants