diff --git a/src/api/Server.ts b/src/api/Server.ts index 62a5177..0969e5e 100644 --- a/src/api/Server.ts +++ b/src/api/Server.ts @@ -89,7 +89,7 @@ await initRateLimits(api); await initTranslation(api); - this.routes = await registerRoutes(this, path.join(__dirname, "routes", "/")); + this.routes = (await registerRoutes(this, path.join(__dirname, "routes", "/"))).filter((r) => !!r); // 404 is not an error in express, so this should not be an error middleware // this is a fine place to put the 404 handler because its after we register the routes @@ -127,14 +127,14 @@ }); // current well-known location - app.get("/.well-known/spacebar", (req,res)=>{ + app.get("/.well-known/spacebar", (req, res) => { res.json({ - api: Config.get().api.endpointPublic + api: Config.get().api.endpointPublic, }); }); // new well-known location - app.get("/.well-known/spacebar/client", (req,res)=>{ + app.get("/.well-known/spacebar/client", (req, res) => { let erlpackSupported = false; try { require("@yukikaze-bot/erlpack"); @@ -148,20 +148,23 @@ baseUrl: Config.get().api.endpointPublic?.split("/api")[0] || "", // TODO: migrate database values to not include /api/v9 apiVersions: { default: Config.get().api.defaultVersion, - active: Config.get().api.activeVersions - } + active: Config.get().api.activeVersions, + }, }, cdn: { - baseUrl: Config.get().cdn.endpointPublic + baseUrl: Config.get().cdn.endpointPublic, }, gateway: { baseUrl: Config.get().gateway.endpointPublic, encoding: [...(erlpackSupported ? ["etf"] : []), "json"], compression: ["zstd-stream", "zlib-stream", null], }, - admin: Config.get().admin.endpointPublic === null ? undefined : { - baseUrl: Config.get().admin.endpointPublic - } + admin: + Config.get().admin.endpointPublic === null + ? undefined + : { + baseUrl: Config.get().admin.endpointPublic, + }, }); }); diff --git a/src/bundle/stats.ts b/src/bundle/stats.ts index 1af7144..dec5e2e 100644 --- a/src/bundle/stats.ts +++ b/src/bundle/stats.ts @@ -32,25 +32,18 @@ console.log(`[System] ${os.platform()} ${os.release()} ${os.arch()}`); if (os.platform() == "linux") { try { - const osReleaseLines = readFileSync( - "/etc/os-release", - "utf8", - ).split("\n"); + const osReleaseLines = readFileSync("/etc/os-release", "utf8").split("\n"); // eslint-disable-next-line @typescript-eslint/ban-ts-comment //@ts-ignore - const osRelease: any = {}; + const osRelease: { [key: string]: string } = {}; for (const line of osReleaseLines) { if (!line) continue; const [key, value] = line.match(/(.*?)="?([^"]*)"?/)!.slice(1); osRelease[key] = value; } - console.log( - `[System]\x1b[${osRelease.ANSI_COLOR}m ${osRelease.NAME ?? "Unknown"} ${osRelease.VERSION ?? "Unknown"} (${osRelease.BUILD_ID ?? "No build ID"})\x1b[0m`, - ); + console.log(`[System]\x1b[${osRelease.ANSI_COLOR}m ${osRelease.NAME ?? "Unknown"} ${osRelease.VERSION ?? "Unknown"} (${osRelease.BUILD_ID ?? "No build ID"})\x1b[0m`); } catch (e) { - console.log( - "[System] Unknown Linux distribution (missing /etc/os-release)", - ); + console.log("[System] Unknown Linux distribution (missing /etc/os-release)"); console.log(e); } } diff --git a/src/cdn/Server.ts b/src/cdn/Server.ts index f73d924..d92ec6c 100644 --- a/src/cdn/Server.ts +++ b/src/cdn/Server.ts @@ -17,12 +17,7 @@ */ import { Server, ServerOptions } from "lambert-server"; -import { - Attachment, - Config, - initDatabase, - registerRoutes, -} from "@spacebar/util"; +import { Attachment, Config, initDatabase, registerRoutes } from "@spacebar/util"; import { CORS, BodyParser } from "@spacebar/api"; import path from "path"; import avatarsRoute from "./routes/avatars"; @@ -50,13 +45,8 @@ this.app.use( morgan("combined", { skip: (req, res) => { - let skip = !( - process.env["LOG_REQUESTS"]?.includes( - res.statusCode.toString(), - ) ?? false - ); - if (process.env["LOG_REQUESTS"]?.charAt(0) == "-") - skip = !skip; + let skip = !(process.env["LOG_REQUESTS"]?.includes(res.statusCode.toString()) ?? false); + if (process.env["LOG_REQUESTS"]?.charAt(0) == "-") skip = !skip; return skip; }, }), @@ -74,52 +64,46 @@ await registerRoutes(this, path.join(__dirname, "routes/")); this.app.use("/icons/", avatarsRoute); - this.log("verbose", "[Server] Route /icons registered"); + console.log("[Server] Route /icons registered"); this.app.use("/role-icons/", iconsRoute); - this.log("verbose", "[Server] Route /role-icons registered"); + console.log("[Server] Route /role-icons registered"); this.app.use("/emojis/", avatarsRoute); - this.log("verbose", "[Server] Route /emojis registered"); + console.log("[Server] Route /emojis registered"); this.app.use("/stickers/", avatarsRoute); - this.log("verbose", "[Server] Route /stickers registered"); + console.log("[Server] Route /stickers registered"); this.app.use("/banners/", avatarsRoute); - this.log("verbose", "[Server] Route /banners registered"); + console.log("[Server] Route /banners registered"); this.app.use("/splashes/", avatarsRoute); - this.log("verbose", "[Server] Route /splashes registered"); + console.log("[Server] Route /splashes registered"); this.app.use("/discovery-splashes/", avatarsRoute); - this.log("verbose", "[Server] Route /discovery-splashes registered"); + console.log("[Server] Route /discovery-splashes registered"); this.app.use("/app-icons/", avatarsRoute); - this.log("verbose", "[Server] Route /app-icons registered"); + console.log("[Server] Route /app-icons registered"); this.app.use("/app-assets/", avatarsRoute); - this.log("verbose", "[Server] Route /app-assets registered"); + console.log("[Server] Route /app-assets registered"); this.app.use("/discover-splashes/", avatarsRoute); - this.log("verbose", "[Server] Route /discover-splashes registered"); + console.log("[Server] Route /discover-splashes registered"); this.app.use("/team-icons/", avatarsRoute); - this.log("verbose", "[Server] Route /team-icons registered"); + console.log("[Server] Route /team-icons registered"); this.app.use("/channel-icons/", avatarsRoute); - this.log("verbose", "[Server] Route /channel-icons registered"); + console.log("[Server] Route /channel-icons registered"); - this.app.use( - "/guilds/:guild_id/users/:user_id/avatars", - guildProfilesRoute, - ); - this.log("verbose", "[Server] Route /guilds/avatars registered"); + this.app.use("/guilds/:guild_id/users/:user_id/avatars", guildProfilesRoute); + console.log("[Server] Route /guilds/avatars registered"); - this.app.use( - "/guilds/:guild_id/users/:user_id/banners", - guildProfilesRoute, - ); - this.log("verbose", "[Server] Route /guilds/banners registered"); + this.app.use("/guilds/:guild_id/users/:user_id/banners", guildProfilesRoute); + console.log("[Server] Route /guilds/banners registered"); return super.start(); } @@ -129,24 +113,21 @@ } async cleanupSignaturesInDb() { - this.log("verbose", "[CDN] Cleaning up signatures in database"); + console.log("[CDN] Cleaning up signatures in database"); const attachmentsToFix = await Attachment.find({ where: { url: Like("%?ex=%") }, }); if (attachmentsToFix.length === 0) { - this.log("verbose", "[CDN] No attachments to fix"); + console.log("[CDN] No attachments to fix"); return; } - this.log( - "verbose", - `[CDN] Found ${attachmentsToFix.length} attachments to fix`, - ); + console.log("[CDN] Found", attachmentsToFix.length, " attachments to fix"); for (const attachment of attachmentsToFix) { attachment.url = attachment.url.split("?ex=")[0]; attachment.proxy_url = attachment.proxy_url?.split("?ex=")[0]; await attachment.save(); - this.log("verbose", `[CDN] Fixed attachment ${attachment.id}`); + console.log(`[CDN] Fixed attachment ${attachment.id}`); } } } diff --git a/src/schemas/api/guilds/Automod.ts b/src/schemas/api/guilds/Automod.ts index 9439869..473d988 100644 --- a/src/schemas/api/guilds/Automod.ts +++ b/src/schemas/api/guilds/Automod.ts @@ -86,6 +86,9 @@ duration_seconds: number; }; }; + +// TODO +// eslint-disable-next-line export interface AutomodRuleActionMetadata { } \ No newline at end of file diff --git a/src/schemas/uncategorised/AutomodRuleSchema.ts b/src/schemas/uncategorised/AutomodRuleSchema.ts index 55cf202..bc75108 100644 --- a/src/schemas/uncategorised/AutomodRuleSchema.ts +++ b/src/schemas/uncategorised/AutomodRuleSchema.ts @@ -21,7 +21,8 @@ mention_raid_protection_enabled: boolean; } -export interface AutomodSuspectedSpamRuleSchema {} +// export interface AutomodSuspectedSpamRuleSchema {} +export type AutomodSuspectedSpamRuleSchema = Record; // hack to represent an empty object export interface AutomodCommonlyFlaggedWordsRuleSchema { allow_list: [string]; diff --git a/src/util/entities/UserSettingsProtos.ts b/src/util/entities/UserSettingsProtos.ts index e68fca5..7ed392c 100644 --- a/src/util/entities/UserSettingsProtos.ts +++ b/src/util/entities/UserSettingsProtos.ts @@ -53,7 +53,7 @@ // @Column({nullable: true, type: "simple-json"}) // testSettings: {}; - bigintReplacer(_key: string, value: any): any { + bigintReplacer(_key: string, value: unknown): unknown { if (typeof value === "bigint") { return (value as bigint).toString(); } else if (value instanceof Uint8Array) { @@ -68,7 +68,7 @@ } } - bigintReviver(_key: string, value: any): any { + bigintReviver(_key: string, value: unknown): unknown { if (typeof value === "string" && /^\d+n$/.test(value)) { return BigInt((value as string).slice(0, -1)); } else if ( @@ -78,7 +78,7 @@ ) { if (value.__type === "Uint8Array" && "data" in value) { return new Uint8Array( - value.data + (value.data as string) .match(/.{1,2}/g)! .map((byte: string) => parseInt(byte, 16)), ); diff --git a/src/util/util/Config.ts b/src/util/util/Config.ts index 496f21c..38bd3bc 100644 --- a/src/util/util/Config.ts +++ b/src/util/util/Config.ts @@ -21,6 +21,7 @@ import { OrmUtils } from ".."; import { ConfigValue } from "../config"; import { ConfigEntity } from "../entities/Config"; +import { JsonValue } from "@protobuf-ts/runtime"; // TODO: yaml instead of json const overridePath = process.env.CONFIG_PATH ?? ""; @@ -174,10 +175,10 @@ function validateFinalConfig(config: ConfigValue) { let hasErrors = false; - function assertConfig(path: string, condition: (val: any) => boolean, recommendedValue: string) { + function assertConfig(path: string, condition: (val: JsonValue) => boolean, recommendedValue: string) { // _ to separate keys const keys = path.split("_"); - let obj: any = config; + let obj: never = config as never; for (const key of keys) { if (obj == null || !(key in obj)) { diff --git a/src/util/util/Token.ts b/src/util/util/Token.ts index 91d475d..cc19d85 100644 --- a/src/util/util/Token.ts +++ b/src/util/util/Token.ts @@ -52,7 +52,7 @@ console.log(`[AUTH] ${text}`); } -function rejectAndLog(rejectFunction: (reason?: any) => void, reason: any) { +function rejectAndLog(rejectFunction: (reason?: string) => void, reason: string) { console.error(reason); rejectFunction(reason); } diff --git a/src/util/util/lambert-server/Server.ts b/src/util/util/lambert-server/Server.ts index 6f09087..c848ba7 100644 --- a/src/util/util/lambert-server/Server.ts +++ b/src/util/util/lambert-server/Server.ts @@ -9,6 +9,7 @@ import chalk from "chalk"; declare global { + // eslint-disable-next-line @typescript-eslint/no-namespace namespace Express { interface Request { server: Server; @@ -21,7 +22,7 @@ host: string; production: boolean; serverInitLogging: boolean; - errorHandler?: { (err: Error, req: Request, res: Response, next: NextFunction): any }; + // errorHandler?: { (err: Error, req: Request, res: Response, next: NextFunction): any }; jsonBody: boolean; server: http.Server; app: Application; @@ -48,7 +49,7 @@ if (!opts.host) opts.host = "0.0.0.0"; if (opts.production == null) opts.production = false; if (opts.serverInitLogging == null) opts.serverInitLogging = true; - if (opts.errorHandler == null) opts.errorHandler = this.errorHandler; + // if (opts.errorHandler == null) opts.errorHandler = this.errorHandler; if (opts.jsonBody == null) opts.jsonBody = true; if (opts.server) this.http = opts.server; @@ -98,7 +99,7 @@ await new Promise((res) => { this.http = server.listen(this.options.port, () => res()); }); - if (this.options.serverInitLogging) this.log("info", `[Server] started on ${this.options.host}:${this.options.port}`); + if (this.options.serverInitLogging) console.log(`[Server] started on ${this.options.host}:${this.options.port}`); } } @@ -109,39 +110,12 @@ }); if (this.options.jsonBody) this.app.use(bodyParser.json()); const result = await traverseDirectory({ dirname: root, recursive: true }, this.registerRoute.bind(this, root)); - if (this.options.errorHandler) this.app.use(this.options.errorHandler); + // if (this.options.errorHandler) this.app.use(this.options.errorHandler); // if (this.options.production) this.secureExpress(); return result; } - log(l: "info" | "error" | "warn" | "verbose", ...args: any[]) { - // @ts-ignore - if (!console[l]) l = "verbose"; - - const level = l === "verbose" ? "log" : l; - - var color: "red" | "yellow" | "blue" | "reset"; - - switch (level) { - case "error": - color = "red"; - break; - case "warn": - color = "yellow"; - break; - case "info": - color = "blue"; - case "log": - default: - color = "reset"; - } - - if (this.options.production && l === "verbose") return; - - console[level](chalk[color](`[${new Date().toTimeString().split(" ")[0]}]`), ...args); - } - - registerRoute(root: string, file: string): any { + registerRoute(root: string, file: string): Router | undefined { if (root.endsWith("/") || root.endsWith("\\")) root = root.slice(0, -1); // removes slash at the end of the root dir let path = file.replace(root, ""); // remove root from path and path = path.split(".").slice(0, -1).join("."); // trancate .js/.ts file extension of path @@ -155,10 +129,10 @@ if (router.default) router = router.default; if (!router || router?.prototype?.constructor?.name !== "router") throw `File doesn't export any default router`; - if (this.options.errorHandler) router.use(this.options.errorHandler); + // if (this.options.errorHandler) router.use(this.options.errorHandler); this.app.use(path, router); - if (this.options.serverInitLogging) this.log("verbose", `[Server] Route ${path} registered`); + if (this.options.serverInitLogging) console.log(`[Server] Route ${path} registered`); return router; } catch (error) { diff --git a/src/util/util/lambert-server/Utils.ts b/src/util/util/lambert-server/Utils.ts index 7b39d0a..23766fd 100644 --- a/src/util/util/lambert-server/Utils.ts +++ b/src/util/util/lambert-server/Utils.ts @@ -8,7 +8,7 @@ } const DEFAULT_EXCLUDE_DIR = /^\./; -const DEFAULT_FILTER = /^([^\.].*)(?( options: traverseDirectoryOptions, diff --git a/src/util/util/lambert-server/check.ts b/src/util/util/lambert-server/check.ts index bca65bf..5fe9d84 100644 --- a/src/util/util/lambert-server/check.ts +++ b/src/util/util/lambert-server/check.ts @@ -4,20 +4,10 @@ const OPTIONAL_PREFIX = "$"; const EMAIL_REGEX = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; -export function check(schema: any) { - return (req: Request, res: Response, next: NextFunction) => { - try { - const result = instanceOf(schema, req.body, { path: "body" }); - if (result === true) return next(); - throw result; - } catch (error) { - next(new HTTPError((error as any).toString(), 400)); - } - }; -} - export class Tuple { + // eslint-disable-next-line @typescript-eslint/no-explicit-any public types: any[]; + // eslint-disable-next-line @typescript-eslint/no-explicit-any constructor(...types: any[]) { this.types = types; } @@ -30,6 +20,7 @@ } } +// eslint-disable-next-line @typescript-eslint/no-explicit-any export function instanceOf(type: any, value: any, { path = "", optional = false }: { path?: string; optional?: boolean } = {}): boolean { if (!type) return true; // no type was specified