Files

329 lines
12 KiB
TypeScript

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2026 Bryan Joshua Pedini
import fs from 'node:fs';
import path from 'node:path';
import mysql from 'mysql2/promise';
import { GROUP_NAMES, GROUPS, MYSQL_HOST, requireEnv, type GroupConfig } from './env';
import { HarnessError } from './errors';
export interface RecordRow {
id: number;
zone: string;
name: string;
ttl: number | null;
content: string | null;
record_type: string;
}
export interface UserRow {
id: number;
username: string;
role: string;
password_hash: string;
created_at: string;
updated_at: string;
last_login_at: string | null;
deleted_at: string | null;
}
export interface AuditRow {
id: number;
time: string;
user_id: number | null;
actor: string;
origin: string;
operation: string;
status: number | null;
error: string | null;
zone: string | null;
record_id: number | null;
target_user_id: number | null;
before_value: unknown;
after_value: unknown;
}
export interface DelegationRow {
zone: string;
user_id: number;
username: string;
created_at: string;
created_by: number;
}
export interface SessionRow {
user_id: number;
created_at: string;
last_seen_at: string;
expires_at: string;
origin: string;
user_agent: string;
}
export type RawRecord = { zone: string; name: string; ttl: number | null; content: string | null; record_type: string };
const INIT_TEMPLATE = path.resolve(process.cwd(), 'stack', 'mysql-init.sql');
const WEBUI_GRANT_TEMPLATES = {
tables: path.resolve(process.cwd(), 'stack', 'mysql-webui-tables.sql'),
database: path.resolve(process.cwd(), 'stack', 'mysql-webui-database.sql'),
} as const;
function connectionOptions(database?: string): mysql.ConnectionOptions {
return {
host: MYSQL_HOST,
port: 3306,
user: 'root',
password: requireEnv('E2E_MYSQL_ROOT_PASSWORD'),
database,
timezone: 'Z',
dateStrings: true,
supportBigNumbers: true,
bigNumberStrings: false,
charset: 'utf8mb4_general_ci',
connectTimeout: 10_000,
};
}
function q(identifier: string): string {
if (!/^[A-Za-z0-9_]+$/.test(identifier)) throw new HarnessError('infrastructure', `unsafe identifier ${identifier}`);
return '`' + identifier + '`';
}
function qualified(schema: string, table: string): string {
return `${q(schema)}.${q(table)}`;
}
export function initSql(g: GroupConfig): string {
const template = fs.readFileSync(INIT_TEMPLATE, 'utf8') + '\n' + fs.readFileSync(WEBUI_GRANT_TEMPLATES[g.webuiGrants], 'utf8');
const values: Record<string, string> = {
DATABASE: g.database,
PREFIX: g.prefix,
WEBUI_DATABASE: g.webuiDatabase,
WEBUI_PREFIX: g.webuiPrefix,
DNS_USER: g.dnsUser,
DNS_PASSWORD: g.dnsPassword,
APP_USER: g.appUser,
APP_PASSWORD: g.appPassword,
};
return template
.split('\n')
.filter((l) => !l.startsWith('--'))
.join('\n')
.replace(/\{\{([A-Z_]+)\}\}/g, (_m, k: string) => {
const v = values[k];
if (v === undefined || !/^[A-Za-z0-9_-]*$/.test(v) || (v === '' && !k.endsWith('PREFIX'))) throw new HarnessError('infrastructure', `bad template value ${k}`);
return v;
});
}
export async function initDatabases(): Promise<void> {
const conn = await mysql.createConnection({ ...connectionOptions(), multipleStatements: true });
try {
for (const name of GROUP_NAMES) {
const [rows] = await conn.query<mysql.RowDataPacket[]>('SELECT SCHEMA_NAME FROM information_schema.SCHEMATA WHERE SCHEMA_NAME = ?', [GROUPS[name].database]);
if (rows.length > 0) continue;
await conn.query(initSql(GROUPS[name]));
}
} finally {
await conn.end();
}
}
export async function waitForMysql(timeoutMs = 120_000): Promise<void> {
const deadline = Date.now() + timeoutMs;
for (;;) {
try {
const conn = await mysql.createConnection(connectionOptions());
await conn.query('SELECT 1');
await conn.end();
return;
} catch (e) {
if (Date.now() > deadline) throw new HarnessError('timeout', `mysql not reachable: ${(e as Error).message}`);
await new Promise((r) => setTimeout(r, 500));
}
}
}
export class Db {
private readonly pool: mysql.Pool;
readonly t: { records: string; users: string; sessions: string; delegations: string; audit: string; schema: string };
constructor(readonly group: GroupConfig) {
this.pool = mysql.createPool({ ...connectionOptions(group.database), connectionLimit: 4 });
const ui = (table: string) => qualified(group.webuiDatabase, `${group.webuiPrefix}webui_${table}`);
this.t = {
records: qualified(group.database, `${group.prefix}records`),
users: ui('users'),
sessions: ui('sessions'),
delegations: ui('zone_delegations'),
audit: ui('audit'),
schema: ui('schema'),
};
}
async query<T = mysql.RowDataPacket>(sql: string, params: unknown[] = []): Promise<T[]> {
const [rows] = await this.pool.query(sql, params);
return rows as T[];
}
async exec(sql: string, params: unknown[] = []): Promise<mysql.ResultSetHeader> {
const [r] = await this.pool.query<mysql.ResultSetHeader>(sql, params);
return r;
}
async records(zone?: string): Promise<RecordRow[]> {
const where = zone === undefined ? '' : 'WHERE `zone` = BINARY ?';
return this.query<RecordRow>(`SELECT id, zone, name, ttl, content, record_type FROM ${this.t.records} ${where} ORDER BY id`, zone === undefined ? [] : [zone]);
}
async recordById(id: number): Promise<RecordRow | undefined> {
const rows = await this.query<RecordRow>(`SELECT id, zone, name, ttl, content, record_type FROM ${this.t.records} WHERE id = ?`, [id]);
return rows[0];
}
async zones(): Promise<string[]> {
const rows = await this.query<{ zone: string }>(`SELECT DISTINCT zone FROM ${this.t.records} ORDER BY zone`);
return rows.map((r) => r.zone);
}
async recordCount(): Promise<number> {
const rows = await this.query<{ n: number }>(`SELECT COUNT(*) AS n FROM ${this.t.records}`);
return Number(rows[0].n);
}
async insertRaw(r: RawRecord): Promise<number> {
const res = await this.exec(`INSERT INTO ${this.t.records} (zone, name, ttl, content, record_type) VALUES (?, ?, ?, ?, ?)`, [r.zone, r.name, r.ttl, r.content, r.record_type]);
return res.insertId;
}
async insertMany(rows: RawRecord[]): Promise<void> {
for (let i = 0; i < rows.length; i += 1000) {
const chunk = rows.slice(i, i + 1000);
await this.exec(
`INSERT INTO ${this.t.records} (zone, name, ttl, content, record_type) VALUES ${chunk.map(() => '(?, ?, ?, ?, ?)').join(', ')}`,
chunk.flatMap((r) => [r.zone, r.name, r.ttl, r.content, r.record_type]),
);
}
}
async updateRaw(id: number, fields: Partial<RawRecord>): Promise<void> {
const keys = Object.keys(fields) as Array<keyof RawRecord>;
if (keys.length === 0) return;
await this.exec(`UPDATE ${this.t.records} SET ${keys.map((k) => `${q(k)} = ?`).join(', ')} WHERE id = ?`, [...keys.map((k) => fields[k]), id]);
}
async deleteZoneRaw(zone: string): Promise<void> {
await this.exec(`DELETE FROM ${this.t.records} WHERE zone = BINARY ?`, [zone]);
}
async soaContent(zone: string): Promise<Record<string, unknown> | null> {
const rows = await this.query<RecordRow>(`SELECT id, zone, name, ttl, content, record_type FROM ${this.t.records} WHERE zone = BINARY ? AND name = '' AND record_type = 'SOA'`, [zone]);
if (rows.length !== 1 || rows[0].content === null) return null;
return JSON.parse(rows[0].content) as Record<string, unknown>;
}
async soaSerial(zone: string): Promise<number | null> {
const soa = await this.soaContent(zone);
return soa && typeof soa.serial === 'number' ? soa.serial : null;
}
async users(): Promise<UserRow[]> {
return this.query<UserRow>(`SELECT id, username, role, password_hash, created_at, updated_at, last_login_at, deleted_at FROM ${this.t.users} ORDER BY id`);
}
async user(username: string): Promise<UserRow | undefined> {
const rows = await this.query<UserRow>(
`SELECT id, username, role, password_hash, created_at, updated_at, last_login_at, deleted_at FROM ${this.t.users} WHERE username = ?`,
[username],
);
return rows[0];
}
async userId(username: string): Promise<number | null> {
return (await this.user(username))?.id ?? null;
}
async usernameById(id: number): Promise<string | null> {
const rows = await this.query<{ username: string }>(`SELECT username FROM ${this.t.users} WHERE id = ?`, [id]);
return rows[0]?.username ?? null;
}
async delegations(): Promise<DelegationRow[]> {
return this.query<DelegationRow>(
`SELECT d.zone, d.user_id, u.username, d.created_at, d.created_by FROM ${this.t.delegations} d JOIN ${this.t.users} u ON u.id = d.user_id ORDER BY d.zone, u.username`,
);
}
async sessions(userId?: number): Promise<SessionRow[]> {
const where = userId === undefined ? '' : 'WHERE user_id = ?';
return this.query<SessionRow>(`SELECT user_id, created_at, last_seen_at, expires_at, origin, user_agent FROM ${this.t.sessions} ${where}`, userId === undefined ? [] : [userId]);
}
async sessionExists(hash: Buffer): Promise<boolean> {
const [row] = await this.query<{ n: number }>(`SELECT COUNT(*) AS n FROM ${this.t.sessions} WHERE token_hash = ?`, [hash]);
return Number(row.n) === 1;
}
async deleteSessions(userId: number): Promise<void> {
await this.exec(`DELETE FROM ${this.t.sessions} WHERE user_id = ?`, [userId]);
}
async auditMaxId(): Promise<number> {
const rows = await this.query<{ id: number | null }>(`SELECT MAX(id) AS id FROM ${this.t.audit}`);
return Number(rows[0].id ?? 0);
}
private async auditRows(clause: string, value: number): Promise<AuditRow[]> {
const rows = await this.query<AuditRow>(
`SELECT id, DATE_FORMAT(time, '%Y-%m-%dT%H:%i:%s.%fZ') AS time, user_id, actor, origin, operation, status, error, zone, record_id, target_user_id, CAST(before_value AS CHAR) AS before_value, CAST(after_value AS CHAR) AS after_value FROM ${this.t.audit} ${clause}`,
[value],
);
return rows.map(row => ({
...row,
before_value: row.before_value === null ? null : JSON.parse(String(row.before_value)),
after_value: row.after_value === null ? null : JSON.parse(String(row.after_value)),
}));
}
async auditSince(id: number): Promise<AuditRow[]> {
return this.auditRows('WHERE id > ? ORDER BY id', id);
}
async auditTail(n: number): Promise<AuditRow[]> {
const rows = await this.auditRows('ORDER BY id DESC LIMIT ?', n);
return rows.reverse();
}
async auditCount(where = '1 = 1', params: unknown[] = []): Promise<number> {
const rows = await this.query<{ n: number }>(`SELECT COUNT(*) AS n FROM ${this.t.audit} WHERE ${where}`, params);
return Number(rows[0].n);
}
async tables(schema: string): Promise<string[]> {
const rows = await this.query<{ name: string }>('SELECT TABLE_NAME AS name FROM information_schema.TABLES WHERE TABLE_SCHEMA = ? ORDER BY TABLE_NAME', [schema]);
return rows.map((r) => r.name);
}
async snapshot(): Promise<string> {
const records = await this.records().catch(() => []);
const audit = await this.auditTail(60).catch(() => []);
const users = await this.users().catch(() => []);
const delegations = await this.delegations().catch(() => []);
return JSON.stringify(
{
records: records.slice(-300),
recordCount: records.length,
users: users.map((u) => ({ ...u, password_hash: u.password_hash ? '[hash]' : '' })),
delegations,
audit,
},
null,
2,
);
}
async close(): Promise<void> {
await this.pool.end();
}
}