MCPcopy Create free account
hub / github.com/error311/FileRise / fetchWithCsrf

Function fetchWithCsrf

public/js/auth.js:154–199  ·  view source on GitHub ↗
(url, options = {})

Source from the content-addressed store, hash-verified

152 */
153
154export async function fetchWithCsrf(url, options = {}) {
155 const original = window.fetch.bind(window);
156 const wantJson = (options.headers && /json/i.test(options.headers['Content-Type'] || '')) || typeof options.body === 'string' && options.body.trim().startsWith('{');
157
158 options = { credentials: 'include', ...options };
159 options.headers = {
160 'Accept': 'application/json',
161 ...(options.headers || {})
162 };
163 if (window.csrfToken) {
164 options.headers['X-CSRF-Token'] = window.csrfToken;
165 }
166
167 async function retryWithFreshCsrf(asFormFallback = false) {
168 const tokRes = await original('/api/auth/token.php', { credentials: 'include' });
169 if (tokRes.ok) {
170 const body = await tokRes.json().catch(() => ({}));
171 if (body?.csrf_token) {
172 window.csrfToken = body.csrf_token;
173 const meta = document.querySelector('meta[name="csrf-token"]');
174 if (meta) meta.content = body.csrf_token;
175 options.headers['X-CSRF-Token'] = body.csrf_token;
176 }
177 }
178 if (asFormFallback && wantJson) {
179 // convert JSON body into x-www-form-urlencoded
180 const orig = options.body && typeof options.body === 'string' ? JSON.parse(options.body) : {};
181 options.body = toFormBody(orig);
182 options.headers['Content-Type'] = 'application/x-www-form-urlencoded';
183 }
184 return original(url, options);
185 }
186
187 let res = await original(url, options);
188
189 // If API doesn’t like JSON or token is stale
190 if (res.status === 400 || res.status === 403 || res.status === 415) {
191 // 1) retry with fresh CSRF keeping same encoding
192 res = await retryWithFreshCsrf(false);
193 if (!res.ok && wantJson) {
194 // 2) retry again as form-encoded
195 res = await retryWithFreshCsrf(true);
196 }
197 }
198 return res;
199}
200
201// wrap the TOTP modal opener to disable other login buttons only for Basic/OIDC flows
202function openTOTPLoginModal() {

Callers 8

setFolderEncryptionFunction · 0.85
tickOnceFunction · 0.85
startFolderCryptoJobFlowFunction · 0.85
renameFolderInlineFunction · 0.85
folderManager.jsFile · 0.85
submitLoginFunction · 0.85
initAuthFunction · 0.85

Calls 1

retryWithFreshCsrfFunction · 0.85

Tested by

no test coverage detected