function buildEdgeFunction()

in source/solution-helper/index.js [137:218]


function buildEdgeFunction(roleARN, edgeFunctionName, apiGatewayURL){
  return new Promise(function(resolve,reject){
    try{
      console.log("lambda_create_function");
        
      var zip = new JSZip();
      var lambdaCode = `'use strict';

exports.handler = async (event, context, callback) => {
const response = event.Records[0].cf.response;
const headers = response.headers;

headers['Strict-Transport-Security'] = [{
  key: 'Strict-Transport-Security',
  value: 'max-age=63072000; includeSubDomains; preload',
}];

headers['X-XSS-Protection'] = [{
  key: 'X-XSS-Protection',
  value: '1; mode=block',
}];

headers['X-Content-Type-Options'] = [{
  key: 'X-Content-Type-Options',
  value: 'nosniff',
}];

// headers['X-Frame-Options'] = [{
//     key: 'X-Frame-Options',
//     value: 'SAMEORIGIN',
// }];

headers['Referrer-Policy'] = [{ key: 'Referrer-Policy', value: 'no-referrer-when-downgrade' }];

headers['Content-Security-Policy'] = [{
  key: 'Content-Security-Policy',
  value: "upgrade-insecure-requests;default-src 'self'; img-src 'self' ; font-src 'self' https://fonts.gstatic.com; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; object-src 'none'; connect-src 'self' ${apiGatewayURL}",
}];

callback(null, response);
};`;

      zip.file("index.js", lambdaCode);

      zip.generateNodeStream({type:'nodebuffer',streamFiles:true})
      .pipe(fs.createWriteStream('/tmp/function.zip'))
      .on('finish', function () {
          // JSZip generates a readable stream with a "end" event,
          // but is piped here in a writable stream which emits a "finish" event.
          console.log("function.zip written.");

          var params = {
            Code: {
              ZipFile: fs.readFileSync('/tmp/function.zip')
            }, 
            Description: "Preference Center Lambda Edge Secure Header Function", 
            FunctionName: edgeFunctionName, 
            Handler: "index.handler", 
            MemorySize: 128, 
            Publish: true, 
            Role: roleARN, 
            Runtime: "nodejs12.x", 
            Timeout: 5
          };

          lambda.createFunction(params, function(err, data) {
            if (err) {
              console.log(err, err.stack); // an error occurred
              reject(err);
            } else {
              console.log(data); // successful response
              resolve(`${data.FunctionArn}:${data.Version}`);
            }   
          });

      });
    } catch (err){
      console.log(err);
      reject(err);
    }
  });
}