feat: SQLite RBAC, granular permissions, 100-VPS seeder, DM pagination

This commit is contained in:
khuongnguyen committed 2026-12-02 10:26:56 +07:00
1 parent 41d9e9e8eb
commit 4ccb35a44c
16 files changed
+1690 -327

No files matched your search

+255 -42
View File
@@ -1,81 +1,294 @@
import fs from "node:fs";
import path from "node:path";
import { VPS, vpsListSchema } from "../types/vps.js";
import { DatabaseSync } from "node:sqlite";
import { getDataConfig } from "../config/env.js";
import { VPS, vpsListSchema, vpsSchema } from "../types/vps.js";
export class VPSRepository {
private filePath: string;
private cache: VPS[] | null = null;
/**
* Storage-agnostic repository contract.
*/
export interface IVPSRepository {
getAll(): VPS[];
getById(id: string): VPS | undefined;
getByName(name: string): VPS | undefined;
close?(): void;
}
constructor(filePath?: string) {
this.filePath = filePath || process.env.VPS_DATA_PATH || path.resolve(process.cwd(), "data/vps.json");
interface VPSRow {
id: string;
name: string;
provider: string;
region: string;
environment: string;
cpu: number;
ramGB: number;
diskGB: number;
ip: string | null;
sshUser: string | null;
sshPort: number | null;
}
const CORE_SEED_RECORDS: readonly VPS[] = [
{
id: "vps-001",
name: "shop-prod-01",
provider: "Vultr",
region: "Singapore",
environment: "Production",
cpu: 4,
ramGB: 8,
diskGB: 160,
ip: "203.0.113.10",
sshUser: "deploy",
sshPort: 22,
},
{
id: "vps-002",
name: "staging-01",
provider: "DigitalOcean",
region: "Singapore",
environment: "Staging",
cpu: 2,
ramGB: 4,
diskGB: 80,
ip: "198.51.100.20",
sshUser: "ubuntu",
sshPort: 2222,
},
{
id: "vps-003",
name: "db-prod-01",
provider: "Vultr",
region: "Singapore",
environment: "Production",
cpu: 4,
ramGB: 16,
diskGB: 320,
ip: "192.0.2.30",
},
];
const PROVIDERS = ["Vultr", "DigitalOcean", "AWS", "Linode", "Hetzner"] as const;
const REGIONS = ["Singapore", "Tokyo", "Frankfurt", "US-East"] as const;
const ENVIRONMENTS = ["Production", "Staging", "Development"] as const;
const DOC_PREFIXES = ["203.0.113", "198.51.100", "192.0.2"] as const;
const CPU_TIERS = [2, 4, 8] as const;
function buildGeneratedSeedRecords(totalTarget = 100): VPS[] {
const records: VPS[] = [...CORE_SEED_RECORDS];
for (let i = records.length + 1; i <= totalTarget; i++) {
const num = String(i).padStart(3, "0");
const env = ENVIRONMENTS[(i - 1) % ENVIRONMENTS.length];
const envShort = env === "Production" ? "prod" : env === "Staging" ? "stg" : "dev";
const provider = PROVIDERS[(i - 1) % PROVIDERS.length];
const region = REGIONS[(i - 1) % REGIONS.length];
const cpu = CPU_TIERS[(i - 1) % CPU_TIERS.length];
const ramGB = cpu * 2;
const diskGB = cpu * 40;
const ipPrefix = DOC_PREFIXES[(i - 1) % DOC_PREFIXES.length];
const lastOctet = ((i * 7) % 240) + 10;
records.push({
id: `vps-${num}`,
name: `app-${envShort}-${num}`,
provider,
region,
environment: env,
cpu,
ramGB,
diskGB,
ip: `${ipPrefix}.${lastOctet}`,
sshUser: env === "Production" ? "deploy" : "ubuntu",
sshPort: env === "Staging" ? 2222 : 22,
});
}
return records;
}
export const SEED_VPS_RECORDS: readonly VPS[] = buildGeneratedSeedRecords(100);
const SELECT_COLUMNS = `
id,
name,
provider,
region,
environment,
cpu,
ram_gb AS ramGB,
disk_gb AS diskGB,
ip,
ssh_user AS sshUser,
ssh_port AS sshPort
`;
function mapRowToVPS(row: VPSRow): VPS {
const candidate = {
id: row.id,
name: row.name,
provider: row.provider,
region: row.region,
environment: row.environment,
cpu: row.cpu,
ramGB: row.ramGB,
diskGB: row.diskGB,
ip: row.ip ?? undefined,
sshUser: row.sshUser ?? undefined,
sshPort: row.sshPort ?? undefined,
};
return vpsSchema.parse(candidate);
}
export class VPSRepository implements IVPSRepository {
private dbPath: string;
private db: DatabaseSync | null = null;
constructor(dbPath?: string) {
const configuredPath = dbPath || getDataConfig().VPS_DB_PATH;
this.dbPath =
configuredPath === ":memory:"
? ":memory:"
: path.resolve(process.cwd(), configuredPath);
}
/**
* Loads and validates VPS records from the JSON data file.
* Opens the SQLite database connection and ensures the `vps` table exists.
*/
public load(): VPS[] {
const resolvedPath = path.resolve(this.filePath);
if (!fs.existsSync(resolvedPath)) {
throw new Error(`Inventory data file not found at path: ${resolvedPath}`);
public init(): void {
if (this.db) {
return;
}
let rawData: string;
try {
rawData = fs.readFileSync(resolvedPath, "utf-8");
if (this.dbPath !== ":memory:") {
fs.mkdirSync(path.dirname(this.dbPath), { recursive: true });
}
this.db = new DatabaseSync(this.dbPath);
this.db.exec(`
PRAGMA foreign_keys = ON;
${this.dbPath !== ":memory:" ? "PRAGMA journal_mode = WAL;" : ""}
CREATE TABLE IF NOT EXISTS vps (
id TEXT PRIMARY KEY,
name TEXT NOT NULL UNIQUE COLLATE NOCASE,
provider TEXT NOT NULL,
region TEXT NOT NULL,
environment TEXT NOT NULL CHECK (environment IN ('Production', 'Staging', 'Development')),
cpu INTEGER NOT NULL CHECK (cpu > 0),
ram_gb REAL NOT NULL CHECK (ram_gb > 0),
disk_gb REAL NOT NULL CHECK (disk_gb > 0),
ip TEXT,
ssh_user TEXT,
ssh_port INTEGER CHECK (ssh_port IS NULL OR (ssh_port >= 1 AND ssh_port <= 65535))
);
`);
} catch (err) {
throw new Error(`Failed to read inventory data file: ${(err as Error).message}`);
throw new Error(`Failed to initialize SQLite database: ${(err as Error).message}`);
}
}
let parsed: unknown;
try {
parsed = JSON.parse(rawData);
} catch (err) {
throw new Error(`Corrupted JSON inventory data file: ${(err as Error).message}`);
private getDb(): DatabaseSync {
if (!this.db) {
this.init();
}
const validation = vpsListSchema.safeParse(parsed);
if (!validation.success) {
const issueDetails = validation.error.issues
.map((issue) => `[${issue.path.join(".")}]: ${issue.message}`)
.join("; ");
throw new Error(`Invalid VPS inventory data structure: ${issueDetails}`);
}
this.cache = validation.data;
return this.cache;
return this.db!;
}
/**
* Returns all VPS records.
* Inserts default workshop seed records if the `vps` table is currently empty.
* Returns the number of inserted records.
*/
public seedIfEmpty(records: readonly VPS[] = SEED_VPS_RECORDS): number {
const db = this.getDb();
const countRow = db.prepare("SELECT COUNT(*) AS count FROM vps").get() as { count: number };
if (countRow.count > 0) {
return 0;
}
const insert = db.prepare(`
INSERT INTO vps (id, name, provider, region, environment, cpu, ram_gb, disk_gb, ip, ssh_user, ssh_port)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`);
for (const vps of records) {
insert.run(
vps.id,
vps.name,
vps.provider,
vps.region,
vps.environment,
vps.cpu,
vps.ramGB,
vps.diskGB,
vps.ip ?? null,
vps.sshUser ?? null,
vps.sshPort ?? null
);
}
return records.length;
}
/**
* Returns all VPS records from SQLite.
*/
public getAll(): VPS[] {
if (!this.cache) {
return this.load();
try {
const db = this.getDb();
const rows = db.prepare(`SELECT ${SELECT_COLUMNS} FROM vps ORDER BY rowid ASC`).all() as unknown as VPSRow[];
const mapped = rows.map(mapRowToVPS);
return vpsListSchema.parse(mapped);
} catch (err) {
throw new Error(`Failed to query VPS records: ${(err as Error).message}`);
}
return this.cache;
}
/**
* Finds a VPS by exact ID.
*/
public getById(id: string): VPS | undefined {
return this.getAll().find((vps) => vps.id === id);
try {
const db = this.getDb();
const row = db
.prepare(`SELECT ${SELECT_COLUMNS} FROM vps WHERE id = ? LIMIT 1`)
.get(id) as unknown as VPSRow | undefined;
return row ? mapRowToVPS(row) : undefined;
} catch (err) {
throw new Error(`Failed to query VPS by ID: ${(err as Error).message}`);
}
}
/**
* Finds a VPS by name (case-insensitive).
*/
public getByName(name: string): VPS | undefined {
const trimmed = name.trim().toLowerCase();
return this.getAll().find((vps) => vps.name.toLowerCase() === trimmed);
const trimmed = name.trim();
if (!trimmed) {
return undefined;
}
try {
const db = this.getDb();
const row = db
.prepare(`SELECT ${SELECT_COLUMNS} FROM vps WHERE LOWER(name) = LOWER(?) LIMIT 1`)
.get(trimmed) as unknown as VPSRow | undefined;
return row ? mapRowToVPS(row) : undefined;
} catch (err) {
throw new Error(`Failed to query VPS by name: ${(err as Error).message}`);
}
}
/**
* Force reloads the data from disk.
* Closes the SQLite database connection.
*/
public reload(): VPS[] {
this.cache = null;
return this.load();
public close(): void {
if (this.db) {
this.db.close();
this.db = null;
}
}
}