Signed-off-by: Matheus Sampaio Queiroga <srherobrine20@gmail.com>
80 lines
2.1 KiB
TypeScript
80 lines
2.1 KiB
TypeScript
import * as net_e from "@sirherobrine23/extends/src/net.js";
|
|
import { DataTypes, InferAttributes, InferCreationAttributes, Model } from "sequelize";
|
|
import * as wg from "wireguard-tools.js";
|
|
import { dbConection } from "./db.js";
|
|
import { randomBytes, randomInt } from "crypto";
|
|
|
|
export const modelName = "wg_servers";
|
|
export type Server = InferAttributes<wgServer, { omit: never; }>
|
|
export class wgServer extends Model<InferAttributes<wgServer>, InferCreationAttributes<wgServer>> {
|
|
declare id?: number;
|
|
name: string;
|
|
privateKey: string;
|
|
portListen: number;
|
|
IPv4: string;
|
|
IPv6: string;
|
|
uploadStats: number;
|
|
downloadStats: number;
|
|
};
|
|
|
|
wgServer.init({
|
|
id: {
|
|
type: DataTypes.INTEGER,
|
|
autoIncrement: true,
|
|
primaryKey: true
|
|
},
|
|
name: {
|
|
type: DataTypes.STRING,
|
|
allowNull: false,
|
|
unique: true,
|
|
},
|
|
privateKey: {
|
|
type: DataTypes.CHAR(44),
|
|
allowNull: false,
|
|
unique: true
|
|
},
|
|
portListen: {
|
|
type: DataTypes.INTEGER,
|
|
unique: true,
|
|
allowNull: false,
|
|
defaultValue: 0,
|
|
set(val) {
|
|
if (val === 0) val = randomInt(2024, 65525);
|
|
this.setDataValue("portListen", Number(val));
|
|
},
|
|
},
|
|
uploadStats: {
|
|
type: DataTypes.INTEGER,
|
|
allowNull: false,
|
|
defaultValue: 0,
|
|
},
|
|
downloadStats: {
|
|
type: DataTypes.INTEGER,
|
|
allowNull: false,
|
|
defaultValue: 0,
|
|
},
|
|
IPv4: {
|
|
type: DataTypes.CHAR,
|
|
unique: true,
|
|
},
|
|
IPv6: {
|
|
type: DataTypes.CHAR,
|
|
unique: true,
|
|
},
|
|
}, { sequelize: dbConection, modelName });
|
|
|
|
wgServer.sync().then(async () => {
|
|
if (await wgServer.count() === 0) await createInterface();
|
|
});
|
|
|
|
export async function createInterface() {
|
|
const wgInt = new wgServer;
|
|
wgInt.name = randomBytes(4).toString("hex");
|
|
wgInt.privateKey = await wg.key.privateKey();
|
|
wgInt.IPv4 = await net_e.randomIp("10.10.0.0/16");
|
|
wgInt.IPv6 = net_e.toString(net_e.toInt(wgInt.IPv4), true);
|
|
do { wgInt.portListen = randomInt(2024, 65525); } while (await wgServer.findOne({ where: { portListen: wgInt.portListen } }));
|
|
await wgInt.validate();
|
|
await wgInt.save();
|
|
return wgInt.toJSON();
|
|
} |