<commit_before>// Generated on 2014-12-24 using generator-angular 0.10.0
'use strict';

// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'

module.exports = function (grunt) {

  // Load grunt tasks automatically
  require('load-grunt-tasks')(grunt);

  // Time how long tasks take. Can help when optimizing build times
  require('time-grunt')(grunt);

  // Configurable paths for the application
  var appConfig = {
    app: require('./bower.json').appPath || 'app',
    dist: 'dist'
  };

  // Define the configuration for all the tasks
  grunt.initConfig({

    // Project settings
    yeoman: appConfig,

    // Watches files for changes and runs tasks based on the changed files
    watch: {
      bower: {
        files: ['bower.json'],
        tasks: ['wiredep']
      },
      js: {
        files: ['<%= yeoman.app %>/scripts/{,*/}*.js'],
        tasks: ['newer:jshint:all'],
        options: {
          livereload: '<%= connect.options.livereload %>'
        }
      },
      jsTest: {
        files: ['test/spec/{,*/}*.js'],
        tasks: ['newer:jshint:test', 'karma']
      },
      compass: {
        files: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'],
        tasks: ['compass:server', 'autoprefixer']
      },
      gruntfile: {
        files: ['Gruntfile.js']
      },
      livereload: {
        options: {
          livereload: '<%= connect.options.livereload %>'
        },
        files: [
          '<%= yeoman.app %>/{,*/}*.html',
          '.tmp/styles/{,*/}*.css',
          '<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
        ]
      }
    },

    // The actual grunt server settings
    connect: {
      options: {
        port: 9000,
        // Change this to '0.0.0.0' to access the server from outside.
        hostname: 'localhost',
        livereload: 35729
      },
      livereload: {
        options: {
          open: true,
          middleware: function (connect) {
            return [
              connect.static('.tmp'),
              connect().use(
                '/bower_components',
                connect.static('./bower_components')
              ),
              connect.static(appConfig.app)
            ];
          }
        }
      },
      test: {
        options: {
          port: 9001,
          middleware: function (connect) {
            return [
              connect.static('.tmp'),
              connect.static('test'),
              connect().use(
                '/bower_components',
                connect.static('./bower_components')
              ),
              connect.static(appConfig.app)
            ];
          }
        }
      },
      dist: {
        options: {
          open: true,
          base: '<%= yeoman.dist %>'
        }
      }
    },

    // Make sure code styles are up to par and there are no obvious mistakes
    jshint: {
      options: {
        jshintrc: '.jshintrc',
        reporter: require('jshint-stylish')
      },
      all: {
        src: [
          'Gruntfile.js',
          '<%= yeoman.app %>/scripts/{,*/}*.js'
        ]
      },
      test: {
        options: {
          jshintrc: 'test/.jshintrc'
        },
        src: ['test/spec/{,*/}*.js']
      }
    },

    // Empties folders to start fresh
    clean: {
      dist: {
        files: [{
          dot: true,
          src: [
            '.tmp',
            '<%= yeoman.dist %>/{,*/}*',
            '!<%= yeoman.dist %>/.git{,*/}*'
          ]
        }]
      },
      server: '.tmp'
    },

    // Add vendor prefixed styles
    autoprefixer: {
      options: {
        browsers: ['last 1 version']
      },
      dist: {
        files: [{
          expand: true,
          cwd: '.tmp/styles/',
          src: '{,*/}*.css',
          dest: '.tmp/styles/'
        }]
      }
    },

    // Automatically inject Bower components into the app
    wiredep: {
      app: {
        src: ['<%= yeoman.app %>/index.html'],
        ignorePath:  /\.\.\//
      },
      sass: {
        src: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'],
        ignorePath: /(\.\.\/){1,2}bower_components\//
      }
    },

    // Compiles Sass to CSS and generates necessary files if requested
    compass: {
      options: {
        sassDir: '<%= yeoman.app %>/styles',
        cssDir: '.tmp/styles',
        generatedImagesDir: '.tmp/images/generated',
        imagesDir: '<%= yeoman.app %>/images',
        javascriptsDir: '<%= yeoman.app %>/scripts',
        fontsDir: '<%= yeoman.app %>/styles/fonts',
        importPath: './bower_components',
        httpImagesPath: '/images',
        httpGeneratedImagesPath: '/images/generated',
        httpFontsPath: '/styles/fonts',
        relativeAssets: false,
        assetCacheBuster: false,
        raw: 'Sass::Script::Number.precision = 10\n'
      },
      dist: {
        options: {
          generatedImagesDir: '<%= yeoman.dist %>/images/generated'
        }
      },
      server: {
        options: {
          debugInfo: true
        }
      }
    },

    // Renames files for browser caching purposes
    filerev: {
      dist: {
        src: [
          '<%= yeoman.dist %>/scripts/{,*/}*.js',
          '<%= yeoman.dist %>/styles/{,*/}*.css',
          '<%= yeoman.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}',
          '<%= yeoman.dist %>/styles/fonts/*'
        ]
      }
    },

    // Reads HTML for usemin blocks to enable smart builds that automatically
    // concat, minify and revision files. Creates configurations in memory so
    // additional tasks can operate on them
    useminPrepare: {
      html: '<%= yeoman.app %>/index.html',
      options: {
        dest: '<%= yeoman.dist %>',
        flow: {
          html: {
            steps: {
              js: ['concat', 'uglifyjs'],
              css: ['cssmin']
            },
            post: {}
          }
        }
      }
    },

    // Performs rewrites based on filerev and the useminPrepare configuration
    usemin: {
      html: ['<%= yeoman.dist %>/{,*/}*.html'],
      css: ['<%= yeoman.dist %>/styles/{,*/}*.css'],
      options: {
        assetsDirs: ['<%= yeoman.dist %>','<%= yeoman.dist %>/images']
      }
    },

    // The following *-min tasks will produce minified files in the dist folder
    // By default, your `index.html`'s <!-- Usemin block --> will take care of
    // minification. These next options are pre-configured if you do not wish
    // to use the Usemin blocks.
    // cssmin: {
    //   dist: {
    //     files: {
    //       '<%= yeoman.dist %>/styles/main.css': [
    //         '.tmp/styles/{,*/}*.css'
    //       ]
    //     }
    //   }
    // },
    // uglify: {
    //   dist: {
    //     files: {
    //       '<%= yeoman.dist %>/scripts/scripts.js': [
    //         '<%= yeoman.dist %>/scripts/scripts.js'
    //       ]
    //     }
    //   }
    // },
    // concat: {
    //   dist: {}
    // },

    imagemin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= yeoman.app %>/images',
          src: '{,*/}*.{png,jpg,jpeg,gif}',
          dest: '<%= yeoman.dist %>/images'
        }]
      }
    },

    svgmin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= yeoman.app %>/images',
          src: '{,*/}*.svg',
          dest: '<%= yeoman.dist %>/images'
        }]
      }
    },

    htmlmin: {
      dist: {
        options: {
          collapseWhitespace: true,
          conservativeCollapse: true,
          collapseBooleanAttributes: true,
          removeCommentsFromCDATA: true,
          removeOptionalTags: true
        },
        files: [{
          expand: true,
          cwd: '<%= yeoman.dist %>',
          src: ['*.html', 'views/{,*/}*.html'],
          dest: '<%= yeoman.dist %>'
        }]
      }
    },

    // ng-annotate tries to make the code safe for minification automatically
    // by using the Angular long form for dependency injection.
    ngAnnotate: {
      dist: {
        files: [{
          expand: true,
          cwd: '.tmp/concat/scripts',
          src: ['*.js', '!oldieshim.js'],
          dest: '.tmp/concat/scripts'
        }]
      }
    },

    // Replace Google CDN references
    cdnify: {
      dist: {
        html: ['<%= yeoman.dist %>/*.html']
      }
    },

    // Copies remaining files to places other tasks can use
    copy: {
      dist: {
        files: [{
          expand: true,
          dot: true,
          cwd: '<%= yeoman.app %>',
          dest: '<%= yeoman.dist %>',
          src: [
            '*.{ico,png,txt}',
            '.htaccess',
            '*.html',
            'views/{,*/}*.html',
            'images/{,*/}*.{webp}',
            'fonts/{,*/}*.*'
          ]
        }, {
          expand: true,
          cwd: '.tmp/images',
          dest: '<%= yeoman.dist %>/images',
          src: ['generated/*']
        }, {
          expand: true,
          cwd: '.',
          src: 'bower_components/bootstrap-sass-official/assets/fonts/bootstrap/*',
          dest: '<%= yeoman.dist %>'
        }]
      },
      styles: {
        expand: true,
        cwd: '<%= yeoman.app %>/styles',
        dest: '.tmp/styles/',
        src: '{,*/}*.css'
      }
    },

    // Run some tasks in parallel to speed up the build process
    concurrent: {
      server: [
        'compass:server'
      ],
      test: [
        'compass'
      ],
      dist: [
        'compass:dist',
        'imagemin',
        'svgmin'
      ]
    },

    // Test settings
    karma: {
      unit: {
        configFile: 'test/karma.conf.js',
        singleRun: true
      }
    }
  });

  grunt.registerTask('serve', 'Compile then start a connect web server', function (target) {
    if (target === 'dist') {
      return grunt.task.run(['build', 'connect:dist:keepalive']);
    }

    grunt.task.run([
      'clean:server',
      'wiredep',
      'concurrent:server',
      'autoprefixer',
      'connect:livereload',
      'watch'
    ]);
  });

  grunt.registerTask('server', 'DEPRECATED TASK. Use the "serve" task instead', function (target) {
    grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.');
    grunt.task.run(['serve:' + target]);
  });

  grunt.registerTask('test', [
    'clean:server',
    'concurrent:test',
    'autoprefixer',
    'connect:test',
    'karma'
  ]);

  grunt.registerTask('build', [
    'clean:dist',
    'wiredep',
    'useminPrepare',
    'concurrent:dist',
    'autoprefixer',
    'concat',
    'ngAnnotate',
    'copy:dist',
    'cdnify',
    'cssmin',
    'uglify',
    'filerev',
    'usemin',
    'htmlmin'
  ]);

  grunt.registerTask('default', [
    'newer:jshint',
    'test',
    'build'
  ]);
};
<commit_msg>Remove deprecated grunt task<commit_after>// Generated on 2014-12-24 using generator-angular 0.10.0
'use strict';

// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'

module.exports = function (grunt) {

  // Load grunt tasks automatically
  require('load-grunt-tasks')(grunt);

  // Time how long tasks take. Can help when optimizing build times
  require('time-grunt')(grunt);

  // Configurable paths for the application
  var appConfig = {
    app: require('./bower.json').appPath || 'app',
    dist: 'dist'
  };

  // Define the configuration for all the tasks
  grunt.initConfig({

    // Project settings
    yeoman: appConfig,

    // Watches files for changes and runs tasks based on the changed files
    watch: {
      bower: {
        files: ['bower.json'],
        tasks: ['wiredep']
      },
      js: {
        files: ['<%= yeoman.app %>/scripts/{,*/}*.js'],
        tasks: ['newer:jshint:all'],
        options: {
          livereload: '<%= connect.options.livereload %>'
        }
      },
      jsTest: {
        files: ['test/spec/{,*/}*.js'],
        tasks: ['newer:jshint:test', 'karma']
      },
      compass: {
        files: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'],
        tasks: ['compass:server', 'autoprefixer']
      },
      gruntfile: {
        files: ['Gruntfile.js']
      },
      livereload: {
        options: {
          livereload: '<%= connect.options.livereload %>'
        },
        files: [
          '<%= yeoman.app %>/{,*/}*.html',
          '.tmp/styles/{,*/}*.css',
          '<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
        ]
      }
    },

    // The actual grunt server settings
    connect: {
      options: {
        port: 9000,
        // Change this to '0.0.0.0' to access the server from outside.
        hostname: 'localhost',
        livereload: 35729
      },
      livereload: {
        options: {
          open: true,
          middleware: function (connect) {
            return [
              connect.static('.tmp'),
              connect().use(
                '/bower_components',
                connect.static('./bower_components')
              ),
              connect.static(appConfig.app)
            ];
          }
        }
      },
      test: {
        options: {
          port: 9001,
          middleware: function (connect) {
            return [
              connect.static('.tmp'),
              connect.static('test'),
              connect().use(
                '/bower_components',
                connect.static('./bower_components')
              ),
              connect.static(appConfig.app)
            ];
          }
        }
      },
      dist: {
        options: {
          open: true,
          base: '<%= yeoman.dist %>'
        }
      }
    },

    // Make sure code styles are up to par and there are no obvious mistakes
    jshint: {
      options: {
        jshintrc: '.jshintrc',
        reporter: require('jshint-stylish')
      },
      all: {
        src: [
          'Gruntfile.js',
          '<%= yeoman.app %>/scripts/{,*/}*.js'
        ]
      },
      test: {
        options: {
          jshintrc: 'test/.jshintrc'
        },
        src: ['test/spec/{,*/}*.js']
      }
    },

    // Empties folders to start fresh
    clean: {
      dist: {
        files: [{
          dot: true,
          src: [
            '.tmp',
            '<%= yeoman.dist %>/{,*/}*',
            '!<%= yeoman.dist %>/.git{,*/}*'
          ]
        }]
      },
      server: '.tmp'
    },

    // Add vendor prefixed styles
    autoprefixer: {
      options: {
        browsers: ['last 1 version']
      },
      dist: {
        files: [{
          expand: true,
          cwd: '.tmp/styles/',
          src: '{,*/}*.css',
          dest: '.tmp/styles/'
        }]
      }
    },

    // Automatically inject Bower components into the app
    wiredep: {
      app: {
        src: ['<%= yeoman.app %>/index.html'],
        ignorePath:  /\.\.\//
      },
      sass: {
        src: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'],
        ignorePath: /(\.\.\/){1,2}bower_components\//
      }
    },

    // Compiles Sass to CSS and generates necessary files if requested
    compass: {
      options: {
        sassDir: '<%= yeoman.app %>/styles',
        cssDir: '.tmp/styles',
        generatedImagesDir: '.tmp/images/generated',
        imagesDir: '<%= yeoman.app %>/images',
        javascriptsDir: '<%= yeoman.app %>/scripts',
        fontsDir: '<%= yeoman.app %>/styles/fonts',
        importPath: './bower_components',
        httpImagesPath: '/images',
        httpGeneratedImagesPath: '/images/generated',
        httpFontsPath: '/styles/fonts',
        relativeAssets: false,
        assetCacheBuster: false,
        raw: 'Sass::Script::Number.precision = 10\n'
      },
      dist: {
        options: {
          generatedImagesDir: '<%= yeoman.dist %>/images/generated'
        }
      },
      server: {
        options: {
          debugInfo: true
        }
      }
    },

    // Renames files for browser caching purposes
    filerev: {
      dist: {
        src: [
          '<%= yeoman.dist %>/scripts/{,*/}*.js',
          '<%= yeoman.dist %>/styles/{,*/}*.css',
          '<%= yeoman.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}',
          '<%= yeoman.dist %>/styles/fonts/*'
        ]
      }
    },

    // Reads HTML for usemin blocks to enable smart builds that automatically
    // concat, minify and revision files. Creates configurations in memory so
    // additional tasks can operate on them
    useminPrepare: {
      html: '<%= yeoman.app %>/index.html',
      options: {
        dest: '<%= yeoman.dist %>',
        flow: {
          html: {
            steps: {
              js: ['concat', 'uglifyjs'],
              css: ['cssmin']
            },
            post: {}
          }
        }
      }
    },

    // Performs rewrites based on filerev and the useminPrepare configuration
    usemin: {
      html: ['<%= yeoman.dist %>/{,*/}*.html'],
      css: ['<%= yeoman.dist %>/styles/{,*/}*.css'],
      options: {
        assetsDirs: ['<%= yeoman.dist %>','<%= yeoman.dist %>/images']
      }
    },

    // The following *-min tasks will produce minified files in the dist folder
    // By default, your `index.html`'s <!-- Usemin block --> will take care of
    // minification. These next options are pre-configured if you do not wish
    // to use the Usemin blocks.
    // cssmin: {
    //   dist: {
    //     files: {
    //       '<%= yeoman.dist %>/styles/main.css': [
    //         '.tmp/styles/{,*/}*.css'
    //       ]
    //     }
    //   }
    // },
    // uglify: {
    //   dist: {
    //     files: {
    //       '<%= yeoman.dist %>/scripts/scripts.js': [
    //         '<%= yeoman.dist %>/scripts/scripts.js'
    //       ]
    //     }
    //   }
    // },
    // concat: {
    //   dist: {}
    // },

    imagemin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= yeoman.app %>/images',
          src: '{,*/}*.{png,jpg,jpeg,gif}',
          dest: '<%= yeoman.dist %>/images'
        }]
      }
    },

    svgmin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= yeoman.app %>/images',
          src: '{,*/}*.svg',
          dest: '<%= yeoman.dist %>/images'
        }]
      }
    },

    htmlmin: {
      dist: {
        options: {
          collapseWhitespace: true,
          conservativeCollapse: true,
          collapseBooleanAttributes: true,
          removeCommentsFromCDATA: true,
          removeOptionalTags: true
        },
        files: [{
          expand: true,
          cwd: '<%= yeoman.dist %>',
          src: ['*.html', 'views/{,*/}*.html'],
          dest: '<%= yeoman.dist %>'
        }]
      }
    },

    // ng-annotate tries to make the code safe for minification automatically
    // by using the Angular long form for dependency injection.
    ngAnnotate: {
      dist: {
        files: [{
          expand: true,
          cwd: '.tmp/concat/scripts',
          src: ['*.js', '!oldieshim.js'],
          dest: '.tmp/concat/scripts'
        }]
      }
    },

    // Replace Google CDN references
    cdnify: {
      dist: {
        html: ['<%= yeoman.dist %>/*.html']
      }
    },

    // Copies remaining files to places other tasks can use
    copy: {
      dist: {
        files: [{
          expand: true,
          dot: true,
          cwd: '<%= yeoman.app %>',
          dest: '<%= yeoman.dist %>',
          src: [
            '*.{ico,png,txt}',
            '.htaccess',
            '*.html',
            'views/{,*/}*.html',
            'images/{,*/}*.{webp}',
            'fonts/{,*/}*.*'
          ]
        }, {
          expand: true,
          cwd: '.tmp/images',
          dest: '<%= yeoman.dist %>/images',
          src: ['generated/*']
        }, {
          expand: true,
          cwd: '.',
          src: 'bower_components/bootstrap-sass-official/assets/fonts/bootstrap/*',
          dest: '<%= yeoman.dist %>'
        }]
      },
      styles: {
        expand: true,
        cwd: '<%= yeoman.app %>/styles',
        dest: '.tmp/styles/',
        src: '{,*/}*.css'
      }
    },

    // Run some tasks in parallel to speed up the build process
    concurrent: {
      server: [
        'compass:server'
      ],
      test: [
        'compass'
      ],
      dist: [
        'compass:dist',
        'imagemin',
        'svgmin'
      ]
    },

    // Test settings
    karma: {
      unit: {
        configFile: 'test/karma.conf.js',
        singleRun: true
      }
    }
  });

  grunt.registerTask('serve', 'Compile then start a connect web server', function (target) {
    if (target === 'dist') {
      return grunt.task.run(['build', 'connect:dist:keepalive']);
    }

    grunt.task.run([
      'clean:server',
      'wiredep',
      'concurrent:server',
      'autoprefixer',
      'connect:livereload',
      'watch'
    ]);
  });

  grunt.registerTask('test', [
    'clean:server',
    'concurrent:test',
    'autoprefixer',
    'connect:test',
    'karma'
  ]);

  grunt.registerTask('build', [
    'clean:dist',
    'wiredep',
    'useminPrepare',
    'concurrent:dist',
    'autoprefixer',
    'concat',
    'ngAnnotate',
    'copy:dist',
    'cdnify',
    'cssmin',
    'uglify',
    'filerev',
    'usemin',
    'htmlmin'
  ]);

  grunt.registerTask('default', [
    'newer:jshint',
    'test',
    'build'
  ]);
};
<|endoftext|>


