Improved CSRF handling

This commit is contained in:
rainbow napkin 2025-05-04 17:52:55 -04:00
parent 2d5afc23d7
commit 1f00bacb6f
4 changed files with 74 additions and 8 deletions

View file

@ -0,0 +1,31 @@
/*Canopy - The next generation of stoner streaming software
Copyright (C) 2024-2025 Rainbownapkin and the TTN Community
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.*/
//local imports
const {exceptionHandler, errorHandler} = require('../../utils/loggerUtils');
const csrfUtils = require('../../utils/csrfUtils');
//api account functions
module.exports.get = async function(req, res){
try{
//Set status to 200
res.status(200);
//Generate and send token based on the request
res.send({token: csrfUtils.generateToken(req)});
}catch(err){
return exceptionHandler(res, err);
}
}

View file

@ -18,14 +18,19 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.*/
const { Router } = require('express'); const { Router } = require('express');
//local imports //local imports
const csrfUtil = require('../utils/csrfUtils');
const accountRouter = require("./api/accountRouter"); const accountRouter = require("./api/accountRouter");
const channelRouter = require("./api/channelRouter"); const channelRouter = require("./api/channelRouter");
const adminRouter = require("./api/adminRouter"); const adminRouter = require("./api/adminRouter");
const csrfUtil = require('../utils/csrfUtils'); const refreshCSRFTokenController = require("../controllers/api/refreshCSRFTokenController");
//globals //globals
const router = Router(); const router = Router();
//CSRF token request controller
router.get('/refreshToken', refreshCSRFTokenController.get);
//Apply Cross-Site Request Forgery protection to API calls //Apply Cross-Site Request Forgery protection to API calls
router.use(csrfUtil.csrfSynchronisedProtection); router.use(csrfUtil.csrfSynchronisedProtection);

View file

@ -48,8 +48,16 @@ class channel{
document.title = `${this.channelName} - Connected` document.title = `${this.channelName} - Connected`
}); });
this.socket.on("kick", (data) => { this.socket.on("kick", async (data) => {
new canopyUXUtils.popup(`You have been ${data.type} from the channel for the following reason:<br>${data.reason}`); if(data.reason == "Invalid CSRF Token!"){
//Reload the CSRF token
await utils.ajax.reloadCSRFToken();
//Retry the connection
this.connect();
}else{
new canopyUXUtils.popup(`You have been ${data.type} from the channel for the following reason:<br>${data.reason}`);
}
}); });
this.socket.on("clientMetadata", this.handleClientInfo.bind(this)); this.socket.on("clientMetadata", this.handleClientInfo.bind(this));

View file

@ -105,11 +105,18 @@ class canopyUXUtils{
try{ try{
const errors = body.errors; const errors = body.errors;
errors.forEach((err)=>{ errors.forEach((err)=>{
//Capitalize the first letter of the type if(err.msg == "invalid csrf token"){
const type = `${err.type[0].toUpperCase()}${err.type.slice(1)}` //reload CSRF token
utils.ajax.reloadCSRFToken();
//Display our error new canopyUXUtils.popup(`<h3>CSRF Error:</h3><p><br>Bad CSRF token, try again!</p>`);
new canopyUXUtils.popup(`<h3>${type} Error:</h3><p><br>${err.msg}</p>`); }else{
//Capitalize the first letter of the type
const type = `${err.type[0].toUpperCase()}${err.type.slice(1)}`
//Display our error
new canopyUXUtils.popup(`<h3>${type} Error:</h3><p><br>${err.msg}</p>`);
}
}); });
}catch(err){ }catch(err){
console.error("Display Error Body:"); console.error("Display Error Body:");
@ -1056,12 +1063,27 @@ class canopyAjaxUtils{
} }
} }
//Syntatic sugar //Syntatic sugar
getCSRFToken(){ getCSRFToken(){
return document.querySelector("[name='csrf-token']").content; return document.querySelector("[name='csrf-token']").content;
} }
async reloadCSRFToken(){
//Fetch a new token
var response = await fetch('/api/refreshToken',{
method: "GET"
});
if(response.ok){
//Get data from fetch
let data = await response.json()
//Inject new token into the page
document.querySelector("[name='csrf-token']").content = data.token;
}else{
utils.ux.displayResponseError(await response.json());
}
}
} }
const utils = new canopyUtils() const utils = new canopyUtils()