CSRF protection
Create a CSRF token for a page, check it in a middleware of your routes and in WebSocket routes.
A browser sends the cookies of your application also with a request that another website started. A CSRF token stops such requests: your page gets a token from the server and sends it back with each change, and the other website cannot read it.
The default cookies of the framework have SameSite=Lax, so browsers do not send them with a POST request from another website. The token is a second protection, useful with $cookiesamesite : None or for forms that work without a login.
The functions are in the reference.
Turning it on
Set a secret in the config file. Without it the token is an empty string and every check passes:
secret_csrf : a-long-random-text
$csrfexpiration : 2 hoursA token is bound to the IP address and the browser (User-Agent) of the visitor and is valid for the time in $csrfexpiration (30 minutes by default).
The token in the page
@{csrf} prints the token in a view, and $.csrf() creates it in a controller:
<form action="/contact/?csrf=@{csrf}" method="POST">
<input type="text" name="name" />
<button>Send</button>
</form>ROUTE('GET /csrf/', function($) {
$.json({ token: $.csrf() });
});The server reads the token from the header x-csrf-token or from the query argument csrf. JavaScript sends the header:
fetch('/contact/', { method: 'POST', headers: { 'content-type': 'application/json', 'x-csrf-token': token }, body: JSON.stringify(data) });Checking the token
HTTP routes do not check the token by themselves. Write a middleware with DEF.onCSRFcheck($) and put it on the routes that change something:
// middleware/csrf.js
MIDDLEWARE('csrf', function($, next) {
if (DEF.onCSRFcheck($))
next();
else
$.invalid(403);
});ROUTE('GET /contact/', 'contact');
ROUTE('POST /contact/ #csrf', function($) {
$.success();
});A POST without a valid token gets the status 403.
A WebSocket route checks the token with the flag @csrf (see WebSockets). Browsers cannot set headers on a WebSocket, so the token goes in the address:
ROUTE('SOCKET /live/ @csrf', function($) {
$.on('message', (client, msg) => client.send(msg));
});new WebSocket('wss://shop.example.com/live/?csrf=' + token);Your own tokens
DEF.onCSRFcreate and DEF.onCSRFcheck create and check the token, and you can replace both. This pair binds the token to the session instead of the IP address, which changes on mobile networks. It is for routes of signed-in users, with the sessions of Authorization:
// definitions/csrf.js
DEF.onCSRFcreate = function($) {
return ENCRYPT({ id: $.sessionid, expire: NOW.add('2 hours').getTime() }, CONF.secret_csrf);
};
DEF.onCSRFcheck = function($) {
var token = DECRYPT($.headers['x-csrf-token'] || $.query.csrf || '', CONF.secret_csrf);
return token && $.sessionid ? token.id === $.sessionid && token.expire > Date.now() : false;
};