<commit_before>"use strict";

const {NodeVM} = require("vm2");
const fs = require("fs");
const {PartialOrder} = require("po-utils");
const {TotalOrder} = require("to-utils");
const {auth} = require("auth");
const {SecureKV_PO} = require("secure-kv-po");
const {SecureKV_TO} = require("secure-kv-to");
const aws = require("aws-sdk");
const nodemailer = require("nodemailer");
const got = require('got');
const fetch = require('node-fetch');

const rmFilesInDir = function (dirPath) {
    try {
        const files = fs.readdirSync(dirPath);

        if (files.length > 0)
            for (let i = 0; i < files.length; i++) {
                const filePath = dirPath + '/' + files[i];
                if (fs.statSync(filePath).isFile())
                    fs.unlinkSync(filePath);
                else
                    rmFilesInDir(filePath);
            }
    }
    catch(e) { }
};

const notEmptyDir = function (dirPath) {
    try {
        const files = fs.readdirSync(dirPath);
        return files.length > 0;
    }
    catch(e) { return true; }
};

const conf = JSON.parse(fs.readFileSync('conf.json', 'utf8'));
const unsecuredLambda = fs.readFileSync(conf.unsecLambda, 'utf8');

const labelOrdering = conf.usingPO ? new PartialOrder(conf.labels) : new TotalOrder(conf.min, conf.max);

