diff options
author | Catalan Lover <48515417+FSG-Cat@users.noreply.github.com> | 2022-08-24 22:21:07 +0200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2022-08-24 22:21:07 +0200 |
commit | 8abee23ca809c715fbcbd50eacabff028edd69ed (patch) | |
tree | 393be1820fcbfc2afec343efcfccf4c553b586b9 | |
parent | Added Env and Software Vars. (diff) | |
parent | Merge pull request #799 from MaddyUnderStars/feat/captchaVerify (diff) | |
download | server-8abee23ca809c715fbcbd50eacabff028edd69ed.tar.xz |
Merge branch 'fosscord:staging' into Bug-Report-Template
-rw-r--r-- | src/api/middlewares/RateLimit.ts | 3 | ||||
-rw-r--r-- | src/api/routes/auth/login.ts | 25 | ||||
-rw-r--r-- | src/api/routes/auth/register.ts | 24 | ||||
-rw-r--r-- | src/api/util/index.ts | 1 | ||||
-rw-r--r-- | src/api/util/utility/captcha.ts | 46 | ||||
-rw-r--r-- | src/api/util/utility/ipAddress.ts | 6 | ||||
-rw-r--r-- | src/util/config/types/subconfigurations/limits/RateLimits.ts | 2 | ||||
-rw-r--r-- | src/util/config/types/subconfigurations/limits/ratelimits/Route.ts | 2 |
8 files changed, 73 insertions, 36 deletions
diff --git a/src/api/middlewares/RateLimit.ts b/src/api/middlewares/RateLimit.ts index 7754edf6..dc93dcef 100644 --- a/src/api/middlewares/RateLimit.ts +++ b/src/api/middlewares/RateLimit.ts @@ -48,7 +48,7 @@ export default function rateLimit(opts: { // exempt user? if so, immediately short circuit if (req.user_id) { const rights = await getRights(req.user_id); - if (rights.has("BYPASS_RATE_LIMITS")) return; + if (rights.has("BYPASS_RATE_LIMITS")) return next(); } const bucket_id = opts.bucket || req.originalUrl.replace(API_PREFIX_TRAILING_SLASH, ""); @@ -121,6 +121,7 @@ export default function rateLimit(opts: { export async function initRateLimits(app: Router) { const { routes, global, ip, error, disabled } = Config.get().limits.rate; if (disabled) return; + console.log("Enabling rate limits..."); await listenEvent(EventRateLimit, (event) => { Cache.set(event.channel_id as string, event.data); event.acknowledge?.(); diff --git a/src/api/routes/auth/login.ts b/src/api/routes/auth/login.ts index f5415a56..68b2656a 100644 --- a/src/api/routes/auth/login.ts +++ b/src/api/routes/auth/login.ts @@ -1,8 +1,7 @@ -import { route, getIpAdress } from "@fosscord/api"; -import { adjustEmail, Config, FieldErrors, generateToken, LoginSchema, User } from "@fosscord/util"; -import crypto from "crypto"; import { Request, Response, Router } from "express"; -import fetch from "node-fetch"; +import { route, getIpAdress, verifyCaptcha } from "@fosscord/api"; +import { Config, User, generateToken, adjustEmail, FieldErrors, LoginSchema } from "@fosscord/util"; +import crypto from "crypto"; let bcrypt: any; try { @@ -23,7 +22,7 @@ router.post("/", route({ body: "LoginSchema" }), async (req: Request, res: Respo const config = Config.get(); if (config.login.requireCaptcha && config.security.captcha.enabled) { - const { sitekey, secret, service } = config.security.captcha; + const { sitekey, service } = config.security.captcha; if (!captcha_key) { return res.status(400).json({ captcha_key: ["captcha-required"], @@ -32,20 +31,14 @@ router.post("/", route({ body: "LoginSchema" }), async (req: Request, res: Respo }); } - - let captchaUrl = ""; - if (service === "recaptcha") { - captchaUrl = `https://www.google.com/recaptcha/api/siteverify=${sitekey}?secret=${secret}&response=${captcha_key}&remoteip=${ip}`; - } else if (service === "hcaptcha") { - captchaUrl = `https://hcaptcha.com/siteverify?sitekey=${sitekey}&secret=${secret}&response=${captcha_key}&remoteip=${ip}`; - } - const response: { success: boolean; "error-codes": string[] } = await (await fetch(captchaUrl, { method: "POST" })).json(); - if (!response.success) { + const ip = getIpAdress(req); + const verify = await verifyCaptcha(captcha_key, ip); + if (!verify.success) { return res.status(400).json({ - captcha_key: response["error-codes"], + captcha_key: verify["error-codes"], captcha_sitekey: sitekey, captcha_service: service - }); + }) } } diff --git a/src/api/routes/auth/register.ts b/src/api/routes/auth/register.ts index 7ff691d0..d3b5a59c 100644 --- a/src/api/routes/auth/register.ts +++ b/src/api/routes/auth/register.ts @@ -1,7 +1,6 @@ -import { getIpAdress, IPAnalysis, isProxy, route } from "@fosscord/api"; -import { adjustEmail, Config, FieldErrors, generateToken, HTTPError, Invite, RegisterSchema, User } from "@fosscord/util"; import { Request, Response, Router } from "express"; -import fetch from "node-fetch"; +import { Config, generateToken, Invite, FieldErrors, User, adjustEmail, RegisterSchema } from "@fosscord/util"; +import { route, getIpAdress, IPAnalysis, isProxy, verifyCaptcha } from "@fosscord/api"; let bcrypt: any; try { @@ -10,6 +9,7 @@ try { bcrypt = require("bcryptjs"); console.log("Warning: using bcryptjs because bcrypt is not installed! Performance will be affected."); } +import { HTTPError } from "@fosscord/util"; const router: Router = Router(); @@ -45,8 +45,7 @@ router.post("/", route({ body: "RegisterSchema" }), async (req: Request, res: Re } if (register.requireCaptcha && security.captcha.enabled) { - const { sitekey, secret, service } = security.captcha; - + const { sitekey, service } = security.captcha; if (!body.captcha_key) { return res?.status(400).json({ captcha_key: ["captcha-required"], @@ -55,20 +54,13 @@ router.post("/", route({ body: "RegisterSchema" }), async (req: Request, res: Re }); } - - let captchaUrl = ""; - if (service === "recaptcha") { - captchaUrl = `https://www.google.com/recaptcha/api/siteverify=${sitekey}?secret=${secret}&response=${body.captcha_key}&remoteip=${ip}`; - } else if (service === "hcaptcha") { - captchaUrl = `https://hcaptcha.com/siteverify?sitekey=${sitekey}&secret=${secret}&response=${body.captcha_key}&remoteip=${ip}`; - } - const response: { success: boolean; "error-codes": string[] } = await (await fetch(captchaUrl, { method: "POST" })).json(); - if (!response.success) { + const verify = await verifyCaptcha(body.captcha_key, ip); + if (!verify.success) { return res.status(400).json({ - captcha_key: response["error-codes"], + captcha_key: verify["error-codes"], captcha_sitekey: sitekey, captcha_service: service - }); + }) } } diff --git a/src/api/util/index.ts b/src/api/util/index.ts index 76db5fd0..31e75325 100644 --- a/src/api/util/index.ts +++ b/src/api/util/index.ts @@ -7,3 +7,4 @@ export * from "./utility/ipAddress"; export * from "./utility/passwordStrength"; export * from "./utility/RandomInviteID"; export * from "./utility/String"; +export * from "./utility/captcha"; \ No newline at end of file diff --git a/src/api/util/utility/captcha.ts b/src/api/util/utility/captcha.ts new file mode 100644 index 00000000..739647d2 --- /dev/null +++ b/src/api/util/utility/captcha.ts @@ -0,0 +1,46 @@ +import { Config } from "@fosscord/util"; +import fetch from "node-fetch"; + +export interface hcaptchaResponse { + success: boolean; + challenge_ts: string; + hostname: string; + credit: boolean; + "error-codes": string[]; + score: number; // enterprise only + score_reason: string[]; // enterprise only +} + +export interface recaptchaResponse { + success: boolean; + score: number; // between 0 - 1 + action: string; + challenge_ts: string; + hostname: string; + "error-codes"?: string[]; +} + +const verifyEndpoints = { + hcaptcha: "https://hcaptcha.com/siteverify", + recaptcha: "https://www.google.com/recaptcha/api/siteverify", +} + +export async function verifyCaptcha(response: string, ip?: string) { + const { security } = Config.get(); + const { service, secret, sitekey } = security.captcha; + + if (!service) throw new Error("Cannot verify captcha without service"); + + const res = await fetch(verifyEndpoints[service], { + method: "POST", + headers: { + "Content-Type": "application/x-www-form-urlencoded", + }, + body: `response=${encodeURIComponent(response)}` + + `&secret=${encodeURIComponent(secret!)}` + + `&sitekey=${encodeURIComponent(sitekey!)}` + + (ip ? `&remoteip=${encodeURIComponent(ip!)}` : ""), + }); + + return await res.json() as hcaptchaResponse | recaptchaResponse; +} \ No newline at end of file diff --git a/src/api/util/utility/ipAddress.ts b/src/api/util/utility/ipAddress.ts index 8d986b26..c96feb9e 100644 --- a/src/api/util/utility/ipAddress.ts +++ b/src/api/util/utility/ipAddress.ts @@ -78,7 +78,11 @@ export function isProxy(data: typeof exampleData) { export function getIpAdress(req: Request): string { // @ts-ignore - return req.headers[Config.get().security.forwadedFor] || req.socket.remoteAddress; + return ( + req.headers[Config.get().security.forwadedFor as string] || + req.headers[Config.get().security.forwadedFor?.toLowerCase() as string] || + req.socket.remoteAddress + ); } export function distanceBetweenLocations(loc1: any, loc2: any): number { diff --git a/src/util/config/types/subconfigurations/limits/RateLimits.ts b/src/util/config/types/subconfigurations/limits/RateLimits.ts index db3f8a4c..764acdd6 100644 --- a/src/util/config/types/subconfigurations/limits/RateLimits.ts +++ b/src/util/config/types/subconfigurations/limits/RateLimits.ts @@ -14,5 +14,5 @@ export class RateLimits { count: 10, window: 5 }; - routes: RouteRateLimit; + routes: RouteRateLimit = new RouteRateLimit(); } diff --git a/src/util/config/types/subconfigurations/limits/ratelimits/Route.ts b/src/util/config/types/subconfigurations/limits/ratelimits/Route.ts index 464670f2..6890699e 100644 --- a/src/util/config/types/subconfigurations/limits/ratelimits/Route.ts +++ b/src/util/config/types/subconfigurations/limits/ratelimits/Route.ts @@ -14,6 +14,6 @@ export class RouteRateLimit { count: 10, window: 5 }; - auth: AuthRateLimit; + auth: AuthRateLimit = new AuthRateLimit(); // TODO: rate limit configuration for all routes } |