diff options
author | Emma [it/its]@Rory& <root@rory.gay> | 2023-12-11 01:12:54 +0100 |
---|---|---|
committer | Emma [it/its]@Rory& <root@rory.gay> | 2023-12-11 01:12:54 +0100 |
commit | 0a8ceb9e6349284e75545a01ffad608b020f78e2 (patch) | |
tree | 17a9163f963eddabf9168b0b630096b2f7535b64 /src/api/util | |
parent | Prettier: use editorconfig (diff) | |
download | server-0a8ceb9e6349284e75545a01ffad608b020f78e2.tar.xz |
Actually run prettier dev/emma-refactors
Diffstat (limited to 'src/api/util')
-rw-r--r-- | src/api/util/handlers/Message.ts | 63 | ||||
-rw-r--r-- | src/api/util/handlers/Voice.ts | 9 | ||||
-rw-r--r-- | src/api/util/handlers/route.ts | 24 | ||||
-rw-r--r-- | src/api/util/utility/Base64.ts | 3 | ||||
-rw-r--r-- | src/api/util/utility/EmbedHandlers.ts | 88 | ||||
-rw-r--r-- | src/api/util/utility/RandomInviteID.ts | 6 | ||||
-rw-r--r-- | src/api/util/utility/String.ts | 8 | ||||
-rw-r--r-- | src/api/util/utility/captcha.ts | 2 | ||||
-rw-r--r-- | src/api/util/utility/ipAddress.ts | 31 | ||||
-rw-r--r-- | src/api/util/utility/passwordStrength.ts | 12 |
10 files changed, 62 insertions, 184 deletions
diff --git a/src/api/util/handlers/Message.ts b/src/api/util/handlers/Message.ts index 6172a3d0..24e307ca 100644 --- a/src/api/util/handlers/Message.ts +++ b/src/api/util/handlers/Message.ts @@ -58,12 +58,9 @@ export async function handleMessage(opts: MessageOptions): Promise<Message> { where: { id: opts.channel_id }, relations: ["recipients"], }); - if (!channel || !opts.channel_id) - throw new HTTPError("Channel not found", 404); + if (!channel || !opts.channel_id) throw new HTTPError("Channel not found", 404); - const stickers = opts.sticker_ids - ? await Sticker.find({ where: { id: In(opts.sticker_ids) } }) - : undefined; + const stickers = opts.sticker_ids ? await Sticker.find({ where: { id: In(opts.sticker_ids) } }) : undefined; const message = Message.create({ ...opts, sticker_items: stickers, @@ -75,10 +72,7 @@ export async function handleMessage(opts: MessageOptions): Promise<Message> { type: opts.type ?? 0, }); - if ( - message.content && - message.content.length > Config.get().limits.message.maxCharacters - ) { + if (message.content && message.content.length > Config.get().limits.message.maxCharacters) { throw new HTTPError("Content length over max character limit"); } @@ -98,11 +92,7 @@ export async function handleMessage(opts: MessageOptions): Promise<Message> { }); } - const permission = await getPermission( - opts.author_id, - channel.guild_id, - opts.channel_id, - ); + const permission = await getPermission(opts.author_id, channel.guild_id, opts.channel_id); permission.hasThrow("SEND_MESSAGES"); if (permission.cache.member) { message.member = permission.cache.member; @@ -118,13 +108,9 @@ export async function handleMessage(opts: MessageOptions): Promise<Message> { }); 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", - ); + 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", - ); + throw new HTTPError("You can only reference messages from this channel"); } } /** Q: should be checked if the referenced message exists? ANSWER: NO @@ -162,27 +148,22 @@ export async function handleMessage(opts: MessageOptions): Promise<Message> { }*/ for (const [, mention] of content.matchAll(USER_MENTION)) { - if (!mention_user_ids.includes(mention)) - mention_user_ids.push(mention); + if (!mention_user_ids.includes(mention)) mention_user_ids.push(mention); } await Promise.all( - Array.from(content.matchAll(ROLE_MENTION)).map( - async ([, mention]) => { - const role = await Role.findOneOrFail({ - where: { id: mention, guild_id: channel.guild_id }, - }); - if (role.mentionable || permission.has("MANAGE_ROLES")) { - mention_role_ids.push(mention); - } - }, - ), + Array.from(content.matchAll(ROLE_MENTION)).map(async ([, mention]) => { + const role = await Role.findOneOrFail({ + where: { id: mention, guild_id: channel.guild_id }, + }); + if (role.mentionable || permission.has("MANAGE_ROLES")) { + mention_role_ids.push(mention); + } + }) ); if (permission.has("MENTION_EVERYONE")) { - mention_everyone = - !!content.match(EVERYONE_MENTION) || - !!content.match(HERE_MENTION); + mention_everyone = !!content.match(EVERYONE_MENTION) || !!content.match(HERE_MENTION); } } @@ -222,8 +203,7 @@ export async function postHandleMessage(message: Message) { } // bit gross, but whatever! - const endpointPublic = - Config.get().cdn.endpointPublic || "http://127.0.0.1"; // lol + const endpointPublic = Config.get().cdn.endpointPublic || "http://127.0.0.1"; // lol const handler = url.hostname == new URL(endpointPublic).hostname ? EmbedHandlers["self"] @@ -262,10 +242,7 @@ export async function postHandleMessage(message: Message) { channel_id: message.channel_id, data, } as MessageUpdateEvent), - Message.update( - { id: message.id, channel_id: message.channel_id }, - { embeds: data.embeds }, - ), + Message.update({ id: message.id, channel_id: message.channel_id }, { embeds: data.embeds }), ...cachePromises, ]); } @@ -283,9 +260,7 @@ export async function sendMessage(opts: MessageOptions) { ]); // no await as it should catch error non-blockingly - postHandleMessage(message).catch((e) => - console.error("[Message] post-message handler failed", e), - ); + postHandleMessage(message).catch((e) => console.error("[Message] post-message handler failed", e)); return message; } diff --git a/src/api/util/handlers/Voice.ts b/src/api/util/handlers/Voice.ts index db06bd33..1407a180 100644 --- a/src/api/util/handlers/Voice.ts +++ b/src/api/util/handlers/Voice.ts @@ -21,9 +21,7 @@ import { distanceBetweenLocations, IPAnalysis } from "../utility/ipAddress"; export async function getVoiceRegions(ipAddress: string, vip: boolean) { const regions = Config.get().regions; - const availableRegions = regions.available.filter((ar) => - vip ? true : !ar.vip, - ); + const availableRegions = regions.available.filter((ar) => (vip ? true : !ar.vip)); let optimalId = regions.default; if (!regions.useDefaultAsOptimal) { @@ -33,10 +31,7 @@ export async function getVoiceRegions(ipAddress: string, vip: boolean) { for (const ar of availableRegions) { //TODO the endpoint location should be saved in the database if not already present to prevent IPAnalysis call - const dist = distanceBetweenLocations( - clientIpAnalysis, - ar.location || (await IPAnalysis(ar.endpoint)), - ); + const dist = distanceBetweenLocations(clientIpAnalysis, ar.location || (await IPAnalysis(ar.endpoint))); if (dist < min) { min = dist; diff --git a/src/api/util/handlers/route.ts b/src/api/util/handlers/route.ts index 5a0b48e6..9668b09b 100644 --- a/src/api/util/handlers/route.ts +++ b/src/api/util/handlers/route.ts @@ -84,24 +84,17 @@ export function route(opts: RouteOptions) { let validate: AnyValidateFunction | undefined; if (opts.requestBody) { validate = ajv.getSchema(opts.requestBody); - if (!validate) - throw new Error(`Body schema ${opts.requestBody} not found`); + if (!validate) throw new Error(`Body schema ${opts.requestBody} not found`); } return async (req: Request, res: Response, next: NextFunction) => { if (opts.permission) { const required = new Permissions(opts.permission); - req.permission = await getPermission( - req.user_id, - req.params.guild_id, - req.params.channel_id, - ); + req.permission = await getPermission(req.user_id, req.params.guild_id, req.params.channel_id); // bitfield comparison: check if user lacks certain permission if (!req.permission.has(required)) { - throw DiscordApiErrors.MISSING_PERMISSIONS.withParams( - opts.permission as string, - ); + throw DiscordApiErrors.MISSING_PERMISSIONS.withParams(opts.permission as string); } } @@ -110,25 +103,20 @@ export function route(opts: RouteOptions) { req.rights = await getRights(req.user_id); if (!req.rights || !req.rights.has(required)) { - throw SpacebarApiErrors.MISSING_RIGHTS.withParams( - opts.right as string, - ); + throw SpacebarApiErrors.MISSING_RIGHTS.withParams(opts.right as string); } } if (validate) { const valid = validate(normalizeBody(req.body)); if (!valid) { - const fields: Record< - string, - { code?: string; message: string } - > = {}; + const fields: Record<string, { code?: string; message: string }> = {}; validate.errors?.forEach( (x) => (fields[x.instancePath.slice(1)] = { code: x.keyword, message: x.message || "", - }), + }) ); throw FieldErrors(fields); } diff --git a/src/api/util/utility/Base64.ts b/src/api/util/utility/Base64.ts index c6d1257c..7426d22b 100644 --- a/src/api/util/utility/Base64.ts +++ b/src/api/util/utility/Base64.ts @@ -16,8 +16,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>. */ -const alphabet = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+"; +const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+"; // binary to string lookup table const b2s = alphabet.split(""); diff --git a/src/api/util/utility/EmbedHandlers.ts b/src/api/util/utility/EmbedHandlers.ts index 0f1e88a5..78e56986 100644 --- a/src/api/util/utility/EmbedHandlers.ts +++ b/src/api/util/utility/EmbedHandlers.ts @@ -27,8 +27,7 @@ export const DEFAULT_FETCH_OPTIONS: RequestInit = { redirect: "follow", follow: 1, headers: { - "user-agent": - "Mozilla/5.0 (compatible; Spacebar/1.0; +https://github.com/spacebarchat/server)", + "user-agent": "Mozilla/5.0 (compatible; Spacebar/1.0; +https://github.com/spacebarchat/server)", }, // size: 1024 * 1024 * 5, // grabbed from config later compress: true, @@ -38,7 +37,7 @@ export const DEFAULT_FETCH_OPTIONS: RequestInit = { const makeEmbedImage = ( url: string | undefined, width: number | undefined, - height: number | undefined, + height: number | undefined ): Required<EmbedImage> | undefined => { if (!url || !width || !height) return undefined; return { @@ -51,13 +50,8 @@ const makeEmbedImage = ( let hasWarnedAboutImagor = false; -export const getProxyUrl = ( - url: URL, - width: number, - height: number, -): string => { - const { resizeWidthMax, resizeHeightMax, imagorServerUrl } = - Config.get().cdn; +export const getProxyUrl = (url: URL, width: number, height: number): string => { + const { resizeWidthMax, resizeHeightMax, imagorServerUrl } = Config.get().cdn; const secret = Config.get().security.requestSignature; width = Math.min(width || 500, resizeWidthMax || width); height = Math.min(height || 500, resizeHeightMax || width); @@ -81,8 +75,8 @@ export const getProxyUrl = ( console.log( "[Embeds]", yellow( - "Imagor has not been set up correctly. https://docs.spacebar.chat/setup/server/configuration/imagor/", - ), + "Imagor has not been set up correctly. https://docs.spacebar.chat/setup/server/configuration/imagor/" + ) ); } @@ -157,11 +151,7 @@ const genericImageHandler = async (url: URL): Promise<Embed | null> => { const response = await doFetch(url); if (!response) return null; const metas = getMetaDescriptions(await response.text()); - image = makeEmbedImage( - metas.image || metas.image_fallback, - metas.width, - metas.height, - ); + image = makeEmbedImage(metas.image || metas.image_fallback, metas.width, metas.height); } if (!image) return null; @@ -182,8 +172,7 @@ export const EmbedHandlers: { ...DEFAULT_FETCH_OPTIONS, method: "HEAD", }); - if (type.headers.get("content-type")?.indexOf("image") !== -1) - return await genericImageHandler(url); + if (type.headers.get("content-type")?.indexOf("image") !== -1) return await genericImageHandler(url); const response = await doFetch(url); if (!response) return null; @@ -275,9 +264,7 @@ export const EmbedHandlers: { const text = json.data.text; const created_at = new Date(json.data.created_at); const metrics = json.data.public_metrics; - const media = json.includes.media?.filter( - (x: { type: string }) => x.type == "photo", - ); + const media = json.includes.media?.filter((x: { type: string }) => x.type == "photo"); const embed: Embed = { type: EmbedType.rich, @@ -286,11 +273,7 @@ export const EmbedHandlers: { author: { url: `https://twitter.com/${author.username}`, name: `${author.name} (@${author.username})`, - proxy_icon_url: getProxyUrl( - new URL(author.profile_image_url), - 400, - 400, - ), + proxy_icon_url: getProxyUrl(new URL(author.profile_image_url), 400, 400), icon_url: author.profile_image_url, }, timestamp: created_at, @@ -310,14 +293,11 @@ export const EmbedHandlers: { footer: { text: "Twitter", proxy_icon_url: getProxyUrl( - new URL( - "https://abs.twimg.com/icons/apple-touch-icon-192x192.png", - ), - 192, + new URL("https://abs.twimg.com/icons/apple-touch-icon-192x192.png"), 192, + 192 ), - icon_url: - "https://abs.twimg.com/icons/apple-touch-icon-192x192.png", + icon_url: "https://abs.twimg.com/icons/apple-touch-icon-192x192.png", }, // Discord doesn't send this? // provider: { @@ -331,11 +311,7 @@ export const EmbedHandlers: { width: media[0].width, height: media[0].height, url: media[0].url, - proxy_url: getProxyUrl( - new URL(media[0].url), - media[0].width, - media[0].height, - ), + proxy_url: getProxyUrl(new URL(media[0].url), media[0].width, media[0].height), }; media.shift(); } @@ -388,11 +364,7 @@ export const EmbedHandlers: { type: EmbedType.image, title: metas.title, description: metas.description, - image: makeEmbedImage( - metas.image || metas.image_fallback, - metas.width, - metas.height, - ), + image: makeEmbedImage(metas.image || metas.image_fallback, metas.width, metas.height), provider: { url: "https://pixiv.net", name: "Pixiv", @@ -404,17 +376,9 @@ export const EmbedHandlers: { const response = await doFetch(url); if (!response) return null; const metas = getMetaDescriptions(await response.text()); - const numReviews = metas.$("#review_summary_num_reviews").val() as - | string - | undefined; - const price = metas - .$(".game_purchase_price.price") - .data("price-final") as number | undefined; - const releaseDate = metas - .$(".release_date") - .find("div.date") - .text() - .trim(); + const numReviews = metas.$("#review_summary_num_reviews").val() as string | undefined; + const price = metas.$(".game_purchase_price.price").data("price-final") as number | undefined; + const releaseDate = metas.$(".release_date").find("div.date").text().trim(); const isReleased = new Date(releaseDate) < new Date(); const fields: Embed["fields"] = []; @@ -452,9 +416,7 @@ export const EmbedHandlers: { width: 460, height: 215, url: metas.image, - proxy_url: metas.image - ? getProxyUrl(new URL(metas.image), 460, 215) - : undefined, + proxy_url: metas.image ? getProxyUrl(new URL(metas.image), 460, 215) : undefined, }, provider: { url: "https://store.steampowered.com", @@ -485,19 +447,11 @@ export const EmbedHandlers: { const metas = getMetaDescriptions(await response.text()); return { - video: makeEmbedImage( - metas.youtube_embed, - metas.width, - metas.height, - ), + video: makeEmbedImage(metas.youtube_embed, metas.width, metas.height), url: url.href, type: metas.youtube_embed ? EmbedType.video : EmbedType.link, title: metas.title, - thumbnail: makeEmbedImage( - metas.image || metas.image_fallback, - metas.width, - metas.height, - ), + thumbnail: makeEmbedImage(metas.image || metas.image_fallback, metas.width, metas.height), provider: { url: "https://www.youtube.com", name: "YouTube", diff --git a/src/api/util/utility/RandomInviteID.ts b/src/api/util/utility/RandomInviteID.ts index 926750d3..f3b9197b 100644 --- a/src/api/util/utility/RandomInviteID.ts +++ b/src/api/util/utility/RandomInviteID.ts @@ -24,8 +24,7 @@ import crypto from "crypto"; export function random(length = 6) { // Declare all characters - const chars = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; // Pick characers randomly let str = ""; @@ -38,8 +37,7 @@ export function random(length = 6) { export function snowflakeBasedInvite() { // Declare all characters - const chars = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; const base = BigInt(chars.length); let snowflake = Snowflake.generateWorkerProcess(); diff --git a/src/api/util/utility/String.ts b/src/api/util/utility/String.ts index eef69e39..e531b447 100644 --- a/src/api/util/utility/String.ts +++ b/src/api/util/utility/String.ts @@ -20,13 +20,7 @@ import { Request } from "express"; import { ntob } from "./Base64"; import { FieldErrors } from "@spacebar/util"; -export function checkLength( - str: string, - min: number, - max: number, - key: string, - req: Request, -) { +export function checkLength(str: string, min: number, max: number, key: string, req: Request) { if (str.length < min || str.length > max) { throw FieldErrors({ [key]: { diff --git a/src/api/util/utility/captcha.ts b/src/api/util/utility/captcha.ts index db1b7957..9326eeb8 100644 --- a/src/api/util/utility/captcha.ts +++ b/src/api/util/utility/captcha.ts @@ -49,7 +49,7 @@ export async function verifyCaptcha(response: string, ip?: string) { if (!service || !secret || !sitekey) throw new Error( - "CAPTCHA is not configured correctly. https://docs.spacebar.chat/setup/server/security/captcha/", + "CAPTCHA is not configured correctly. https://docs.spacebar.chat/setup/server/security/captcha/" ); const res = await fetch(verifyEndpoints[service], { diff --git a/src/api/util/utility/ipAddress.ts b/src/api/util/utility/ipAddress.ts index c51daf6c..731812d7 100644 --- a/src/api/util/utility/ipAddress.ts +++ b/src/api/util/utility/ipAddress.ts @@ -83,9 +83,7 @@ export async function IPAnalysis(ip: string): Promise<typeof exampleData> { const { ipdataApiKey } = Config.get().security; if (!ipdataApiKey) return { ...exampleData, ip }; - return ( - await fetch(`https://api.ipdata.co/${ip}?api-key=${ipdataApiKey}`) - ).json(); + return (await fetch(`https://api.ipdata.co/${ip}?api-key=${ipdataApiKey}`)).json(); } export function isProxy(data: typeof exampleData) { @@ -102,37 +100,20 @@ export function getIpAdress(req: Request): string { return ( // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore - req.headers[Config.get().security.forwardedFor] || - req.socket.remoteAddress + req.headers[Config.get().security.forwardedFor] || req.socket.remoteAddress ); } type Location = { latitude: number; longitude: number }; -export function distanceBetweenLocations( - loc1: Location, - loc2: Location, -): number { - return distanceBetweenCoords( - loc1.latitude, - loc1.longitude, - loc2.latitude, - loc2.longitude, - ); +export function distanceBetweenLocations(loc1: Location, loc2: Location): number { + return distanceBetweenCoords(loc1.latitude, loc1.longitude, loc2.latitude, loc2.longitude); } //Haversine function -function distanceBetweenCoords( - lat1: number, - lon1: number, - lat2: number, - lon2: number, -) { +function distanceBetweenCoords(lat1: number, lon1: number, lat2: number, lon2: number) { const p = 0.017453292519943295; // Math.PI / 180 const c = Math.cos; - const a = - 0.5 - - c((lat2 - lat1) * p) / 2 + - (c(lat1 * p) * c(lat2 * p) * (1 - c((lon2 - lon1) * p))) / 2; + const a = 0.5 - c((lat2 - lat1) * p) / 2 + (c(lat1 * p) * c(lat2 * p) * (1 - c((lon2 - lon1) * p))) / 2; return 12742 * Math.asin(Math.sqrt(a)); // 2 * R; R = 6371 km } diff --git a/src/api/util/utility/passwordStrength.ts b/src/api/util/utility/passwordStrength.ts index fd627fbf..2f3e8bb1 100644 --- a/src/api/util/utility/passwordStrength.ts +++ b/src/api/util/utility/passwordStrength.ts @@ -36,8 +36,7 @@ const reSYMBOLS = /[A-Z,a-z,0-9]/g; * Returns: 0 > pw > 1 */ export function checkPassword(password: string): number { - const { minLength, minNumbers, minUpperCase, minSymbols } = - Config.get().register.password; + const { minLength, minNumbers, minUpperCase, minSymbols } = Config.get().register.password; let strength = 0; // checks for total password len @@ -61,10 +60,7 @@ export function checkPassword(password: string): number { } // checks if password only consists of numbers or only consists of chars - if ( - password.length == password.count(reNUMBER) || - password.length === password.count(reUPPERCASELETTER) - ) { + if (password.length == password.count(reNUMBER) || password.length === password.count(reUPPERCASELETTER)) { strength = 0; } @@ -77,8 +73,6 @@ export function checkPassword(password: string): number { const 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); + strength += entropies.reduceRight((a: number, x: number) => a - x * Math.log2(x)) / Math.log2(password.length); return strength; } |