module.exports.makeShim = function (exp, allowExtReq) {
    for (let handlerName of conf.handlers) {

        exp[handlerName] = function (event, context, callback) {

            let label;
            let securityBound;

            let p;
            const strippedEvent = event;
            if (conf.runFromKinesis) { // Handle events originating from AWS Kinesis.

                let ifcLabel;
                let storedSecurityBound;
                strippedEvent.Records = event.Records.map((record) => {
                    const payload = new Buffer(record.kinesis.data, 'base64').toString();
                    const parsed = JSON.parse(payload);
                    if (!ifcLabel) {
                        ifcLabel = parsed.ifcLabel;
                    } else if (ifcLabel !== parsed.ifcLabel) {
                        console.log("Batch of kinesis event with different labels unsupported.");
                        return callback("Batch of kinesis event with different labels unsupported.");
                    }
                    delete parsed.ifcLabel;

                    if (!storedSecurityBound) {
                        storedSecurityBound = parsed.securityBound;
                    } else if (storedSecurityBound !== parsed.securityBound) {
                        console.log("Batch of kinesis event with different security bounds unsupported.");
                        return callback("Batch of kinesis event with different security bounds unsupported.");
                    }
                    delete parsed.securityBound;

                    record.kinesis.data = new Buffer(JSON.stringify(parsed)).toString('base64');
                    return record;
                });

                if (!ifcLabel) {
                    console.log("Could not resolve an ifcLabel in kinesis event.")
                    return callback("Could not resolve an ifcLabel in kinesis event.")
                }
                if (!storedSecurityBound) {
                    console.log("Could not resolve a securityBound in kinesis event.")
                    return callback("Could not resolve a securityBound in kinesis event.")
                }

                console.log(`Running kinesis event with label: ${ifcLabel}`);

                securityBound = storedSecurityBound;
                console.log(`Running kinesis event with securityBound: ${securityBound}`);

                p = Promise.resolve(ifcLabel);
            } else if (conf.runFromSF /* && event.ifcLabel*/) { // Handle events originating from AWS Step Functions.
                const sfLabel = event.ifcLabel;
                delete strippedEvent.ifcLabel;

                securityBound = event.securityBound;
                delete strippedEvent.securityBound;

                p = Promise.resolve(sfLabel);
            } else {
                let reqUser;
                let reqPass;

                if (conf.runFromGET) { // Run http GET request on behalf of invoking user.
                    reqUser = event.queryStringParameters.user;
                    reqPass = event.queryStringParameters.pass;
                    if (conf.userPassForIFCOnly) {
                        delete event.queryStringParameters.user;
                        delete event.queryStringParameters.pass;
                    }
                } else { // Run http POST request on behalf of invoking user.
                    let reqBody;
                    if ((typeof event.body) === "string") {
                        reqBody = JSON.parse(event.body);
                    } else {
                        reqBody = event.body;
                    }
                    reqUser = reqBody.user;
                    reqPass = reqBody.pass;

                }
                p = auth(reqUser, reqPass);
            }
            const processEnv = {};

            for (let envVar of conf.processEnv) {
                processEnv[envVar] = process.env[envVar];
            }

            let executionEnv = {
                console: 'inherit',
                sandbox: {
                    process: {
                        env: processEnv,
                    },
                    externalEvent: strippedEvent,
                    externalContext: context,
                    externalCallback:
                        function (err, value) {
                            if (conf.runFromSF) { // Add label to the callback to the stepfunction, which in turn becomes the input to the next lambda.
                                if (value) {
                                    value.ifcLabel = label;
                                    value.securityBound = securityBound;
                                }
                                return callback(err, value);
                            } else {
                                if (conf.declassifier &&
                                    labelOrdering.lte(label, conf.declassifier.maxLabel) &&
                                    labelOrdering.lte(conf.declassifier.minLabel, securityBound)) {
                                    declf.declassifier(err, value, callback);
                                } else {
                                    if (labelOrdering.lte(label, securityBound)) {
                                        return callback(err, value);
                                    } else {
                                        return callback(null);
                                    }
                                }
                            }
                        },
                    bumpLabelTo:
                        function (newLabel) {
                            if (labelOrdering.lte(label, newLabel)) {
                                label = newLabel;
                                return true;
                            } else {
                                return false;
                            }
                        },
                    bumpLabelToTop:
                        function () {
                            label = labelOrdering.getTop();
                        }
                },
                require: {
                    external: allowExtReq,
                    builtin: ['fs', 'url'],
                    root: "./",
                    mock: {
                        'kv-store': {
                            KV_Store: function (h, u, pwd, tableName) {
                                const skv = conf.usingPO ?
                                    new SecureKV_PO(conf.host, conf.user, conf.pass, labelOrdering, tableName) :
                                    new SecureKV_TO(conf.host, conf.user, conf.pass, tableName);

                                return {
                                    init: () => skv.init(),
                                    close: () => skv.close(),
                                    put: (k, v) => skv.put(k, v, label),
                                    get: (k) => {
                                        return skv.get(k, label)
                                            .then((res) => {
                                                if (res.length > 0) {
                                                    return res[0].rowvalues;
                                                } else {
                                                    return res;
                                                }
                                            }); // Arbitrary choice (?)
                                    },
                                    del: (k) => skv.del(k, label),
                                    keys: () => skv.keys(label),
                                    entries: () => skv.entries(label),
                                }
                            }
                        },
                        'aws-sdk': {
                            config: aws.config,

                            Kinesis: function () {
                                const kinesis = new aws.Kinesis();
                                return {
                                    putRecord: (event, callback) => {
                                        const data = JSON.parse(event.Data);
                                        if (data.ifcLabel) { // && event.Data.ifcLabel !== label) {
                                            throw `Unexpected security label. Event written to kinesis should not have an ifcLabel field. Has label: ${event.ifcLabel}`;
                                        } else if (data.securityBound) {
                                            throw `Unexpected security bound. Event written to kinesis should not have a securityBound field. Has label: ${event.securityBound}`;
                                        } else {
                                            data.ifcLabel = label;
                                            data.securityBound = securityBound;

                                            event.Data = JSON.stringify(data);
                                            return kinesis.putRecord(event, callback);
                                        }
                                    },
                                }
                            },

                            StepFunctions: function () {
                                const stepfunctions = new aws.StepFunctions();
                                return {
                                    startExecution: (params, callback) => {
                                        // Can add additional security measures here.
                                        // e.g. check the stream name against a valid stream name in the configuration.

                                        const transParams = params;
                                        const input = JSON.parse(params.input);
                                        input.ifcLabel = label;
                                        input.securityBound = securityBound;
                                        transParams.input = JSON.stringify(input);
                                        return stepfunctions.startExecution(transParams, callback);
                                    },
                                    getActivityTask: (params, callback) => stepfunctions.getActivityTask(params, callback),
                                    sendTaskFailure: (params, callback) => stepfunctions.sendTaskFailure(params, callback),
                                    sendTaskSuccess: (params, callback) => stepfunctions.sendTaskSuccess(params, callback),
                                }
                            }
                        },
                        'nodemailer' : {
                            createTestAccount: () => {
                                if (labelOrdering.lte(label, securityBound)) {
                                    return nodemailer.createTestAccount();
                                } else {
                                    throw "Attempting to create test account in violation with security policy"
                                }
                            },
                            createTransport: (params) => {
                                const mailer = nodemailer.createTransport(params);

                                return {
                                    sendMail: (mailOptions) => {
                                        if (labelOrdering.lte(label, securityBound)) {
                                            return mailer.sendMail(mailOptions);
                                        } else {
                                            throw "Attempting to send in violation with security policy"
                                        }

                                    }
                                }
                            },
                            getTestMessageUrl: (info) => nodemailer.getTestMessageUrl(info),
                        },
                        'got' : {
                            get: (uri, params) => {
                                if (labelOrdering.lte(label, securityBound)) {
                                    return got.get(uri, params);
                                } else {
                                    return Promise.reject("Attempting to access a url in violation with security policy");
                                }
                            }
                        },
                        'node-fetch' : (params) => {
                            if (labelOrdering.lte(label, securityBound)) {
                                return fetch(params);
                            } else {
                                return Promise.reject("Attempting to access a url in violation with security policy");
                            }
                        }
                    }
                }
            };

            if (notEmptyDir('/tmp/')) {
                console.log("WARNING : /tmp/ dir not empty on fresh invocation of lambda. Might lead to data leak.")
            }

            p.then((l) => {
                if (l === undefined) {
                    // In case getting the label failed, run on behalf of 'bottom' (completely unprivileged).
                    label = labelOrdering.getBottom();
                } else {
                    label = l;
                }

                if (conf.securityBound) { // Statically defined security bound
                    securityBound = conf.securityBound;
                } else if (conf.runFromKinesis) {
                    if (!securityBound) {
                        console.log("Kinesis event with no security bound.");
                        return callback("Kinesis event with no security bound.");
                    }
                } else if (conf.runFromSF) {
                    if (!securityBound) {
                        console.log("StepFunctions event with no security bound.");
                        return callback("StepFunctions event with no security bound.");
                    }
                } else { // Running an http request - the security bound is the same as the invoking user's label.
                    securityBound = label;
                }

                let declf;
                if (conf.declassifier) {
                    // The relative path part of the next require is a very dangerous workaround to model load issues.
                    // TODO: KALEV - Should change to something more robust.
                    declf = require("../../decl");
                }

                const vm = new NodeVM(executionEnv);

                console.log(`
//  ***********************************
//  ** Original Lambda Code:
${unsecuredLambda}
//  ** End of Original Lambda Code:
//  ***********************************

module.exports.${handlerName}(externalEvent, externalContext, externalCallback);

        `);

                vm.run(`
//  ***********************************
//  ** Original Lambda Code:
${unsecuredLambda}
//  ** End of Original Lambda Code:
//  ***********************************

module.exports.${handlerName}(externalEvent, externalContext, externalCallback);
        `, conf.secLambdaFullPath);
            })
                .catch(err => {console.log(err)});
        };
    }
};

<commit_msg>Fixed a bug in that caused 'require' calls to bypass the mock when called from an imported module + added Rekognition to AWS mock.<commit_after>"use strict";

const {NodeVM} = require("vm2");
const fs = require("fs");
const {PartialOrder} = require("po-utils");
const {TotalOrder} = require("to-utils");
const {auth} = require("auth");
const {SecureKV_PO} = require("secure-kv-po");
const {SecureKV_TO} = require("secure-kv-to");
const aws = require("aws-sdk");
const nodemailer = require("nodemailer");
const got = require('got');
const fetch = require('node-fetch');

const rmFilesInDir = function (dirPath) {
    try {
        const files = fs.readdirSync(dirPath);

        if (files.length > 0)
            for (let i = 0; i < files.length; i++) {
                const filePath = dirPath + '/' + files[i];
                if (fs.statSync(filePath).isFile())
                    fs.unlinkSync(filePath);
                else
                    rmFilesInDir(filePath);
            }
    }
    catch(e) { }
};

const notEmptyDir = function (dirPath) {
    try {
        const files = fs.readdirSync(dirPath);
        return files.length > 0;
    }
    catch(e) { return true; }
};

const conf = JSON.parse(fs.readFileSync('conf.json', 'utf8'));
const unsecuredLambda = fs.readFileSync(conf.unsecLambda, 'utf8');

const labelOrdering = conf.usingPO ? new PartialOrder(conf.labels) : new TotalOrder(conf.min, conf.max);

