From ab151cb732b2ff20f4588f9f0558f65c3174a13e Mon Sep 17 00:00:00 2001 From: Wolvan Date: Wed, 12 Jan 2022 19:46:45 +0100 Subject: [PATCH] Use CSRF token to discourage botting A suggestion to avoid stupid bots to vote on polls was a token that gets checked to a session cookie on vote submission. --- frontend/html/poll.html | 1 + src/backend.ts | 14 ++++++++++++++ src/frontend.ts | 7 +++++++ 3 files changed, 22 insertions(+) diff --git a/frontend/html/poll.html b/frontend/html/poll.html index 8ee9f65..ca51be6 100644 --- a/frontend/html/poll.html +++ b/frontend/html/poll.html @@ -36,6 +36,7 @@
+
{{ POLL_TITLE }}
diff --git a/src/backend.ts b/src/backend.ts index 0ce5e8c..de9acdb 100644 --- a/src/backend.ts +++ b/src/backend.ts @@ -4,6 +4,7 @@ import { CookieOptions, Router } from "express"; import { BackendPoll as Poll, DupeCheckMode } from "./Poll"; import { MAX_POLL_OPTIONS, MAX_CHARACTER_LENGTH } from "./Config"; import Storage from "./Storage"; +import crypto from "crypto"; function randomString(length = 10, charset = "abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789") { let result = ""; @@ -213,12 +214,25 @@ export default async function init(router: Router, polls: Storage): Promise` ).join(""); + const csrfToken = req.cookies.csrftoken || crypto.randomBytes(32).toString("base64"); + res.cookie("csrftoken", csrfToken, { + httpOnly: true, + }); + await displayPage(req, res, "poll.html", { + "CSRF_TOKEN": csrfToken, "POLL_ID": poll.id, "POLL_TITLE": xss(poll.title), "POLL_OPTION_DIVS": pollOptions,