|
| 1 | +document.addEventListener('submit', function (event) { |
| 2 | + var csrfField = event.target.querySelector('input[data-controller="csrf-protection"]'); |
| 3 | + |
| 4 | + if (!csrfField) { |
| 5 | + return; |
| 6 | + } |
| 7 | + |
| 8 | + var csrfCookie = csrfField.getAttribute('data-csrf-protection-cookie-value'); |
| 9 | + var csrfToken = csrfField.value; |
| 10 | + |
| 11 | + if (!csrfCookie && /^[-_a-zA-Z0-9]{4,22}$/.test(csrfToken)) { |
| 12 | + csrfField.setAttribute('data-csrf-protection-cookie-value', csrfCookie = csrfToken); |
| 13 | + csrfField.value = csrfToken = btoa(String.fromCharCode.apply(null, (window.crypto || window.msCrypto).getRandomValues(new Uint8Array(18)))); |
| 14 | + } |
| 15 | + |
| 16 | + if (csrfCookie && /^[-_/+a-zA-Z0-9]{24,}$/.test(csrfToken)) { |
| 17 | + var cookie = csrfCookie + '_' + csrfToken + '=' + csrfCookie + '; path=/; samesite=strict'; |
| 18 | + document.cookie = window.location.protocol === 'https:' ? '__Host-' + cookie + '; secure' : cookie; |
| 19 | + } |
| 20 | +}); |
| 21 | + |
| 22 | +document.addEventListener('turbo:submit-start', function (event) { |
| 23 | + var csrfField = event.detail.formSubmission.formElement.querySelector('input[data-controller="csrf-protection"]'); |
| 24 | + |
| 25 | + if (!csrfField) { |
| 26 | + return; |
| 27 | + } |
| 28 | + |
| 29 | + var csrfCookie = csrfField.getAttribute('data-csrf-protection-cookie-value'); |
| 30 | + |
| 31 | + if (/^[-_/+a-zA-Z0-9]{24,}$/.test(csrfField.value) && /^[-_a-zA-Z0-9]{4,22}$/.test(csrfCookie)) { |
| 32 | + event.detail.formSubmission.fetchRequest.headers[csrfCookie] = csrfField.value; |
| 33 | + } |
| 34 | +}); |
| 35 | + |
| 36 | +document.addEventListener('turbo:submit-end', function (event) { |
| 37 | + var csrfField = event.detail.formSubmission.formElement.querySelector('input[data-controller="csrf-protection"]'); |
| 38 | + |
| 39 | + if (!csrfField) { |
| 40 | + return; |
| 41 | + } |
| 42 | + |
| 43 | + var csrfCookie = csrfField.getAttribute('data-csrf-protection-cookie-value'); |
| 44 | + |
| 45 | + if (/^[-_/+a-zA-Z0-9]{24,}$/.test(csrfField.value) && /^[-_a-zA-Z0-9]{4,22}$/.test(csrfCookie)) { |
| 46 | + var cookie = csrfCookie + '_' + csrfField.value + '=0; path=/; samesite=strict; max-age=0'; |
| 47 | + |
| 48 | + document.cookie = window.location.protocol === 'https:' ? '__Host-' + cookie + '; secure' : cookie; |
| 49 | + } |
| 50 | +}); |
| 51 | + |
| 52 | +/* stimulusFetch: 'lazy' */ |
| 53 | +export default 'csrf-protection-controller'; |
0 commit comments