module.exports.makeShim = function (exp, allowExtReq) {
    for (let handlerName of conf.handlers) {

        exp[handlerName] = function (event, context, callback) {

            let label;
            let securityBound;

            let p;
            const strippedEvent = event;
            if (conf.runFromKinesis) { // Handle events originating from AWS Kinesis.

                let ifcLabel;
                let storedSecurityBound;
                strippedEvent.Records = event.Records.map((record) => {
                    const payload = new Buffer(record.kinesis.data, 'base64').toString();
                    const parsed = JSON.parse(payload);
                    if (!ifcLabel) {
                        ifcLabel = parsed.ifcLabel;
                    } else if (ifcLabel !== parsed.ifcLabel) {
                        console.log("Batch of kinesis event with different labels unsupported.");
                        return callback("Batch of kinesis event with different labels unsupported.");
                    }
                    delete parsed.ifcLabel;

                    if (!storedSecurityBound) {
                        storedSecurityBound = parsed.securityBound;
                    } else if (storedSecurityBound !== parsed.securityBound) {
                        console.log("Batch of kinesis event with different security bounds unsupported.");
                        return callback("Batch of kinesis event with different security bounds unsupported.");
                    }
                    delete parsed.securityBound;

                    record.kinesis.data = new Buffer(JSON.stringify(parsed)).toString('base64');
                    return record;
                });

                if (!ifcLabel) {
                    console.log("Could not resolve an ifcLabel in kinesis event.")
                    return callback("Could not resolve an ifcLabel in kinesis event.")
                }
                if (!storedSecurityBound) {
                    console.log("Could not resolve a securityBound in kinesis event.")
                    return callback("Could not resolve a securityBound in kinesis event.")
                }

                console.log(`Running kinesis event with label: ${ifcLabel}`);

                securityBound = storedSecurityBound;
                console.log(`Running kinesis event with securityBound: ${securityBound}`);

                p = Promise.resolve(ifcLabel);
            } else if (conf.runFromSF /* && event.ifcLabel*/) { // Handle events originating from AWS Step Functions.
                const sfLabel = event.ifcLabel;
                delete strippedEvent.ifcLabel;

                securityBound = event.securityBound;
                delete strippedEvent.securityBound;

                p = Promise.resolve(sfLabel);
            } else {
                let reqUser;
                let reqPass;

                if (conf.runFromGET) { // Run http GET request on behalf of invoking user.
                    reqUser = event.queryStringParameters.user;
                    reqPass = event.queryStringParameters.pass;
                    if (conf.userPassForIFCOnly) {
                        delete event.queryStringParameters.user;
                        delete event.queryStringParameters.pass;
                    }
                } else { // Run http POST request on behalf of invoking user.
                    let reqBody;
                    if ((typeof event.body) === "string") {
                        reqBody = JSON.parse(event.body);
                    } else {
                        reqBody = event.body;
                    }
                    reqUser = reqBody.user;
                    reqPass = reqBody.pass;

                }
                p = auth(reqUser, reqPass);
            }
            const processEnv = {};

            for (let envVar of conf.processEnv) {
                processEnv[envVar] = process.env[envVar];
            }

            let executionEnv = {
                console: 'inherit',
                sandbox: {
                    process: {
                        env: processEnv,
                    },
                    externalEvent: strippedEvent,
                    externalContext: context,
                    externalCallback:
                        function (err, value) {
                            if (conf.runFromSF) { // Add label to the callback to the stepfunction, which in turn becomes the input to the next lambda.
                                if (value) {
                                    value.ifcLabel = label;
                                    value.securityBound = securityBound;
                                }
                                return callback(err, value);
                            } else {
                                if (conf.declassifier &&
                                    labelOrdering.lte(label, conf.declassifier.maxLabel) &&
                                    labelOrdering.lte(conf.declassifier.minLabel, securityBound)) {
                                    declf.declassifier(err, value, callback);
                                } else {
                                    if (labelOrdering.lte(label, securityBound)) {
                                        return callback(err, value);
                                    } else {
                                        return callback(null);
                                    }
                                }
                            }
                        },
                    bumpLabelTo:
                        function (newLabel) {
                            if (labelOrdering.lte(label, newLabel)) {
                                label = newLabel;
                                return true;
                            } else {
                                return false;
                            }
                        },
                    bumpLabelToTop:
                        function () {
                            label = labelOrdering.getTop();
                        }
                },
                require: {
                    context: 'sandbox',
                    external: allowExtReq,
                    builtin: ['fs', 'url'],
                    root: "./",
                    mock: {
                        'kv-store': {
                            KV_Store: function (h, u, pwd, tableName) {
                                const skv = conf.usingPO ?
                                    new SecureKV_PO(conf.host, conf.user, conf.pass, labelOrdering, tableName) :
                                    new SecureKV_TO(conf.host, conf.user, conf.pass, tableName);

                                return {
                                    init: () => skv.init(),
                                    close: () => skv.close(),
                                    put: (k, v) => skv.put(k, v, label),
                                    get: (k) => {
                                        return skv.get(k, label)
                                            .then((res) => {
                                                if (res.length > 0) {
                                                    return res[0].rowvalues;
                                                } else {
                                                    return res;
                                                }
                                            }); // Arbitrary choice (?)
                                    },
                                    del: (k) => skv.del(k, label),
                                    keys: () => skv.keys(label),
                                    entries: () => skv.entries(label),
                                }
                            }
                        },
                        'aws-sdk': {
                            config: aws.config,

                            Kinesis: function () {
                                const kinesis = new aws.Kinesis();
                                return {
                                    putRecord: (event, callback) => {
                                        const data = JSON.parse(event.Data);
                                        if (data.ifcLabel) { // && event.Data.ifcLabel !== label) {
                                            throw `Unexpected security label. Event written to kinesis should not have an ifcLabel field. Has label: ${event.ifcLabel}`;
                                        } else if (data.securityBound) {
                                            throw `Unexpected security bound. Event written to kinesis should not have a securityBound field. Has label: ${event.securityBound}`;
                                        } else {
                                            data.ifcLabel = label;
                                            data.securityBound = securityBound;

                                            event.Data = JSON.stringify(data);
                                            return kinesis.putRecord(event, callback);
                                        }
                                    },
                                }
                            },

                            StepFunctions: function () {
                                const stepfunctions = new aws.StepFunctions();
                                return {
                                    startExecution: (params, callback) => {
                                        // Can add additional security measures here.
                                        // e.g. check the stream name against a valid stream name in the configuration.

                                        const transParams = params;
                                        const input = JSON.parse(params.input);
                                        input.ifcLabel = label;
                                        input.securityBound = securityBound;
                                        transParams.input = JSON.stringify(input);
                                        return stepfunctions.startExecution(transParams, callback);
                                    },
                                    getActivityTask: (params, callback) => stepfunctions.getActivityTask(params, callback),
                                    sendTaskFailure: (params, callback) => stepfunctions.sendTaskFailure(params, callback),
                                    sendTaskSuccess: (params, callback) => stepfunctions.sendTaskSuccess(params, callback),
                                }
                            },

                            Rekognition: function () {
                                const rek = new aws.Rekognition();
                                return rek;

                                // NOTE: Might want to uncomment this code, to secure outgoing call to rekognition.
                                // return {
                                //     detectLabels: function (params, callback) {
                                //         if (labelOrdering.lte(label, securityBound)) {
                                //             return rek.detectLabels(params, callback);
                                //         } else {
                                //             return callback("Attempting to call detectLabels in violation with security policy");
                                //         }
                                //     }
                                // }
                            },
                        },
                        'nodemailer' : {
                            createTestAccount: () => {
                                if (labelOrdering.lte(label, securityBound)) {
                                    return nodemailer.createTestAccount();
                                } else {
                                    throw "Attempting to create test account in violation with security policy"
                                }
                            },
                            createTransport: (params) => {
                                const mailer = nodemailer.createTransport(params);

                                return {
                                    sendMail: (mailOptions) => {
                                        if (labelOrdering.lte(label, securityBound)) {
                                            return mailer.sendMail(mailOptions);
                                        } else {
                                            throw "Attempting to send in violation with security policy"
                                        }

                                    }
                                }
                            },
                            getTestMessageUrl: (info) => nodemailer.getTestMessageUrl(info),
                        },
                        'got' : {
                            get: (uri, params) => {
                                if (labelOrdering.lte(label, securityBound)) {
                                    return got.get(uri, params);
                                } else {
                                    return Promise.reject("Attempting to access a url in violation with security policy");
                                }
                            }
                        },
                        'node-fetch' : (params) => {
                            if (labelOrdering.lte(label, securityBound)) {
                                return fetch(params);
                            } else {
                                return Promise.reject("Attempting to access a url in violation with security policy");
                            }
                        }
                    }
                },
            };

            if (notEmptyDir('/tmp/')) {
                console.log("WARNING : /tmp/ dir not empty on fresh invocation of lambda. Might lead to data leak.")
            }

            p.then((l) => {
                if (l === undefined) {
                    // In case getting the label failed, run on behalf of 'bottom' (completely unprivileged).
                    label = labelOrdering.getBottom();
                } else {
                    label = l;
                }

                if (conf.securityBound) { // Statically defined security bound
                    securityBound = conf.securityBound;
                } else if (conf.runFromKinesis) {
                    if (!securityBound) {
                        console.log("Kinesis event with no security bound.");
                        return callback("Kinesis event with no security bound.");
                    }
                } else if (conf.runFromSF) {
                    if (!securityBound) {
                        console.log("StepFunctions event with no security bound.");
                        return callback("StepFunctions event with no security bound.");
                    }
                } else { // Running an http request - the security bound is the same as the invoking user's label.
                    securityBound = label;
                }

                let declf;
                if (conf.declassifier) {
                    // The relative path part of the next require is a very dangerous workaround to model load issues.
                    // TODO: KALEV - Should change to something more robust.
                    declf = require("../../decl");
                }

                const vm = new NodeVM(executionEnv);

                console.log(`
//  ***********************************
//  ** Original Lambda Code:
${unsecuredLambda}
//  ** End of Original Lambda Code:
//  ***********************************

module.exports.${handlerName}(externalEvent, externalContext, externalCallback);

        `);

                vm.run(`
//  ***********************************
//  ** Original Lambda Code:
${unsecuredLambda}
//  ** End of Original Lambda Code:
//  ***********************************

module.exports.${handlerName}(externalEvent, externalContext, externalCallback);
        `, conf.secLambdaFullPath);
            })
                .catch(err => {console.log(err)});
        };
    }
};

<|endoftext|>


<commit_before>'use strict';
const { noop, size, time, co2 } = require('./helpers');

