From 01e61d7995388b35359c9477f45ca4b664a08ed5 Mon Sep 17 00:00:00 2001 From: ai-bot Date: Sat, 14 Nov 2026 16:15:25 +0000 Subject: [PATCH] Add static/session.js to add the CSRF header and handle 401 --- static/session.js | 63 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 static/session.js diff --git a/static/session.js b/static/session.js new file mode 100644 index 0000000..7651cb6 --- /dev/null +++ b/static/session.js @@ -0,0 +1,63 @@ +/* Skuld — patch window.fetch so every same-origin call carries the CSRF token. + * + * The server sends the CSRF secret in a script-readable cookie (skuld_csrf) + * next to the HttpOnly session cookie. This file copies it into the + * X-CSRF-Token header of every mutating call, and sends the browser to /login + * when the session has gone. + * + * Load this before app.js. + */ + +(function () { + "use strict"; + + var MUTATING = ["POST", "PATCH", "PUT", "DELETE"]; + var CSRF_COOKIE = "skuld_csrf"; + + function readCookie(name) { + var prefix = name + "="; + var parts = document.cookie ? document.cookie.split("; ") : []; + for (var i = 0; i < parts.length; i += 1) { + if (parts[i].indexOf(prefix) === 0) { + return decodeURIComponent(parts[i].slice(prefix.length)); + } + } + return ""; + } + + function isSameOrigin(url) { + if (!url) { + return true; + } + if (url.indexOf("//") === -1) { + return true; + } + return url.indexOf(window.location.origin) === 0; + } + + var nativeFetch = window.fetch ? window.fetch.bind(window) : null; + if (!nativeFetch) { + return; + } + + window.fetch = function (input, init) { + var options = init ? Object.assign({}, init) : {}; + var url = typeof input === "string" ? input : (input && input.url) || ""; + var method = (options.method || (input && input.method) || "GET").toUpperCase(); + + if (isSameOrigin(url) && MUTATING.indexOf(method) !== -1) { + var headers = new Headers(options.headers || (input && input.headers) || {}); + if (!headers.has("X-CSRF-Token")) { + headers.set("X-CSRF-Token", readCookie(CSRF_COOKIE)); + } + options.headers = headers; + } + + return nativeFetch(input, options).then(function (response) { + if (response.status === 401 && window.location.pathname !== "/login") { + window.location.href = "/login"; + } + return response; + }); + }; +})();