application.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536
  1. 'use strict';
  2. const safeCurl = require('../../lib/extend/safe_curl');
  3. const INPUT_CSRF = '\r\n<input type="hidden" name="_csrf" value="{{ctx.csrf}}" /></form>';
  4. exports.injectCsrf = function injectCsrf(tmplStr) {
  5. tmplStr = tmplStr.replace(/(<form.*?>)([\s\S]*?)<\/form>/gi, function replaceCsrf(_, $1, $2) {
  6. const match = $2;
  7. if (match.indexOf('name="_csrf"') !== -1 || match.indexOf('name=\'_csrf\'') !== -1) {
  8. return $1 + match + '</form>';
  9. }
  10. return $1 + match + INPUT_CSRF;
  11. });
  12. return tmplStr;
  13. };
  14. exports.injectNonce = function injectNonce(tmplStr) {
  15. tmplStr = tmplStr.replace(/<script(.*?)>([\s\S]*?)<\/script[^>]*?>/gi, function replaceNonce(_, $1, $2) {
  16. if ($1.indexOf('nonce=') === -1) {
  17. $1 += ' nonce="{{ctx.nonce}}"';
  18. }
  19. return '<script' + $1 + '>' + $2 + '</script>';
  20. });
  21. return tmplStr;
  22. };
  23. const INJECTION_DEFENSE = '<!--for injection--><!--</html>--><!--for injection-->';
  24. exports.injectHijackingDefense = function injectHijackingDefense(tmplStr) {
  25. return INJECTION_DEFENSE + tmplStr + INJECTION_DEFENSE;
  26. };
  27. exports.safeCurl = safeCurl;