summary refs log tree commit diff
path: root/src/api/util
diff options
context:
space:
mode:
Diffstat (limited to 'src/api/util')
-rw-r--r--src/api/util/entities/AssetCacheItem.ts2
-rw-r--r--src/api/util/handlers/Instance.ts3
-rw-r--r--src/api/util/handlers/Message.ts52
-rw-r--r--src/api/util/handlers/route.ts18
-rw-r--r--src/api/util/index.ts2
-rw-r--r--src/api/util/utility/RandomInviteID.ts7
-rw-r--r--src/api/util/utility/String.ts2
-rw-r--r--src/api/util/utility/passwordStrength.ts10
8 files changed, 47 insertions, 49 deletions
diff --git a/src/api/util/entities/AssetCacheItem.ts b/src/api/util/entities/AssetCacheItem.ts
index 160dece6..958d5a61 100644
--- a/src/api/util/entities/AssetCacheItem.ts
+++ b/src/api/util/entities/AssetCacheItem.ts
@@ -1,3 +1,3 @@
 export class AssetCacheItem {
 	constructor(public Key: string, public FilePath: string = "", public Headers: any = null as any) {}
-}
\ No newline at end of file
+}
diff --git a/src/api/util/handlers/Instance.ts b/src/api/util/handlers/Instance.ts
index 7c337270..e03c9488 100644
--- a/src/api/util/handlers/Instance.ts
+++ b/src/api/util/handlers/Instance.ts
@@ -1,5 +1,4 @@
 import { Config, Guild, Session } from "@fosscord/util";
