-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
298 lines (263 loc) · 9.82 KB
/
Copy pathserver.ts
File metadata and controls
298 lines (263 loc) · 9.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
import express from 'express';
import cors from 'cors';
import path from 'path';
import { createServer as createViteServer } from 'vite';
import mysql from 'mysql2/promise';
import { Client } from 'pg';
import Redis from 'ioredis';
const app = express();
const PORT = 3000;
app.use(cors());
app.use(express.json());
// API route logic inside functions to isolate DB connections
import { createClient } from 'webdav';
app.post('/api/webdav/backup', async (req, res) => {
const { url, username, password, data, path = "/dbclient_connections.json" } = req.body;
if (!url || !username || !password) return res.status(400).json({error: 'Missing details'});
try {
const client = createClient(url, { username, password });
// if a directory path is provided, try to create it first.
const dirPath = path.substring(0, path.lastIndexOf('/'));
if (dirPath && dirPath.length > 0 && dirPath !== '/') {
try {
await client.createDirectory(dirPath);
} catch (e) {}
}
await client.putFileContents(path, JSON.stringify(data));
res.json({ success: true });
} catch (error: any) {
res.status(400).json({ error: error.message });
}
});
app.post('/api/webdav/restore', async (req, res) => {
const { url, username, password, path = "/dbclient_connections.json" } = req.body;
if (!url || !username || !password) return res.status(400).json({error: 'Missing details'});
try {
const client = createClient(url, { username, password });
if (await client.exists(path) === false) {
return res.status(404).json({ error: "Backup file not found on WebDAV server at " + path });
}
const data = await client.getFileContents(path, { format: "text" });
let textData = typeof data === 'string' ? data : (data as Buffer).toString('utf-8');
try {
res.json({ success: true, data: JSON.parse(textData) });
} catch (parseError) {
const preview = textData.trim().substring(0, 40).replace(/\r?\n|\r/g, ' ');
return res.status(400).json({ error: `WebDAV server returned an invalid file (not JSON). Server response starts with: "${preview}...". Please check your URL/Path and ensure you have backed up first.` });
}
} catch (error: any) {
res.status(400).json({ error: error.message });
}
});
const connectMysql = async (config: any) => {
return await mysql.createConnection({
host: config.host,
port: config.port || 3306,
user: config.username,
password: config.password,
database: config.database,
ssl: config.ssl ? { rejectUnauthorized: false } : undefined,
connectTimeout: 10000,
});
};
const connectPg = async (config: any) => {
const client = new Client({
host: config.host,
port: config.port || 5432,
user: config.username,
password: config.password,
database: config.database,
ssl: config.ssl ? { rejectUnauthorized: false } : false,
connectionTimeoutMillis: 10000,
});
await client.connect();
return client;
};
const connectRedis = async (config: any) => {
return new Redis({
host: config.host,
port: config.port || 6379,
password: config.password,
db: config.database ? parseInt(config.database, 10) || 0 : 0,
tls: config.ssl ? { rejectUnauthorized: false } : undefined,
commandTimeout: 10000,
maxRetriesPerRequest: 1,
retryStrategy: () => null // Do not retry on initial connect failure
});
};
// 1. /api/ping: Test connection
app.post('/api/ping', async (req, res) => {
const t0 = Date.now();
const config = req.body;
try {
if (config.type === 'mysql') {
const conn = await connectMysql(config);
await conn.ping();
await conn.end();
} else if (config.type === 'postgres') {
const conn = await connectPg(config);
await conn.query('SELECT 1');
await conn.end();
} else if (config.type === 'redis') {
const conn = await connectRedis(config);
await conn.ping();
await conn.quit();
} else {
throw new Error('Unsupported database type');
}
res.json({ success: true, ms: Date.now() - t0 });
} catch (error: any) {
res.json({ success: false, error: error.message || 'Connection failed' });
}
});
function applyLimit(sql: string, limit: number): string {
let trimmed = sql.trim();
while (trimmed.endsWith(';')) {
trimmed = trimmed.slice(0, -1).trim();
}
if (!trimmed) return sql;
const upperSql = trimmed.toUpperCase();
if (!upperSql.startsWith('SELECT')) {
return sql;
}
if (upperSql.includes('LIMIT')) return sql;
return `${trimmed} LIMIT ${limit}`;
}
const safeSqlKeywords = ['SELECT', 'SHOW', 'DESCRIBE', 'EXPLAIN'];
function isSafeQuery(sql: string): boolean {
const trimSqL = sql.trim().toUpperCase();
return safeSqlKeywords.some(kw => trimSqL.startsWith(kw));
}
// 2. /api/query: Execute queries (only safe ones)
app.post('/api/query', async (req, res) => {
const config = req.body;
let sql = req.body.sql as string;
if (!sql || !sql.trim()) {
return res.status(400).json({ error: 'SQL/Command is empty' });
}
const isRedis = config.type === 'redis';
if (!isRedis && !isSafeQuery(sql)) {
return res.status(400).json({ error: 'Execution blocked: Only SELECT / SHOW / DESCRIBE / EXPLAIN are allowed' });
}
if (!isRedis) {
sql = applyLimit(sql, 1000);
}
const t0 = Date.now();
try {
let rows: any[] = [];
if (config.type === 'mysql') {
const conn = await connectMysql(config);
const [results] = await conn.query(sql);
rows = Array.isArray(results) ? results : [results]; // Ensure it's an array of rows
await conn.end();
} else if (config.type === 'postgres') {
const conn = await connectPg(config);
const result = await conn.query(sql);
rows = result.rows;
await conn.end();
} else if (isRedis) {
const conn = await connectRedis(config);
// split command string roughly, e.g. "GET mykey" -> ["GET", "mykey"]
const args = sql.trim().match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g) || [];
const parsedArgs = args.map(arg => arg.replace(/^['"](.*)['"]$/, '$1'));
if (parsedArgs.length === 0) throw new Error('Empty command');
const command = parsedArgs[0].toLowerCase();
// block some dangerous redis commands if we want, but for now just pass to ioredis
const blocked = ['flushdb', 'flushall', 'config'];
if (blocked.includes(command)) {
throw new Error(`Execution blocked: ${command.toUpperCase()} is not allowed`);
}
const redisResult = await conn.call(parsedArgs[0], ...parsedArgs.slice(1));
if (Array.isArray(redisResult)) {
rows = redisResult.map((val, index) => ({ index, value: val }));
} else if (typeof redisResult === 'object' && redisResult !== null) {
rows = Object.entries(redisResult).map(([key, value]) => ({ key, value }));
} else {
rows = [{ result: redisResult }];
}
await conn.quit();
} else {
throw new Error('Unsupported database type');
}
const ms = Date.now() - t0;
res.json({ success: true, rows, count: rows.length, ms });
} catch (error: any) {
res.status(400).json({ success: false, error: error.message || 'Execution failed' });
}
});
// 3. /api/structure: Fetch database structure (DB -> Tables -> Columns)
app.post('/api/structure', async (req, res) => {
const config = req.body;
try {
let structure: any = {};
if (config.type === 'mysql') {
const conn = await connectMysql(config);
const [tablesRow] = await conn.query(`SHOW TABLES`);
const tables = (tablesRow as any[]).map(r => Object.values(r)[0] as string);
for (const table of tables) {
const [cols] = await conn.query(`DESCRIBE ??`, [table]);
structure[table] = (cols as any[]).map(c => ({
name: c.Field,
type: c.Type,
nullable: c.Null === 'YES',
primaryKey: c.Key === 'PRI'
}));
}
await conn.end();
} else if (config.type === 'postgres') {
const conn = await connectPg(config);
const tablesQuery = `
SELECT tablename
FROM pg_tables
WHERE schemaname = 'public'
`;
const tableResult = await conn.query(tablesQuery);
const tables = tableResult.rows.map(r => r.tablename);
for (const table of tables) {
const colsQuery = `
SELECT column_name, data_type, is_nullable,
(SELECT count(*) > 0 FROM information_schema.key_column_usage
WHERE table_name = $1 AND column_name = columns.column_name) as is_pk
FROM information_schema.columns
WHERE table_name = $1 AND table_schema = 'public'
`;
const colsResult = await conn.query(colsQuery, [table]);
structure[table] = colsResult.rows.map(c => ({
name: c.column_name,
type: c.data_type,
nullable: c.is_nullable === 'YES',
primaryKey: c.is_pk
}));
}
await conn.end();
} else if (config.type === 'redis') {
structure['Redis Keys'] = [];
} else {
throw new Error('Unsupported database type');
}
res.json({ success: true, structure });
} catch (error: any) {
res.status(400).json({ success: false, error: error.message || 'Failed to fetch structure' });
}
});
// Vite middleware for development
async function startServer() {
if (process.env.NODE_ENV !== 'production') {
const vite = await createViteServer({
server: { middlewareMode: true },
appType: 'spa',
});
app.use(vite.middlewares);
} else {
// Serve production static assets
const distPath = path.join(process.cwd(), 'dist');
app.use(express.static(distPath));
app.get('*', (req, res) => {
res.sendFile(path.join(distPath, 'index.html'));
});
}
app.listen(PORT, '0.0.0.0', () => {
console.log(`Server running on http://localhost:${PORT}`);
});
}
startServer();