csrf_protection_controller.js 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. const nameCheck = /^[-_a-zA-Z0-9]{4,22}$/;
  2. const tokenCheck = /^[-_/+a-zA-Z0-9]{24,}$/;
  3. // Generate and double-submit a CSRF token in a form field and a cookie, as defined by Symfony's SameOriginCsrfTokenManager
  4. // Use `form.requestSubmit()` to ensure that the submit event is triggered. Using `form.submit()` will not trigger the event
  5. // and thus this event-listener will not be executed.
  6. document.addEventListener('submit', function (event) {
  7. generateCsrfToken(event.target);
  8. }, true);
  9. // When @hotwired/turbo handles form submissions, send the CSRF token in a header in addition to a cookie
  10. // The `framework.csrf_protection.check_header` config option needs to be enabled for the header to be checked
  11. document.addEventListener('turbo:submit-start', function (event) {
  12. const h = generateCsrfHeaders(event.detail.formSubmission.formElement);
  13. Object.keys(h).map(function (k) {
  14. event.detail.formSubmission.fetchRequest.headers[k] = h[k];
  15. });
  16. });
  17. // When @hotwired/turbo handles form submissions, remove the CSRF cookie once a form has been submitted
  18. document.addEventListener('turbo:submit-end', function (event) {
  19. removeCsrfToken(event.detail.formSubmission.formElement);
  20. });
  21. export function generateCsrfToken (formElement) {
  22. const csrfField = formElement.querySelector('input[data-controller="csrf-protection"], input[name="_csrf_token"]');
  23. if (!csrfField) {
  24. return;
  25. }
  26. let csrfCookie = csrfField.getAttribute('data-csrf-protection-cookie-value');
  27. let csrfToken = csrfField.value;
  28. if (!csrfCookie && nameCheck.test(csrfToken)) {
  29. csrfField.setAttribute('data-csrf-protection-cookie-value', csrfCookie = csrfToken);
  30. csrfField.defaultValue = csrfToken = btoa(String.fromCharCode.apply(null, (window.crypto || window.msCrypto).getRandomValues(new Uint8Array(18))));
  31. }
  32. csrfField.dispatchEvent(new Event('change', { bubbles: true }));
  33. if (csrfCookie && tokenCheck.test(csrfToken)) {
  34. const cookie = csrfCookie + '_' + csrfToken + '=' + csrfCookie + '; path=/; samesite=strict';
  35. document.cookie = window.location.protocol === 'https:' ? '__Host-' + cookie + '; secure' : cookie;
  36. }
  37. }
  38. export function generateCsrfHeaders (formElement) {
  39. const headers = {};
  40. const csrfField = formElement.querySelector('input[data-controller="csrf-protection"], input[name="_csrf_token"]');
  41. if (!csrfField) {
  42. return headers;
  43. }
  44. const csrfCookie = csrfField.getAttribute('data-csrf-protection-cookie-value');
  45. if (tokenCheck.test(csrfField.value) && nameCheck.test(csrfCookie)) {
  46. headers[csrfCookie] = csrfField.value;
  47. }
  48. return headers;
  49. }
  50. export function removeCsrfToken (formElement) {
  51. const csrfField = formElement.querySelector('input[data-controller="csrf-protection"], input[name="_csrf_token"]');
  52. if (!csrfField) {
  53. return;
  54. }
  55. const csrfCookie = csrfField.getAttribute('data-csrf-protection-cookie-value');
  56. if (tokenCheck.test(csrfField.value) && nameCheck.test(csrfCookie)) {
  57. const cookie = csrfCookie + '_' + csrfField.value + '=0; path=/; samesite=strict; max-age=0';
  58. document.cookie = window.location.protocol === 'https:' ? '__Host-' + cookie + '; secure' : cookie;
  59. }
  60. }
  61. /* stimulusFetch: 'lazy' */
  62. export default 'csrf-protection-controller';