From 05057b922a84c6b0331357867dfa50166320b318 Mon Sep 17 00:00:00 2001 From: Diego Magdaleno Date: Fri, 21 May 2021 18:18:58 -0500 Subject: [PATCH] Config: Refactor config method, so we have a new get all option, fix issues in configurations --- src/middlewares/GlobalRateLimit.ts | 3 +-- src/routes/auth/login.ts | 5 ++--- src/routes/auth/register.ts | 3 +-- .../#channel_id/messages/bulk-delete.ts | 3 +-- src/routes/channels/#channel_id/pins.ts | 3 +-- src/routes/gateway.ts | 3 +-- src/routes/guilds/index.ts | 3 +-- src/routes/guilds/templates/index.ts | 3 +-- src/util/Config.ts | 18 +++++++++++++++--- src/util/Member.ts | 3 +-- src/util/passwordStrength.ts | 3 +-- 11 files changed, 26 insertions(+), 24 deletions(-) diff --git a/src/middlewares/GlobalRateLimit.ts b/src/middlewares/GlobalRateLimit.ts index 5186ae80..38098981 100644 --- a/src/middlewares/GlobalRateLimit.ts +++ b/src/middlewares/GlobalRateLimit.ts @@ -44,8 +44,7 @@ export async function GlobalRateLimit(req: Request, res: Response, next: NextFun } export function getIpAdress(req: Request): string { - const rateLimitProperties = Config.apiConfig.get('security', {jwtSecret: crypto.randomBytes(256).toString("base64"), forwadedFor: null, captcha: {enabled:false, service: null, sitekey: null, secret: null}}) as Config.DefaultOptions; - const { forwadedFor } = rateLimitProperties.security; + const { forwadedFor } = Config.apiConfig.getAll().security; const ip = forwadedFor ? req.headers[forwadedFor] : req.ip; return ip.replaceAll(".", "_").replaceAll(":", "_"); } diff --git a/src/routes/auth/login.ts b/src/routes/auth/login.ts index 218a56ae..1938b794 100644 --- a/src/routes/auth/login.ts +++ b/src/routes/auth/login.ts @@ -27,7 +27,7 @@ router.post( // TODO: Rewrite this to have the proper config syntax on the new method - const config = Config.apiConfig.store as unknown as Config.DefaultOptions; + const config = Config.apiConfig.getAll(); if (config.login.requireCaptcha && config.security.captcha.enabled) { if (!captcha_key) { @@ -69,10 +69,9 @@ export async function generateToken(id: string) { const algorithm = "HS256"; return new Promise((res, rej) => { - const securityPropertiesSecret = Config.apiConfig.get('security.jwtSecret') as Config.DefaultOptions; jwt.sign( { id: id, iat }, - securityPropertiesSecret.security.jwtSecret, + Config.apiConfig.getAll().security.jwtSecret, { algorithm, }, diff --git a/src/routes/auth/register.ts b/src/routes/auth/register.ts index 6389fb22..ca6351fa 100644 --- a/src/routes/auth/register.ts +++ b/src/routes/auth/register.ts @@ -52,8 +52,7 @@ router.post( let discriminator = ""; // get register Config - const securityProperties = Config.apiConfig.store as unknown as Config.DefaultOptions; - const { register, security } = securityProperties; + const { register, security } = Config.apiConfig.getAll(); // check if registration is allowed if (!register.allowNewRegistration) { diff --git a/src/routes/channels/#channel_id/messages/bulk-delete.ts b/src/routes/channels/#channel_id/messages/bulk-delete.ts index c469e495..c70e7ac1 100644 --- a/src/routes/channels/#channel_id/messages/bulk-delete.ts +++ b/src/routes/channels/#channel_id/messages/bulk-delete.ts @@ -20,8 +20,7 @@ router.post("/", check({ messages: [String] }), async (req, res) => { const permission = await getPermission(req.user_id, channel?.guild_id, channel_id, { channel }); permission.hasThrow("MANAGE_MESSAGES"); - const limitsProperties = Config.apiConfig.get('limits.message') as Config.DefaultOptions; - const { maxBulkDelete } = limitsProperties.limits.message; + const { maxBulkDelete } = Config.apiConfig.getAll().limits.message; const { messages } = req.body as { messages: string[] }; if (messages.length < 2) throw new HTTPError("You must at least specify 2 messages to bulk delete"); diff --git a/src/routes/channels/#channel_id/pins.ts b/src/routes/channels/#channel_id/pins.ts index d8e2be9b..4d8f53b1 100644 --- a/src/routes/channels/#channel_id/pins.ts +++ b/src/routes/channels/#channel_id/pins.ts @@ -18,8 +18,7 @@ router.put("/:message_id", async (req: Request, res: Response) => { if (channel.guild_id) permission.hasThrow("MANAGE_MESSAGES"); const pinned_count = await MessageModel.count({ channel_id, pinned: true }).exec(); - const limitsProperties = Config.apiConfig.get('limits.channel') as Config.DefaultOptions; - const { maxPins } = limitsProperties.limits.channel; + const { maxPins } = Config.apiConfig.getAll().limits.channel; if (pinned_count >= maxPins) throw new HTTPError("Max pin count reached: " + maxPins); await MessageModel.updateOne({ id: message_id }, { pinned: true }).exec(); diff --git a/src/routes/gateway.ts b/src/routes/gateway.ts index f92053e5..04ab1248 100644 --- a/src/routes/gateway.ts +++ b/src/routes/gateway.ts @@ -4,8 +4,7 @@ import * as Config from "../util/Config" const router = Router(); router.get("/", (req, res) => { - const generalConfig = Config.apiConfig.get('gateway', 'ws://localhost:3002') as Config.DefaultOptions; - const { gateway } = generalConfig; + const { gateway } = Config.apiConfig.getAll(); res.send({ url: gateway || "ws://localhost:3002" }); }); diff --git a/src/routes/guilds/index.ts b/src/routes/guilds/index.ts index 89f60ab2..e1fbd180 100644 --- a/src/routes/guilds/index.ts +++ b/src/routes/guilds/index.ts @@ -14,8 +14,7 @@ const router: Router = Router(); router.post("/", check(GuildCreateSchema), async (req: Request, res: Response) => { const body = req.body as GuildCreateSchema; - const limitsProperties = Config.apiConfig.get('limits.user') as Config.DefaultOptions; - const { maxGuilds } = limitsProperties.limits.user; + const { maxGuilds } = Config.apiConfig.getAll().limits.user; const user = await getPublicUser(req.user_id, { guilds: true }); if (user.guilds.length >= maxGuilds) { diff --git a/src/routes/guilds/templates/index.ts b/src/routes/guilds/templates/index.ts index c314728d..a7af8295 100644 --- a/src/routes/guilds/templates/index.ts +++ b/src/routes/guilds/templates/index.ts @@ -21,8 +21,7 @@ router.post("/:code", check(GuildTemplateCreateSchema), async (req: Request, res const { code } = req.params; const body = req.body as GuildTemplateCreateSchema; - const limitsProperties = Config.apiConfig.get('limits.user') as Config.DefaultOptions; - const { maxGuilds } = limitsProperties.limits.user; + const { maxGuilds } = Config.apiConfig.getAll().limits.user; const user = await getPublicUser(req.user_id, { guilds: true }); if (user.guilds.length >= maxGuilds) { diff --git a/src/util/Config.ts b/src/util/Config.ts index 1dcd61c0..ee7a2f96 100644 --- a/src/util/Config.ts +++ b/src/util/Config.ts @@ -1,5 +1,4 @@ -import Ajv, { JSONSchemaType } from "ajv" -import { ValidateFunction } from 'ajv' +import Ajv, { JSONSchemaType, ValidateFunction } from "ajv" import ajvFormats from 'ajv-formats'; import dotProp from "dot-prop"; import envPaths from "env-paths"; @@ -101,6 +100,7 @@ export interface DefaultOptions { }; } + const schema: JSONSchemaType & { definitions: { rateLimitOptions: JSONSchemaType @@ -398,6 +398,10 @@ class Config = Record> implements } } + private _has(key: Key | string): boolean { + return dotProp.has(this.store, key as string); + } + private _validate(data: T | unknown): void { if (!this.#validator) { return; @@ -432,7 +436,7 @@ class Config = Record> implements private _ensureDirectory(): void { fs.mkdirSync(path.dirname(this.path), { recursive: true }) } - + set store(value: T) { this._validate(value); @@ -449,9 +453,17 @@ class Config = Record> implements return this._get(key, defaultValue); } + public getAll(): DefaultOptions { + return this.store as unknown as DefaultOptions + } + private _get(key: Key): T[Key] | undefined; private _get(key: Key, defaultValue: Default): T[Key] | Default; private _get(key: Key | string, defaultValue?: Default): Default | undefined { + if (!this._has(key)) { + throw new Error("Tried to acess a non existant property in the config"); + } + return dotProp.get(this.store, key as string, defaultValue as T[Key]); } diff --git a/src/util/Member.ts b/src/util/Member.ts index 87c3e6e1..2842298d 100644 --- a/src/util/Member.ts +++ b/src/util/Member.ts @@ -39,8 +39,7 @@ export async function isMember(user_id: string, guild_id: string) { export async function addMember(user_id: string, guild_id: string, cache?: { guild?: GuildDocument }) { const user = await getPublicUser(user_id, { guilds: true }); - const limitsUserProperties = Config.apiConfig.get('limits.user', {maxGuilds: 100, masxUsername: 32, maxFriends: 1000}) as Config.DefaultOptions; - const { maxGuilds } = limitsUserProperties.limits.user; + const { maxGuilds } = Config.apiConfig.getAll().limits.user; if (user.guilds.length >= maxGuilds) { throw new HTTPError(`You are at the ${maxGuilds} server limit.`, 403); } diff --git a/src/util/passwordStrength.ts b/src/util/passwordStrength.ts index 71a5b5be..7196f797 100644 --- a/src/util/passwordStrength.ts +++ b/src/util/passwordStrength.ts @@ -17,14 +17,13 @@ const blocklist: string[] = []; // TODO: update ones passwordblocklist is stored * Returns: 0 > pw > 1 */ export function check(password: string): number { - const passwordProperties = Config.apiConfig.get('register.password', { minLength: 8, minNumbers: 2, minUpperCase: 2, minSymbols: 0, blockInsecureCommonPasswords: false }) as Config.DefaultOptions; const { minLength, minNumbers, minUpperCase, minSymbols, blockInsecureCommonPasswords, - } = passwordProperties.register.password; + } = Config.apiConfig.getAll().register.password; var strength = 0; // checks for total password len