module.exports = {
  browsertime: {
    timings: {
      firstPaint: {
        path: 'statistics.timings.firstPaint.median',
        summaryPath: 'firstPaint',
        name: 'First Paint',
        format: time.ms
      },
      firstContentfulPaint: {
        path: "statistics.timings.paintTiming['first-contentful-paint'].median",
        summaryPath: "paintTiming['first-contentful-paint']",
        name: 'First Contentful Paint',
        format: time.ms
      },
      largestContentfulPaint: {
        path: 'statistics.timings.largestContentfulPaint.median',
        summaryPath: 'timings.largestContentfulPaint',
        name: 'Largest Contentful Paint',
        format: time.ms
      },
      loadEventEnd: {
        path: 'statistics.timings.loadEventEnd.median',
        summaryPath: 'loadEventEnd',
        name: 'Load Event End',
        format: time.ms
      },
      fullyLoaded: {
        path: 'statistics.timings.fullyLoaded.median',
        summaryPath: 'timings.fullyLoaded',
        name: 'Fully Loaded',
        format: time.ms
      },
      serverResponseTime: {
        path: 'statistics.timings.pageTimings.serverResponseTime.median',
        summaryPath: 'pageTimings.serverResponseTime',
        name: 'Server Response Time',
        format: time.ms
      },
      backEndTime: {
        path: 'statistics.timings.pageTimings.backEndTime.median',
        summaryPath: 'pageTimings.backEndTime',
        name: 'TTFB',
        format: time.ms
      },
      pageLoadTime: {
        path: 'statistics.timings.pageTimings.pageLoadTime.median',
        summaryPath: 'pageTimings.pageLoadTime',
        name: 'Page Load Time',
        format: time.ms
      },
      FirstVisualChange: {
        path: 'statistics.visualMetrics.FirstVisualChange.median',
        summaryPath: 'visualMetrics.FirstVisualChange',
        name: 'First Visual Change',
        format: time.ms
      },
      LastVisualChange: {
        path: 'statistics.visualMetrics.LastVisualChange.median',
        name: 'Last Visual Change',
        summaryPath: 'visualMetrics.LastVisualChange',
        format: time.ms
      },
      SpeedIndex: {
        path: 'statistics.visualMetrics.SpeedIndex.median',
        summaryPath: 'visualMetrics.SpeedIndex',
        name: 'Speed Index',
        format: time.ms
      },
      ContentfulSpeedIndex: {
        path: 'statistics.visualMetrics.ContentfulSpeedIndex.median',
        summaryPath: 'visualMetrics.ContentfulSpeedIndex',
        name: 'Contentful Speed Index',
        format: time.ms
      },
      PerceptualSpeedIndex: {
        path: 'statistics.visualMetrics.PerceptualSpeedIndex.median',
        summaryPath: 'visualMetrics.PerceptualSpeedIndex',
        name: 'Perceptual Speed Index',
        format: time.ms
      },
      VisualReadiness: {
        path: 'statistics.visualMetrics.VisualReadiness.median',
        summaryPath: 'visualMetrics.VisualReadiness',
        name: 'Visual Readiness',
        format: time.ms
      },
      VisualComplete95: {
        path: 'statistics.visualMetrics.VisualComplete95.median',
        summaryPath: 'visualMetrics.VisualComplete95',
        name: 'Visual Complete 95',
        format: time.ms
      },
      VisualComplete99: {
        path: 'statistics.visualMetrics.VisualComplete99.median',
        summaryPath: 'visualMetrics.VisualComplete99',
        name: 'Visual Complete 99',
        format: time.ms
      },
      VisualComplete: {
        path: 'statistics.visualMetrics.VisualComplete.median',
        summaryPath: 'visualMetrics.VisualComplete',
        name: 'Visual Complete',
        format: time.ms
      }
    },
    cpu: {
      totalBlockingTime: {
        path: 'statistics.cpu.longTasks.totalBlockingTime.median',
        summaryPath: 'cpu.longTasks.totalBlockingTime',
        name: 'Total Blocking Time',
        format: time.ms
      },
      maxPotentialFid: {
        path: 'statistics.cpu.longTasks.maxPotentialFid.median',
        summaryPath: 'cpu.longTasks.maxPotentialFid',
        name: 'Max Potential FID',
        format: time.ms
      },
      longTasks: {
        path: 'statistics.cpu.longTasks.tasks.median',
        summaryPath: 'cpu.longTasks.tasks',
        name: 'Number of Long Tasks',
        format: noop
      },
      longTasksTotalDuration: {
        path: 'statistics.cpu.longTasks.totalDuration.median',
        summaryPath: 'cpu.longTasks.totalDuration',
        name: 'Total Duration of Long Tasks',
        format: time.ms
      }
    },
    pageinfo: {
      layoutShift: {
        path: 'statistics.pageinfo.layoutShift.median',
        summaryPath: 'pageinfo.layoutShift',
        name: 'Cumulative Layout Shift',
        format: noop
      }
    }
  },
  pagexray: {
    requests: {
      total: { path: 'requests', name: 'Total Requests', format: noop },
      html: {
        path: 'contentTypes.html.requests',
        name: 'HTML Requests',
        format: noop
      },
      javascript: {
        path: 'rontentTypes.javascript.requests',
        name: 'JavaScript Requests',
        format: noop
      },
      css: {
        path: 'contentTypes.css.request',
        name: 'CSS Requests',
        format: noop
      },
      image: {
        path: 'contentTypes.image.requests',
        name: 'Image Requests',
        format: noop
      },
      font: {
        path: 'contentTypes.font.requests',
        name: 'Font Requests',
        format: noop
      },
      httpErrors: { path: 'responseCodes', name: 'HTTP Errors', format: noop }
    },
    transferSize: {
      total: {
        path: 'transferSize',
        name: 'Total Transfer Size',
        format: size.format
      },
      html: {
        path: 'contentTypes.html.transferSize',
        name: 'HTML Transfer Size',
        format: size.format
      },
      javascript: {
        path: 'contentTypes.javascript.transferSize',
        name: 'JavaScript Transfer Size',
        format: size.format
      },
      css: {
        path: 'contentTypes.css.transferSize',
        name: 'CSS Transfer Size',
        format: size.format
      },
      image: {
        path: 'contentTypes.image.transferSize',
        name: 'Image Transfer Size',
        format: size.format
      },
      font: {
        path: 'contentTypes.font.transferSize',
        name: 'Font Transfer Size',
        format: size.format
      },
      favicon: {
        path: 'contentTypes.favicon.transferSize',
        name: 'Favicon Transfer Size',
        format: size.format
      },
      json: {
        path: 'contentTypes.json.transferSize',
        name: 'JSON Transfer Size',
        format: size.format
      },
      other: {
        path: 'contentTypes.other.transferSize',
        name: 'Other Transfer Size',
        format: size.format
      },
      plain: {
        path: 'contentTypes.plain.transferSize',
        name: 'Plain Transfer Size',
        format: size.format
      },
      svg: {
        path: 'contentTypes.svg.transferSize',
        name: 'SVG Transfer Size',
        format: size.format
      }
    },
    contentSize: {
      total: {
        path: 'contentSize',
        name: 'Total Content Size',
        format: size.format
      },
      html: {
        path: 'contentTypes.html.contentSize',
        name: 'HTML Content Size',
        format: size.format
      },
      javascript: {
        path: 'contentTypes.javascript.contentSize',
        name: 'JavaScript Content Size',
        format: size.format
      },
      css: {
        path: 'contentTypes.css.contentSize',
        name: 'CSS Content Size',
        format: size.format
      },
      image: {
        path: 'contentTypes.image.contentSize',
        name: 'Image Content Size',
        format: size.format
      },
      font: {
        path: 'contentTypes.font.contentSize',
        name: 'Font Content Size',
        format: size.format
      },
      favicon: {
        path: 'contentTypes.favicon.contentSize',
        name: 'Favicon Content Size',
        format: size.format
      },
      json: {
        path: 'contentTypes.json.contentSize',
        name: 'JSON Content Size',
        format: size.format
      },
      other: {
        path: 'contentTypes.other.contentSize',
        name: 'Other Content Size',
        format: size.format
      },
      plain: {
        path: 'contentTypes.plain.contentSize',
        name: 'Plain Content Size',
        format: size.format
      },
      svg: {
        path: 'contentTypes.svg.contentSize',
        name: 'SVG Content Size',
        format: size.format
      }
    },
    thirdParty: {
      transferSize: {
        path: 'thirdParty.transferSize',
        name: 'Third Party Transfer Size',
        format: size.format
      },
      requests: {
        path: 'thirdParty.requests',
        name: 'Third Party Requests',
        format: noop
      }
    },
    firstParty: {
      requests: {
        path: 'firstParty.requests',
        name: 'First Party Requests',
        format: noop
      },
      transferSize: {
        path: 'firstParty.transferSize',
        name: 'First Party Total Transfer Size',
        format: size.format
      },
      contentSize: {
        path: 'firstParty.contentSize',
        name: 'First Party Total Content Size',
        format: size.format
      }
    }
  },
  coach: {
    score: {
      score: {
        path: 'advice.score',
        summaryPath: 'score',
        name: 'Coach Overall Score',
        format: noop
      },
      accessibility: {
        path: 'advice.accessibility.score',
        summaryPath: 'accessibility.score',
        name: 'Coach Accessibility Score',
        format: noop
      },
      bestpractice: {
        path: 'advice.bestpractice.score',
        summaryPath: 'bestpractice.score',
        name: 'Coach Best Practice Score',
        format: noop
      },
      privacy: {
        path: 'advice.privacy.score',
        summaryPath: 'privacy.score',
        name: 'Coach Privacy Score',
        format: noop
      },
      performance: {
        path: 'advice.performance.score',
        summaryPath: 'performance.score',
        name: 'Coach Performance Score',
        format: noop
      }
    }
  },
  lighthouse: {
    lighthouse: {
      performance: {
        path: 'categories.performance.score',
        name: 'Lighthouse Performance Score',
        format: noop
      },
      accessibility: {
        path: 'categories.accessibility.score',
        name: 'Lighthouse Accessibility Score',
        format: noop
      },
      'best-practices': {
        path: 'categories.best-practices.score',
        name: 'Lighthouse Best Practices Score',
        format: noop
      },
      seo: {
        path: 'categories.seo.score',
        name: 'Lighthouse SEO Score',
        format: noop
      },
      pwa: {
        path: 'categories.pwa.score',
        name: 'Lighthouse PWA Score',
        format: noop
      }
    }
  },
  webpagetest: {
    webpagetest: {
      SpeedIndex: {
        path: 'data.median.firstView.SpeedIndex',
        name: 'WebPageTest Speed Index',
        format: time.ms
      },
      lastVisualChange: {
        path: 'data.median.firstView.lastVisualChange',
        name: 'WebPageTest Last Visual Change',
        format: time.ms
      },
      render: {
        path: 'data.median.firstView.render',
        name: 'WebPageTest First Visual Change',
        format: time.ms
      },
      visualComplete: {
        path: 'data.median.firstView.visualComplete',
        name: 'WebPageTest Visual Complete',
        format: time.ms
      },
      visualComplete95: {
        path: 'data.median.firstView.visualComplete95',
        name: 'WebPageTest Visual Complete 95',
        format: time.ms
      },
      TTFB: {
        path: 'data.median.firstView.TTFB',
        name: 'WebPageTest TTFB',
        format: time.ms
      },
      fullyLoaded: {
        path: 'data.median.firstView.fullyLoaded',
        name: 'WebPageTest Fully Loaded',
        format: time.ms
      }
    }
  },
  gpsi: {
    gpsi: {
      performance: {
        path: 'score.performance',
        name: 'GPSI Performance Score',
        format: noop
      },
      accessibility: {
        path: 'score.accessibility',
        name: 'GPSI Accessibility Score',
        format: noop
      },
      'best-practices': {
        path: 'score.best-practices',
        name: 'GPSI Best Practices Score',
        format: noop
      },
      seo: {
        path: 'score.seo',
        name: 'GPSI SEO Score',
        format: noop
      },
      pwa: {
        path: 'score.pwa',
        name: 'GPSI PWA Score',
        format: noop
      }
    }
  },
  sustainable: {
    sustainable: {
      totalCO2: {
        summaryPath: 'totalCO2',
        name: 'Total CO2',
        format: co2.format
      },
      co2PerPageView: {
        summaryPath: 'co2PerPageView',
        name: 'CO2 per page view',
        format: co2.format
      },
      co2FirstParty: {
        summaryPath: 'co2FirstParty',
        name: 'CO2 per first parties',
        format: co2.format
      },
      co2ThirdParty: {
        summaryPath: 'co2ThirdParty',
        name: 'CO2 per third parties',
        format: co2.format
      }
    }
  },
  axe: {
    axe: {
      critical: {
        path: 'violations.critical.median',
        summaryPath: 'violations.critical',
        name: 'AXE Critical Violations',
        format: noop
      },
      serious: {
        path: 'violations.serious.median',
        summaryPath: 'violations.serious',
        name: 'AXE Serious Violations',
        format: noop
      },
      minor: {
        path: 'violations.minor.median',
        summaryPath: 'violations.minor',
        name: 'AXE Minor Violations',
        format: noop
      },
      moderate: {
        path: 'violations.moderate.median',
        summaryPath: 'violations.moderate',
        name: 'AXE Moderate Violations',
        format: noop
      }
    }
  }
};
<commit_msg>Fix friendly name for budget #3071 (#3074)<commit_after>'use strict';
const { noop, size, time, co2 } = require('./helpers');

