import { config } from '../config/index.js';
export class QueryValidator {
private static readonly READ_ONLY_KEYWORDS = [
'SELECT', 'SHOW', 'DESCRIBE', 'DESC', 'EXPLAIN'
];
private static readonly WRITE_KEYWORDS = {
INSERT: 'allowInsert',
UPDATE: 'allowUpdate',
DELETE: 'allowDelete',
DROP: 'allowDDL',
CREATE: 'allowDDL',
ALTER: 'allowDDL',
TRUNCATE: 'allowDDL'
} as const;
public static validateQuery(sql: string): { allowed: boolean; reason?: string } {
const trimmedSql = sql.trim().toUpperCase();
// Check if it's a read-only query
if (this.READ_ONLY_KEYWORDS.some(keyword => trimmedSql.startsWith(keyword))) {
return { allowed: true };
}
// Check write operations
for (const [keyword, configKey] of Object.entries(this.WRITE_KEYWORDS)) {
if (trimmedSql.startsWith(keyword)) {
const allowed = config.server[configKey as keyof typeof config.server];
if (!allowed) {
return {
allowed: false,
reason: `${keyword} operations are not allowed. Enable ${configKey} in configuration.`
};
}
return { allowed: true };
}
}
// If not explicitly allowed, deny
return {
allowed: false,
reason: 'Query type not recognized or not allowed'
};
}
public static isReadOnlyQuery(sql: string): boolean {
const trimmedSql = sql.trim().toUpperCase();
return this.READ_ONLY_KEYWORDS.some(keyword => trimmedSql.startsWith(keyword));
}
}