dev: make anti-csrf more convenient

This commit is contained in:
KernelDeimos
2024-10-24 23:11:07 -04:00
parent f55b7ac0b8
commit b98c5a349e
3 changed files with 29 additions and 1 deletions

View File

@@ -492,6 +492,10 @@ module.exports = class APIError {
status: 400,
message: 'Puter apps must have a valid URL.'
},
'anti-csrf-incorrect': {
status: 400,
message: 'Incorrect or missing anti-CSRF token.',
},
// Chat
// TODO: specifying these errors here might be a violation

View File

@@ -0,0 +1,20 @@
const APIError = require("../api/APIError");
const anticsrf = options => async (req, res, next) => {
const svc_antiCSRF = req.services.get('anti-csrf');
if ( ! req.body.anti_csrf ) {
const err = APIError.create('anti-csrf-incorrect');
err.write(res);
return;
}
const has = svc_antiCSRF.consume_token(req.user.uuid, req.body.anti_csrf);
if ( ! has ) {
const err = APIError.create('anti-csrf-incorrect');
err.write(res);
return;
}
next();
};
module.exports = anticsrf;

View File

@@ -11,7 +11,8 @@ const CollectorHandle = (key, collector) => ({
// TODO: link this with kv.js for expiration handling
export default def(class Collector {
constructor ({ origin, authToken }) {
constructor ({ antiCSRF, origin, authToken }) {
this.antiCSRF = antiCSRF;
this.origin = origin;
this.authToken = authToken;
this.stored = {};
@@ -29,6 +30,9 @@ export default def(class Collector {
return await this.fetch({ method: 'get', route });
}
async post (route, body) {
if ( this.antiCSRF ) {
body.anti_csrf = await this.antiCSRF.token();
}
return await this.fetch({ method: 'post', route, body });
}