ban ipv6 by /64 range

This commit is contained in:
Elijah R 2024-08-14 00:50:22 -04:00
parent b78d596c9d
commit 6297d365e6
3 changed files with 38 additions and 3 deletions

View file

@ -20,6 +20,7 @@
"file-type": "^19.1.1", "file-type": "^19.1.1",
"fluent-ffmpeg": "^2.1.3", "fluent-ffmpeg": "^2.1.3",
"html-entities": "^2.5.2", "html-entities": "^2.5.2",
"ip-address": "^9.0.5",
"mysql2": "^3.10.2", "mysql2": "^3.10.2",
"sharp": "^0.33.4", "sharp": "^0.33.4",
"toml": "^3.0.0", "toml": "^3.0.0",

View file

@ -1,5 +1,7 @@
import { isIP } from 'net';
import { MySQLConfig } from './config.js'; import { MySQLConfig } from './config.js';
import * as mysql from 'mysql2/promise'; import * as mysql from 'mysql2/promise';
import { Address6 } from 'ip-address';
export class Database { export class Database {
private config: MySQLConfig; private config: MySQLConfig;
@ -24,15 +26,46 @@ export class Database {
} }
async banUser(ip: string, username: string) { async banUser(ip: string, username: string) {
let _ip = this.formatIP(ip);
let conn = await this.db.getConnection(); 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(); 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<boolean> { async isUserBanned(ip: string): Promise<boolean> {
let _ip = this.formatIP(ip);
let conn = await this.db.getConnection(); 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(); conn.release();
return res[0][0]['cnt'] !== 0; return isBanned;
} }
} }

View file

@ -511,6 +511,7 @@ __metadata:
file-type: "npm:^19.1.1" file-type: "npm:^19.1.1"
fluent-ffmpeg: "npm:^2.1.3" fluent-ffmpeg: "npm:^2.1.3"
html-entities: "npm:^2.5.2" html-entities: "npm:^2.5.2"
ip-address: "npm:^9.0.5"
mysql2: "npm:^3.10.2" mysql2: "npm:^3.10.2"
sharp: "npm:^0.33.4" sharp: "npm:^0.33.4"
toml: "npm:^3.0.0" toml: "npm:^3.0.0"