module.exports = {
  browsertime: {
    timings: {
      firstPaint: {
        path: 'statistics.timings.firstPaint.median',
        summaryPath: 'firstPaint',
        name: 'First Paint',
        format: time.ms
      },
      firstContentfulPaint: {
        path: "statistics.timings.paintTiming['first-contentful-paint'].median",
        summaryPath: "paintTiming['first-contentful-paint']",
        name: 'First Contentful Paint',
        format: time.ms
      },
      largestContentfulPaint: {
        path: 'statistics.timings.largestContentfulPaint.renderTime.median',
        summaryPath: 'timings.largestContentfulPaint',
        name: 'Largest Contentful Paint',
        format: time.ms
      },
      loadEventEnd: {
        path: 'statistics.timings.loadEventEnd.median',
        summaryPath: 'loadEventEnd',
        name: 'Load Event End',
        format: time.ms
      },
      fullyLoaded: {
        path: 'statistics.timings.fullyLoaded.median',
        summaryPath: 'timings.fullyLoaded',
        name: 'Fully Loaded',
        format: time.ms
      },
      serverResponseTime: {
        path: 'statistics.timings.pageTimings.serverResponseTime.median',
        summaryPath: 'pageTimings.serverResponseTime',
        name: 'Server Response Time',
        format: time.ms
      },
      backEndTime: {
        path: 'statistics.timings.pageTimings.backEndTime.median',
        summaryPath: 'pageTimings.backEndTime',
        name: 'TTFB',
        format: time.ms
      },
      pageLoadTime: {
        path: 'statistics.timings.pageTimings.pageLoadTime.median',
        summaryPath: 'pageTimings.pageLoadTime',
        name: 'Page Load Time',
        format: time.ms
      },
      FirstVisualChange: {
        path: 'statistics.visualMetrics.FirstVisualChange.median',
        summaryPath: 'visualMetrics.FirstVisualChange',
        name: 'First Visual Change',
        format: time.ms
      },
      LastVisualChange: {
        path: 'statistics.visualMetrics.LastVisualChange.median',
        name: 'Last Visual Change',
        summaryPath: 'visualMetrics.LastVisualChange',
        format: time.ms
      },
      SpeedIndex: {
        path: 'statistics.visualMetrics.SpeedIndex.median',
        summaryPath: 'visualMetrics.SpeedIndex',
        name: 'Speed Index',
        format: time.ms
      },
      ContentfulSpeedIndex: {
        path: 'statistics.visualMetrics.ContentfulSpeedIndex.median',
        summaryPath: 'visualMetrics.ContentfulSpeedIndex',
        name: 'Contentful Speed Index',
        format: time.ms
      },
      PerceptualSpeedIndex: {
        path: 'statistics.visualMetrics.PerceptualSpeedIndex.median',
        summaryPath: 'visualMetrics.PerceptualSpeedIndex',
        name: 'Perceptual Speed Index',
        format: time.ms
      },
      VisualReadiness: {
        path: 'statistics.visualMetrics.VisualReadiness.median',
        summaryPath: 'visualMetrics.VisualReadiness',
        name: 'Visual Readiness',
        format: time.ms
      },
      VisualComplete95: {
        path: 'statistics.visualMetrics.VisualComplete95.median',
        summaryPath: 'visualMetrics.VisualComplete95',
        name: 'Visual Complete 95',
        format: time.ms
      },
      VisualComplete99: {
        path: 'statistics.visualMetrics.VisualComplete99.median',
        summaryPath: 'visualMetrics.VisualComplete99',
        name: 'Visual Complete 99',
        format: time.ms
      },
      VisualComplete: {
        path: 'statistics.visualMetrics.VisualComplete.median',
        summaryPath: 'visualMetrics.VisualComplete',
        name: 'Visual Complete',
        format: time.ms
      }
    },
    cpu: {
      totalBlockingTime: {
        path: 'statistics.cpu.longTasks.totalBlockingTime.median',
        summaryPath: 'cpu.longTasks.totalBlockingTime',
        name: 'Total Blocking Time',
        format: time.ms
      },
      maxPotentialFid: {
        path: 'statistics.cpu.longTasks.maxPotentialFid.median',
        summaryPath: 'cpu.longTasks.maxPotentialFid',
        name: 'Max Potential FID',
        format: time.ms
      },
      longTasks: {
        path: 'statistics.cpu.longTasks.tasks.median',
        summaryPath: 'cpu.longTasks.tasks',
        name: 'Number of Long Tasks',
        format: noop
      },
      longTasksTotalDuration: {
        path: 'statistics.cpu.longTasks.totalDuration.median',
        summaryPath: 'cpu.longTasks.totalDuration',
        name: 'Total Duration of Long Tasks',
        format: time.ms
      }
    },
    pageinfo: {
      layoutShift: {
        path: 'statistics.pageinfo.layoutShift.median',
        summaryPath: 'pageinfo.layoutShift',
        name: 'Cumulative Layout Shift',
        format: noop
      }
    }
  },
  pagexray: {
    requests: {
      total: { path: 'requests', name: 'Total Requests', format: noop },
      html: {
        path: 'contentTypes.html.requests',
        name: 'HTML Requests',
        format: noop
      },
      javascript: {
        path: 'rontentTypes.javascript.requests',
        name: 'JavaScript Requests',
        format: noop
      },
      css: {
        path: 'contentTypes.css.request',
        name: 'CSS Requests',
        format: noop
      },
      image: {
        path: 'contentTypes.image.requests',
        name: 'Image Requests',
        format: noop
      },
      font: {
        path: 'contentTypes.font.requests',
        name: 'Font Requests',
        format: noop
      },
      httpErrors: { path: 'responseCodes', name: 'HTTP Errors', format: noop }
    },
    transferSize: {
      total: {
        path: 'transferSize',
        name: 'Total Transfer Size',
        format: size.format
      },
      html: {
        path: 'contentTypes.html.transferSize',
        name: 'HTML Transfer Size',
        format: size.format
      },
      javascript: {
        path: 'contentTypes.javascript.transferSize',
        name: 'JavaScript Transfer Size',
        format: size.format
      },
      css: {
        path: 'contentTypes.css.transferSize',
        name: 'CSS Transfer Size',
        format: size.format
      },
      image: {
        path: 'contentTypes.image.transferSize',
        name: 'Image Transfer Size',
        format: size.format
      },
      font: {
        path: 'contentTypes.font.transferSize',
        name: 'Font Transfer Size',
        format: size.format
      },
      favicon: {
        path: 'contentTypes.favicon.transferSize',
        name: 'Favicon Transfer Size',
        format: size.format
      },
      json: {
        path: 'contentTypes.json.transferSize',
        name: 'JSON Transfer Size',
        format: size.format
      },
      other: {
        path: 'contentTypes.other.transferSize',
        name: 'Other Transfer Size',
        format: size.format
      },
      plain: {
        path: 'contentTypes.plain.transferSize',
        name: 'Plain Transfer Size',
        format: size.format
      },
      svg: {
        path: 'contentTypes.svg.transferSize',
        name: 'SVG Transfer Size',
        format: size.format
      }
    },
    contentSize: {
      total: {
        path: 'contentSize',
        name: 'Total Content Size',
        format: size.format
      },
      html: {
        path: 'contentTypes.html.contentSize',
        name: 'HTML Content Size',
        format: size.format
      },
      javascript: {
        path: 'contentTypes.javascript.contentSize',
        name: 'JavaScript Content Size',
        format: size.format
      },
      css: {
        path: 'contentTypes.css.contentSize',
        name: 'CSS Content Size',
        format: size.format
      },
      image: {
        path: 'contentTypes.image.contentSize',
        name: 'Image Content Size',
        format: size.format
      },
      font: {
        path: 'contentTypes.font.contentSize',
        name: 'Font Content Size',
        format: size.format
      },
      favicon: {
        path: 'contentTypes.favicon.contentSize',
        name: 'Favicon Content Size',
        format: size.format
      },
      json: {
        path: 'contentTypes.json.contentSize',
        name: 'JSON Content Size',
        format: size.format
      },
      other: {
        path: 'contentTypes.other.contentSize',
        name: 'Other Content Size',
        format: size.format
      },
      plain: {
        path: 'contentTypes.plain.contentSize',
        name: 'Plain Content Size',
        format: size.format
      },
      svg: {
        path: 'contentTypes.svg.contentSize',
        name: 'SVG Content Size',
        format: size.format
      }
    },
    thirdParty: {
      transferSize: {
        path: 'thirdParty.transferSize',
        name: 'Third Party Transfer Size',
        format: size.format
      },
      requests: {
        path: 'thirdParty.requests',
        name: 'Third Party Requests',
        format: noop
      }
    },
    firstParty: {
      requests: {
        path: 'firstParty.requests',
        name: 'First Party Requests',
        format: noop
      },
      transferSize: {
        path: 'firstParty.transferSize',
        name: 'First Party Total Transfer Size',
        format: size.format
      },
      contentSize: {
        path: 'firstParty.contentSize',
        name: 'First Party Total Content Size',
        format: size.format
      }
    }
  },
  coach: {
    score: {
      score: {
        path: 'advice.score',
        summaryPath: 'score',
        name: 'Coach Overall Score',
        format: noop
      },
      accessibility: {
        path: 'advice.accessibility.score',
        summaryPath: 'accessibility.score',
        name: 'Coach Accessibility Score',
        format: noop
      },
      bestpractice: {
        path: 'advice.bestpractice.score',
        summaryPath: 'bestpractice.score',
        name: 'Coach Best Practice Score',
        format: noop
      },
      privacy: {
        path: 'advice.privacy.score',
        summaryPath: 'privacy.score',
        name: 'Coach Privacy Score',
        format: noop
      },
      performance: {
        path: 'advice.performance.score',
        summaryPath: 'performance.score',
        name: 'Coach Performance Score',
        format: noop
      }
    }
  },
  lighthouse: {
    lighthouse: {
      performance: {
        path: 'categories.performance.score',
        name: 'Lighthouse Performance Score',
        format: noop
      },
      accessibility: {
        path: 'categories.accessibility.score',
        name: 'Lighthouse Accessibility Score',
        format: noop
      },
      'best-practices': {
        path: 'categories.best-practices.score',
        name: 'Lighthouse Best Practices Score',
        format: noop
      },
      seo: {
        path: 'categories.seo.score',
        name: 'Lighthouse SEO Score',
        format: noop
      },
      pwa: {
        path: 'categories.pwa.score',
        name: 'Lighthouse PWA Score',
        format: noop
      }
    }
  },
  webpagetest: {
    webpagetest: {
      SpeedIndex: {
        path: 'data.median.firstView.SpeedIndex',
        name: 'WebPageTest Speed Index',
        format: time.ms
      },
      lastVisualChange: {
        path: 'data.median.firstView.lastVisualChange',
        name: 'WebPageTest Last Visual Change',
        format: time.ms
      },
      render: {
        path: 'data.median.firstView.render',
        name: 'WebPageTest First Visual Change',
        format: time.ms
      },
      visualComplete: {
        path: 'data.median.firstView.visualComplete',
        name: 'WebPageTest Visual Complete',
        format: time.ms
      },
      visualComplete95: {
        path: 'data.median.firstView.visualComplete95',
        name: 'WebPageTest Visual Complete 95',
        format: time.ms
      },
      TTFB: {
        path: 'data.median.firstView.TTFB',
        name: 'WebPageTest TTFB',
        format: time.ms
      },
      fullyLoaded: {
        path: 'data.median.firstView.fullyLoaded',
        name: 'WebPageTest Fully Loaded',
        format: time.ms
      }
    }
  },
  gpsi: {
    gpsi: {
      performance: {
        path: 'score.performance',
        name: 'GPSI Performance Score',
        format: noop
      },
      accessibility: {
        path: 'score.accessibility',
        name: 'GPSI Accessibility Score',
        format: noop
      },
      'best-practices': {
        path: 'score.best-practices',
        name: 'GPSI Best Practices Score',
        format: noop
      },
      seo: {
        path: 'score.seo',
        name: 'GPSI SEO Score',
        format: noop
      },
      pwa: {
        path: 'score.pwa',
        name: 'GPSI PWA Score',
        format: noop
      }
    }
  },
  sustainable: {
    sustainable: {
      totalCO2: {
        summaryPath: 'totalCO2',
        name: 'Total CO2',
        format: co2.format
      },
      co2PerPageView: {
        summaryPath: 'co2PerPageView',
        name: 'CO2 per page view',
        format: co2.format
      },
      co2FirstParty: {
        summaryPath: 'co2FirstParty',
        name: 'CO2 per first parties',
        format: co2.format
      },
      co2ThirdParty: {
        summaryPath: 'co2ThirdParty',
        name: 'CO2 per third parties',
        format: co2.format
      }
    }
  },
  axe: {
    axe: {
      critical: {
        path: 'violations.critical.median',
        summaryPath: 'violations.critical',
        name: 'AXE Critical Violations',
        format: noop
      },
      serious: {
        path: 'violations.serious.median',
        summaryPath: 'violations.serious',
        name: 'AXE Serious Violations',
        format: noop
      },
      minor: {
        path: 'violations.minor.median',
        summaryPath: 'violations.minor',
        name: 'AXE Minor Violations',
        format: noop
      },
      moderate: {
        path: 'violations.moderate.median',
        summaryPath: 'violations.moderate',
        name: 'AXE Moderate Violations',
        format: noop
      }
    }
  }
};
<|endoftext|>