-import { createQueryBuilder } from "typeorm";
 
 export async function initInstance() {
 	// TODO: clean up database and delete tombstone data
@@ -10,7 +9,7 @@ export async function initInstance() {
 	const { autoJoin } = Config.get().guild;
 
 	if (autoJoin.enabled && !autoJoin.guilds?.length) {
-		let guild = await Guild.findOne({where: {}, order: {id: "ASC"}});
+		let guild = await Guild.findOne({ where: {}, order: { id: "ASC" } });
 		if (guild) {
 			// @ts-ignore
 			await Config.set({ guild: { autoJoin: { guilds: [guild.id] } } });
diff --git a/src/api/util/handlers/Message.ts b/src/api/util/handlers/Message.ts
index ff5ece75..d760d27c 100644
--- a/src/api/util/handlers/Message.ts
+++ b/src/api/util/handlers/Message.ts
@@ -1,32 +1,31 @@
 import {
+	Application,
+	Attachment,
 	Channel,
+	CHANNEL_MENTION,
+	Config,
 	Embed,
 	emitEvent,
+	EVERYONE_MENTION,
+	getPermission,
+	getRights,
 	Guild,
+	HERE_MENTION,
+	HTTPError,
 	Message,
 	MessageCreateEvent,
+	MessageCreateSchema,
+	MessageType,
 	MessageUpdateEvent,
-	getPermission,
-	getRights,
-	CHANNEL_MENTION,
-	Snowflake,
-	USER_MENTION,
-	ROLE_MENTION,
+	OrmUtils,
 	Role,
-	EVERYONE_MENTION,
-	HERE_MENTION,
-	MessageType,
+	ROLE_MENTION,
 	User,
-	Application,
-	Webhook,
-	Attachment,
-	Config,
-	MessageCreateSchema,
+	USER_MENTION,
+	Webhook
 } from "@fosscord/util";
-import { HTTPError } from "@fosscord/util";
-import fetch from "node-fetch";
 import cheerio from "cheerio";
-import { OrmUtils } from "@fosscord/util";
+import fetch from "node-fetch";
 
 const allow_empty = false;
 // TODO: check webhook, application, system author, stickers
@@ -61,21 +60,21 @@ export async function handleMessage(opts: MessageOptions): Promise<Message> {
 	});
 
 	if (message.content && message.content.length > Config.get().limits.message.maxCharacters) {
-		throw new HTTPError("Content length over max character limit")
+		throw new HTTPError("Content length over max character limit");
 	}
 
 	if (opts.author_id) {
 		message.author = await User.getPublicUser(opts.author_id);
 		const rights = await getRights(opts.author_id);
 		rights.hasThrow("SEND_MESSAGES");
-	}	
+	}
 	if (opts.application_id) {
 		message.application = await Application.findOneOrFail({ where: { id: opts.application_id } });
 	}
 	if (opts.webhook_id) {
 		message.webhook = await Webhook.findOneOrFail({ where: { id: opts.webhook_id } });
 	}
-	
+
 	const permission = await getPermission(opts.author_id, channel.guild_id, opts.channel_id);
 	permission.hasThrow("SEND_MESSAGES");
 	if (permission.cache.member) {
@@ -89,8 +88,10 @@ export async function handleMessage(opts: MessageOptions): Promise<Message> {
 		if (message.guild_id !== null) {
 			const guild = await Guild.findOneOrFail({ where: { id: channel.guild_id } });
 			if (!guild.features.includes("CROSS_CHANNEL_REPLIES")) {
-				if (opts.message_reference.guild_id !== channel.guild_id) throw new HTTPError("You can only reference messages from this guild");
-				if (opts.message_reference.channel_id !== opts.channel_id) throw new HTTPError("You can only reference messages from this channel");
+				if (opts.message_reference.guild_id !== channel.guild_id)
+					throw new HTTPError("You can only reference messages from this guild");
+				if (opts.message_reference.channel_id !== opts.channel_id)
+					throw new HTTPError("You can only reference messages from this channel");
 			}
 		}
 		/** Q: should be checked if the referenced message exists? ANSWER: NO
@@ -100,7 +101,7 @@ export async function handleMessage(opts: MessageOptions): Promise<Message> {
 	}
 
 	// TODO: stickers/activity
-	if (!allow_empty && (!opts.content && !opts.embeds?.length && !opts.attachments?.length && !opts.sticker_ids?.length)) {
+	if (!allow_empty && !opts.content && !opts.embeds?.length && !opts.attachments?.length && !opts.sticker_ids?.length) {
 		throw new HTTPError("Empty messages are not allowed", 50006);
 	}
 
@@ -110,7 +111,8 @@ export async function handleMessage(opts: MessageOptions): Promise<Message> {
 	let mention_user_ids = [] as string[];
 	let mention_everyone = false;
 
-	if (content) { // TODO: explicit-only mentions
+	if (content) {
+		// TODO: explicit-only mentions
 		message.content = content.trim();
 		for (const [_, mention] of content.matchAll(CHANNEL_MENTION)) {
 			if (!mention_channel_ids.includes(mention)) mention_channel_ids.push(mention);
@@ -158,7 +160,7 @@ export async function postHandleMessage(message: Message) {
 		try {
 			const request = await fetch(link, {
 				...DEFAULT_FETCH_OPTIONS,
-				size: Config.get().limits.message.maxEmbedDownloadSize,
+				size: Config.get().limits.message.maxEmbedDownloadSize
 			});
 
 			const text = await request.text();
diff --git a/src/api/util/handlers/route.ts b/src/api/util/handlers/route.ts
index 71e14955..d43ae103 100644
--- a/src/api/util/handlers/route.ts
+++ b/src/api/util/handlers/route.ts
@@ -1,8 +1,6 @@
 import {
 	DiscordApiErrors,
 	EVENT,
-	Event,
-	EventData,
 	FieldErrors,
 	FosscordApiErrors,
 	getPermission,
@@ -12,14 +10,14 @@ import {
 	RightResolvable,
 	Rights
 } from "@fosscord/util";
+import Ajv from "ajv";
+import addFormats from "ajv-formats";
+import { AnyValidateFunction } from "ajv/dist/core";
 import { NextFunction, Request, Response } from "express";
 import fs from "fs";
 import path from "path";
-import Ajv from "ajv";
-import { AnyValidateFunction } from "ajv/dist/core";
-import addFormats from "ajv-formats";
 
-const SchemaPath = path.join(__dirname, "..", "..", "..","..", "assets", "schemas.json");
+const SchemaPath = path.join(__dirname, "..", "..", "..", "..", "assets", "schemas.json");
 const schemas = JSON.parse(fs.readFileSync(SchemaPath, { encoding: "utf8" }));
 
 export const ajv = new Ajv({
@@ -117,10 +115,10 @@ export function route(opts: RouteOptions) {
 			const valid = validate(normalizeBody(req.body));
 			if (!valid) {
 				const fields: Record<string, { code?: string; message: string }> = {};
-				if(process.env.LOG_INVALID_BODY) {
-					console.log(`Got invalid request: ${req.method} ${req.originalUrl}`)
-					console.log(req.body)
-					validate.errors?.forEach(x => console.log(x.params))
+				if (process.env.LOG_INVALID_BODY) {
+					console.log(`Got invalid request: ${req.method} ${req.originalUrl}`);
+					console.log(req.body);
+					validate.errors?.forEach((x) => console.log(x.params));
 				}
 				validate.errors?.forEach((x) => (fields[x.instancePath.slice(1)] = { code: x.keyword, message: x.message || "" }));
 				throw FieldErrors(fields);
diff --git a/src/api/util/index.ts b/src/api/util/index.ts
index b3c7559f..76db5fd0 100644
--- a/src/api/util/index.ts
+++ b/src/api/util/index.ts
@@ -6,4 +6,4 @@ export * from "./utility/Base64";
 export * from "./utility/ipAddress";
 export * from "./utility/passwordStrength";
 export * from "./utility/RandomInviteID";
-export * from "./utility/String";
\ No newline at end of file
+export * from "./utility/String";
diff --git a/src/api/util/utility/RandomInviteID.ts b/src/api/util/utility/RandomInviteID.ts
index 7ea344e0..feebfd3d 100644
--- a/src/api/util/utility/RandomInviteID.ts
+++ b/src/api/util/utility/RandomInviteID.ts
@@ -22,11 +22,10 @@ export function snowflakeBasedInvite() {
 	// snowflakes hold ~10.75 characters worth of entropy;
 	// safe to generate a 8-char invite out of them
 	let str = "";
-	for (let i=0; i < 10; i++) {
-		
+	for (let i = 0; i < 10; i++) {
 		str.concat(chars.charAt(Number(snowflake % base)));
 		snowflake = snowflake / base;
 	}
-	
-	return str.substr(3,8).split("").reverse().join("");
+
+	return str.substr(3, 8).split("").reverse().join("");
 }
diff --git a/src/api/util/utility/String.ts b/src/api/util/utility/String.ts
index 982b7e11..a2e491e4 100644
--- a/src/api/util/utility/String.ts
+++ b/src/api/util/utility/String.ts
@@ -1,6 +1,6 @@
+import { FieldErrors } from "@fosscord/util";
 import { Request } from "express";
 import { ntob } from "./Base64";
-import { FieldErrors } from "@fosscord/util";
 
 export function checkLength(str: string, min: number, max: number, key: string, req: Request) {
 	if (str.length < min || str.length > max) {
diff --git a/src/api/util/utility/passwordStrength.ts b/src/api/util/utility/passwordStrength.ts
index 8eca63b8..ff83d3df 100644
--- a/src/api/util/utility/passwordStrength.ts
+++ b/src/api/util/utility/passwordStrength.ts
@@ -44,16 +44,16 @@ export function checkPassword(password: string): number {
 	if (password.length == password.count(reNUMBER) || password.length === password.count(reUPPERCASELETTER)) {
 		strength = 0;
 	}
-	
+
 	let entropyMap: { [key: string]: number } = {};
 	for (let i = 0; i < password.length; i++) {
 		if (entropyMap[password[i]]) entropyMap[password[i]]++;
 		else entropyMap[password[i]] = 1;
 	}
-	
+
 	let entropies = Object.values(entropyMap);
-	
-	entropies.map(x => (x / entropyMap.length));
-	strength += entropies.reduceRight((a: number, x: number) => a - (x * Math.log2(x))) / Math.log2(password.length);	
+
+	entropies.map((x) => x / entropyMap.length);
+	strength += entropies.reduceRight((a: number, x: number) => a - x * Math.log2(x)) / Math.log2(password.length);
 	return strength;
 }