diff --git a/server/package.json b/server/package.json index aca74e8..55b329d 100644 --- a/server/package.json +++ b/server/package.json @@ -20,6 +20,7 @@ "file-type": "^19.1.1", "fluent-ffmpeg": "^2.1.3", "html-entities": "^2.5.2", + "ip-address": "^9.0.5", "mysql2": "^3.10.2", "sharp": "^0.33.4", "toml": "^3.0.0", diff --git a/server/src/database.ts b/server/src/database.ts index 355fdcd..f4944d8 100644 --- a/server/src/database.ts +++ b/server/src/database.ts @@ -1,5 +1,7 @@ +import { isIP } from 'net'; import { MySQLConfig } from './config.js'; import * as mysql from 'mysql2/promise'; +import { Address6 } from 'ip-address'; export class Database { private config: MySQLConfig; @@ -24,15 +26,46 @@ export class Database { } async banUser(ip: string, username: string) { + let _ip = this.formatIP(ip); let conn = await this.db.getConnection(); - await conn.execute('INSERT INTO bans (ip, username) VALUES (?, ?)', [ip, username]); + await conn.execute('INSERT INTO bans (ip, username) VALUES (?, ?)', [_ip, username]); conn.release(); } + private formatIP(ip: string) { + switch (isIP(ip)) { + case 4: + // If IPv4, just return as-is + return ip; + case 6: { + // If IPv6, return the /64 equivalent + let addr = new Address6(ip); + addr.subnetMask = 64; + return addr.startAddress().canonicalForm() + '/64'; + } + case 0: + default: + // Invalid IP + throw new Error('Invalid IP address (what the hell did you even do???)'); + } + } + async isUserBanned(ip: string): Promise { + let _ip = this.formatIP(ip); let conn = await this.db.getConnection(); - let res = (await conn.query('SELECT COUNT(ip) AS cnt FROM bans WHERE ip = ?', [ip])) as mysql.RowDataPacket; + + let isBanned = false; + + let res = (await conn.query('SELECT COUNT(ip) AS cnt FROM bans WHERE ip = ?', [_ip])) as mysql.RowDataPacket; + isBanned = res[0][0]['cnt'] !== 0; + + // compat with old schema + if (!isBanned && _ip !== ip) { + let res = (await conn.query('SELECT COUNT(ip) AS cnt FROM bans WHERE ip = ?', [ip])) as mysql.RowDataPacket; + isBanned = res[0][0]['cnt'] !== 0; + } + conn.release(); - return res[0][0]['cnt'] !== 0; + return isBanned; } } diff --git a/yarn.lock b/yarn.lock index 84f9c3d..f363c4a 100644 --- a/yarn.lock +++ b/yarn.lock @@ -511,6 +511,7 @@ __metadata: file-type: "npm:^19.1.1" fluent-ffmpeg: "npm:^2.1.3" html-entities: "npm:^2.5.2" + ip-address: "npm:^9.0.5" mysql2: "npm:^3.10.2" sharp: "npm:^0.33.4" toml: "npm:^3.0.0"