fdb2 1.0.41 → 1.0.42

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/README.md +10 -0
  2. package/dist/public/.vite/manifest.json +11 -9
  3. package/dist/public/database-monitor.css +109 -86
  4. package/dist/public/database-monitor.js +153 -33
  5. package/dist/public/database.js +41 -2
  6. package/dist/public/explorer.css +303 -252
  7. package/dist/public/explorer.js +633 -412
  8. package/dist/public/export.js +7 -7
  9. package/dist/public/index.js +101 -8
  10. package/dist/public/layout.js +1 -1
  11. package/dist/public/{theme.js → modal.js} +88 -2
  12. package/dist/public/sql-query-editor.css +82 -82
  13. package/dist/public/sql-query-editor.js +64 -47
  14. package/dist/scripts/verify-db-support.cjs +93 -7
  15. package/dist/server/__tests__/excel-export.test.ts +136 -0
  16. package/dist/server/__tests__/export-progress.test.ts +80 -0
  17. package/dist/server/__tests__/health-check.test.ts +67 -0
  18. package/dist/server/__tests__/query-metrics.test.ts +96 -0
  19. package/dist/server/__tests__/remote-proxy.test.ts +14 -0
  20. package/dist/server/__tests__/sql-safety.test.ts +36 -0
  21. package/dist/server/core/dialect.d.ts +3 -0
  22. package/dist/server/core/dialect.d.ts.map +1 -1
  23. package/dist/server/core/dialect.js +17 -0
  24. package/dist/server/core/dialect.js.map +1 -1
  25. package/dist/server/core/dialect.ts +20 -0
  26. package/dist/server/core/query-metrics.d.ts +33 -0
  27. package/dist/server/core/query-metrics.d.ts.map +1 -0
  28. package/dist/server/core/query-metrics.js +117 -0
  29. package/dist/server/core/query-metrics.js.map +1 -0
  30. package/dist/server/core/query-metrics.ts +137 -0
  31. package/dist/server/core/sql-safety.d.ts +9 -0
  32. package/dist/server/core/sql-safety.d.ts.map +1 -0
  33. package/dist/server/core/sql-safety.js +74 -0
  34. package/dist/server/core/sql-safety.js.map +1 -0
  35. package/dist/server/core/sql-safety.ts +72 -0
  36. package/dist/server/index.d.ts +2 -0
  37. package/dist/server/index.d.ts.map +1 -1
  38. package/dist/server/index.js +211 -17
  39. package/dist/server/index.js.map +1 -1
  40. package/dist/server/index.ts +217 -17
  41. package/dist/server/service/database/base.service.d.ts +15 -0
  42. package/dist/server/service/database/base.service.d.ts.map +1 -1
  43. package/dist/server/service/database/base.service.js +108 -0
  44. package/dist/server/service/database/base.service.js.map +1 -1
  45. package/dist/server/service/database/base.service.ts +99 -6
  46. package/dist/server/service/database/clickhouse.service.d.ts.map +1 -1
  47. package/dist/server/service/database/clickhouse.service.js +9 -35
  48. package/dist/server/service/database/clickhouse.service.js.map +1 -1
  49. package/dist/server/service/database/clickhouse.service.ts +9 -44
  50. package/dist/server/service/database/cockroachdb.service.d.ts.map +1 -1
  51. package/dist/server/service/database/cockroachdb.service.js +9 -38
  52. package/dist/server/service/database/cockroachdb.service.js.map +1 -1
  53. package/dist/server/service/database/cockroachdb.service.ts +10 -49
  54. package/dist/server/service/database/database.service.d.ts +15 -2
  55. package/dist/server/service/database/database.service.d.ts.map +1 -1
  56. package/dist/server/service/database/database.service.js +400 -6
  57. package/dist/server/service/database/database.service.js.map +1 -1
  58. package/dist/server/service/database/database.service.ts +402 -7
  59. package/dist/server/service/database/export-progress.d.ts +43 -0
  60. package/dist/server/service/database/export-progress.d.ts.map +1 -0
  61. package/dist/server/service/database/export-progress.js +117 -0
  62. package/dist/server/service/database/export-progress.js.map +1 -0
  63. package/dist/server/service/database/export-progress.ts +125 -0
  64. package/dist/server/service/database/mongodb.service.d.ts +2 -0
  65. package/dist/server/service/database/mongodb.service.d.ts.map +1 -1
  66. package/dist/server/service/database/mongodb.service.js +79 -44
  67. package/dist/server/service/database/mongodb.service.js.map +1 -1
  68. package/dist/server/service/database/mongodb.service.ts +76 -43
  69. package/dist/server/service/database/mssql.service.d.ts.map +1 -1
  70. package/dist/server/service/database/mssql.service.js +10 -9
  71. package/dist/server/service/database/mssql.service.js.map +1 -1
  72. package/dist/server/service/database/mssql.service.ts +10 -9
  73. package/dist/server/service/database/mysql.service.js +10 -10
  74. package/dist/server/service/database/mysql.service.js.map +1 -1
  75. package/dist/server/service/database/mysql.service.ts +10 -10
  76. package/dist/server/service/database/oracle.service.d.ts +4 -0
  77. package/dist/server/service/database/oracle.service.d.ts.map +1 -1
  78. package/dist/server/service/database/oracle.service.js +32 -13
  79. package/dist/server/service/database/oracle.service.js.map +1 -1
  80. package/dist/server/service/database/oracle.service.ts +33 -13
  81. package/dist/server/service/database/postgres.service.d.ts.map +1 -1
  82. package/dist/server/service/database/postgres.service.js +10 -9
  83. package/dist/server/service/database/postgres.service.js.map +1 -1
  84. package/dist/server/service/database/postgres.service.ts +10 -9
  85. package/dist/server/service/database/sap.service.d.ts.map +1 -1
  86. package/dist/server/service/database/sap.service.js +9 -38
  87. package/dist/server/service/database/sap.service.js.map +1 -1
  88. package/dist/server/service/database/sap.service.ts +10 -49
  89. package/dist/server/service/database/sqlite.service.d.ts.map +1 -1
  90. package/dist/server/service/database/sqlite.service.js +10 -9
  91. package/dist/server/service/database/sqlite.service.js.map +1 -1
  92. package/dist/server/service/database/sqlite.service.ts +10 -9
  93. package/package.json +1 -1
  94. package/scripts/verify-db-support.cjs +93 -7
  95. package/server.js +15 -2
@@ -0,0 +1,74 @@
1
+ "use strict";
2
+ /**
3
+ * 只读 SQL 安全闸门。
4
+ * 这里刻意不使用 query-builder 的 classifySql(它只做展示分类,不能作为安全边界)。
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.stripSqlLiteralsAndComments = stripSqlLiteralsAndComments;
8
+ exports.isSafeReadOnlySql = isSafeReadOnlySql;
9
+ /** 去掉注释和字符串/标识符字面量,仅保留需要检查的 SQL 结构。 */
10
+ function stripSqlLiteralsAndComments(sql) {
11
+ const input = String(sql || '');
12
+ let output = '';
13
+ let i = 0;
14
+ while (i < input.length) {
15
+ const ch = input[i];
16
+ const next = input[i + 1];
17
+ if (ch === '-' && next === '-') {
18
+ while (i < input.length && input[i] !== '\n')
19
+ i += 1;
20
+ continue;
21
+ }
22
+ if (ch === '#') {
23
+ while (i < input.length && input[i] !== '\n')
24
+ i += 1;
25
+ continue;
26
+ }
27
+ if (ch === '/' && next === '*') {
28
+ i += 2;
29
+ while (i < input.length && !(input[i] === '*' && input[i + 1] === '/'))
30
+ i += 1;
31
+ i += 2;
32
+ output += ' ';
33
+ continue;
34
+ }
35
+ if (ch === "'" || ch === '"' || ch === '`') {
36
+ const quote = ch;
37
+ i += 1;
38
+ while (i < input.length) {
39
+ if (input[i] === quote) {
40
+ if (input[i + 1] === quote) {
41
+ i += 2;
42
+ continue;
43
+ }
44
+ i += 1;
45
+ break;
46
+ }
47
+ if (quote !== '`' && input[i] === '\\') {
48
+ i += 2;
49
+ continue;
50
+ }
51
+ i += 1;
52
+ }
53
+ output += ' ';
54
+ continue;
55
+ }
56
+ output += ch;
57
+ i += 1;
58
+ }
59
+ return output;
60
+ }
61
+ const FORBIDDEN_KEYWORDS = /\b(?:INSERT|UPDATE|DELETE|REPLACE|MERGE|CREATE|ALTER|DROP|TRUNCATE|RENAME|GRANT|REVOKE|ATTACH|DETACH|COPY|LOAD|EXECUTE|EXEC|CALL|VACUUM|REINDEX|SET|RESET|FLUSH|ANALYZE|INTO|OUTFILE|DUMPFILE|PG_SLEEP|SLEEP)\b/i;
62
+ /** 只允许单条、无副作用、无 ANALYZE 的 SELECT/WITH/SHOW/DESCRIBE/PRAGMA/EXPLAIN。 */
63
+ function isSafeReadOnlySql(sql) {
64
+ const trimmed = String(sql || '').trim();
65
+ if (!trimmed || trimmed.includes(';'))
66
+ return false;
67
+ const structure = stripSqlLiteralsAndComments(trimmed).replace(/\s+/g, ' ').trim();
68
+ if (!/^(?:SELECT|WITH|SHOW|DESCRIBE|DESC|PRAGMA|EXPLAIN)\b/i.test(structure))
69
+ return false;
70
+ if (FORBIDDEN_KEYWORDS.test(structure))
71
+ return false;
72
+ return true;
73
+ }
74
+ //# sourceMappingURL=sql-safety.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sql-safety.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,IAAI,kBAAkB,CAAC,IAAI,CAAC,SAAS,CAAC;QAAE,OAAO,KAAK,CAAC;IAErD,OAAO,IAAI,CAAC;AACd,CAAC"}
@@ -0,0 +1,72 @@
1
+ /**
2
+ * 只读 SQL 安全闸门。
3
+ * 这里刻意不使用 query-builder 的 classifySql(它只做展示分类,不能作为安全边界)。
4
+ */
5
+
6
+ /** 去掉注释和字符串/标识符字面量,仅保留需要检查的 SQL 结构。 */
7
+ export function stripSqlLiteralsAndComments(sql: string): string {
8
+ const input = String(sql || '');
9
+ let output = '';
10
+ let i = 0;
11
+
12
+ while (i < input.length) {
13
+ const ch = input[i];
14
+ const next = input[i + 1];
15
+
16
+ if (ch === '-' && next === '-') {
17
+ while (i < input.length && input[i] !== '\n') i += 1;
18
+ continue;
19
+ }
20
+ if (ch === '#') {
21
+ while (i < input.length && input[i] !== '\n') i += 1;
22
+ continue;
23
+ }
24
+ if (ch === '/' && next === '*') {
25
+ i += 2;
26
+ while (i < input.length && !(input[i] === '*' && input[i + 1] === '/')) i += 1;
27
+ i += 2;
28
+ output += ' ';
29
+ continue;
30
+ }
31
+ if (ch === "'" || ch === '"' || ch === '`') {
32
+ const quote = ch;
33
+ i += 1;
34
+ while (i < input.length) {
35
+ if (input[i] === quote) {
36
+ if (input[i + 1] === quote) {
37
+ i += 2;
38
+ continue;
39
+ }
40
+ i += 1;
41
+ break;
42
+ }
43
+ if (quote !== '`' && input[i] === '\\') {
44
+ i += 2;
45
+ continue;
46
+ }
47
+ i += 1;
48
+ }
49
+ output += ' ';
50
+ continue;
51
+ }
52
+
53
+ output += ch;
54
+ i += 1;
55
+ }
56
+
57
+ return output;
58
+ }
59
+
60
+ const FORBIDDEN_KEYWORDS = /\b(?:INSERT|UPDATE|DELETE|REPLACE|MERGE|CREATE|ALTER|DROP|TRUNCATE|RENAME|GRANT|REVOKE|ATTACH|DETACH|COPY|LOAD|EXECUTE|EXEC|CALL|VACUUM|REINDEX|SET|RESET|FLUSH|ANALYZE|INTO|OUTFILE|DUMPFILE|PG_SLEEP|SLEEP)\b/i;
61
+
62
+ /** 只允许单条、无副作用、无 ANALYZE 的 SELECT/WITH/SHOW/DESCRIBE/PRAGMA/EXPLAIN。 */
63
+ export function isSafeReadOnlySql(sql: string): boolean {
64
+ const trimmed = String(sql || '').trim();
65
+ if (!trimmed || trimmed.includes(';')) return false;
66
+
67
+ const structure = stripSqlLiteralsAndComments(trimmed).replace(/\s+/g, ' ').trim();
68
+ if (!/^(?:SELECT|WITH|SHOW|DESCRIBE|DESC|PRAGMA|EXPLAIN)\b/i.test(structure)) return false;
69
+ if (FORBIDDEN_KEYWORDS.test(structure)) return false;
70
+
71
+ return true;
72
+ }
@@ -13,6 +13,8 @@ export declare function buildRemoteHeaders(proxyConn: any, opts?: {
13
13
  proxyMarker?: boolean;
14
14
  chain?: string[];
15
15
  }): Record<string, string>;
16
+ /** URL 归一化:忽略协议/主机大小写、默认端口与 localhost/127.0.0.1 别名,专用于环路判定。 */
17
+ export declare function normalizeProxyBase(base: string): string;
16
18
  /** 纯判断:base 是否已出现在链路中(用于阻止代理互指导致的递归) */
17
19
  export declare function hasProxyLoop(base: string, chain: string[]): boolean;
18
20
  /** 纯判断:链路深度是否已达到 5 跳上限(当前 URL 尚未加入 chain) */
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../server/index.ts"],"names":[],"mappings":"AAsDA,iCAAiC;AACjC,wBAAgB,aAAa,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,GAAG,MAAM,GAAG,SAAS,CAa7E;AAED;;;GAGG;AACH,wBAAgB,YAAY,CAAC,MAAM,EAAE,MAAM,GAAG;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,YAAY,EAAE,MAAM,CAAA;CAAE,GAAG,IAAI,CAO7F;AAqHD,uDAAuD;AACvD,wBAAgB,kBAAkB,CAChC,SAAS,EAAE,GAAG,EACd,IAAI,GAAE;IAAE,WAAW,CAAC,EAAE,O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,6CAA6C;AAC7C,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,OAAO,CAE/D;AAMD,wBAAgB,gBAAgB,CAAC,OAAO,CAAC,EAAE,GAAG,GAAG,MAAM,EAAE,CAExD;AA+OD,wBAAsB,oBAAoB,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,EAAE,OAAO,CAAC,EAAE,GAAG,gBA6tBpF"}
@@ -36,6 +36,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.extractConnId = extractConnId;
37
37
  exports.splitProxyId = splitProxyId;
38
38
  exports.buildRemoteHeaders = buildRemoteHeaders;
39
+ exports.normalizeProxyBase = normalizeProxyBase;
39
40
  exports.hasProxyLoop = hasProxyLoop;
40
41
  exports.isProxyHopLimitReached = isProxyHopLimitReached;
41
42
  exports.chainFromHeaders = chainFromHeaders;
@@ -45,6 +46,7 @@ const https = __importStar(require("node:https"));
45
46
  const fs = __importStar(require("node:fs"));
46
47
  const connection_service_1 = require("./service/connection.service");
47
48
  const database_service_1 = require("./service/database/database.service");
49
+ const export_progress_1 = require("./service/database/export-progress");
48
50
  const dialect_1 = require("./core/dialect");
49
51
  const data_dir_1 = require("./utils/data-dir");
50
52
  // 远程代理相关常量
@@ -55,6 +57,60 @@ const REMOTE_TOKEN_HEADER = 'x-db-tool-token';
55
57
  const REMOTE_PROXY_HEADER = 'x-db-tool-proxy';
56
58
  const REMOTE_CHAIN_HEADER = 'x-db-tool-proxy-chain';
57
59
  const MAX_PROXY_HOPS = 5;
60
+ /** 通用路由参数闸门:只有非空字符串能作为 id/库名/表名进入服务层。 */
61
+ function requireStringParam(value, name) {
62
+ if (typeof value !== 'string' || value.trim() === '')
63
+ throw Error(`Missing parameter: ${name}`);
64
+ return value;
65
+ }
66
+ const REQUIRED_STRING_PARAMS = {
67
+ '/api/database/executeQuery': ['id', 'sql'],
68
+ '/api/database/getSlowQueries': ['id'],
69
+ '/api/database/clearSlowQueries': ['id'],
70
+ '/api/database/explainQuery': ['id', 'sql'],
71
+ '/api/database/getResourceMetrics': ['id'],
72
+ '/api/database/checkHealth': ['id', 'databaseName'],
73
+ '/api/database/getDatabases': ['id'],
74
+ '/api/database/getDatabaseInfo': ['id', 'database'],
75
+ '/api/database/getTables': ['id', 'database'],
76
+ '/api/database/getTableInfo': ['id', 'database', 'table'],
77
+ '/api/database/getIndexes': ['id', 'database', 'table'],
78
+ '/api/database/createIndex': ['id', 'database', 'table'],
79
+ '/api/database/dropIndex': ['id', 'database', 'table', 'indexName'],
80
+ '/api/database/aggregate': ['id', 'database', 'table'],
81
+ '/api/database/getTableData': ['id', 'database', 'table'],
82
+ '/api/database/insertData': ['id', 'database', 'table'],
83
+ '/api/database/updateData': ['id', 'database', 'table'],
84
+ '/api/database/deleteData': ['id', 'database', 'table'],
85
+ '/api/database/importData': ['id', 'database', 'table'],
86
+ '/api/database/exportTableData': ['id', 'database', 'table'],
87
+ '/api/database/exportTableDataToSQL': ['id', 'database', 'table'],
88
+ '/api/database/exportTableDataToCSV': ['id', 'database', 'table'],
89
+ '/api/database/exportTableDataToJSON': ['id', 'database', 'table'],
90
+ '/api/database/exportTableDataToExcel': ['id', 'database', 'table'],
91
+ '/api/database/getExportProgress': ['jobId'],
92
+ '/api/database/createDatabase': ['id', 'databaseName'],
93
+ '/api/database/dropDatabase': ['id', 'databaseName'],
94
+ '/api/database/restore': ['id', 'databaseName', 'filePath'],
95
+ '/api/database/backup': ['id', 'databaseName'],
96
+ '/api/database/optimize': ['id', 'databaseName'],
97
+ '/api/database/analyze': ['id', 'databaseName'],
98
+ '/api/database/repair': ['id', 'databaseName'],
99
+ '/api/database/getViews': ['id', 'database'],
100
+ '/api/database/getViewDefinition': ['id', 'database', 'viewName'],
101
+ '/api/database/createView': ['id', 'database', 'viewName', 'definition'],
102
+ '/api/database/dropView': ['id', 'database', 'viewName'],
103
+ '/api/database/getProcedures': ['id', 'database'],
104
+ '/api/database/getProcedureDefinition': ['id', 'database', 'procedureName']
105
+ };
106
+ function validateStringParams(pathname, body) {
107
+ for (const name of REQUIRED_STRING_PARAMS[pathname] || []) {
108
+ requireStringParam(body?.[name], name);
109
+ }
110
+ // 可选库名一旦提供也必须是字符串,避免对象被拼进 SQL/代理路径。
111
+ if (body?.database !== undefined && body.database !== null)
112
+ requireStringParam(body.database, 'database');
113
+ }
58
114
  // 永不转发的路由:只作用于本地连接配置(无远程对应物或需要本地语义)
59
115
  const LOCAL_ONLY_ROUTES = new Set([
60
116
  '/api/database/getConnection',
@@ -74,6 +130,21 @@ const CONNECTION_CONFIG_ROUTES = new Set([
74
130
  function isRemoteConnection(conn) {
75
131
  return !!conn && conn.type === 'remote';
76
132
  }
133
+ /** 监控类接口只允许本地页面/扩展宿主调用,阻止任意网页读取本机 SQL 样本。 */
134
+ function isTrustedLocalRequest(headers) {
135
+ const origin = headers?.origin || headers?.Origin;
136
+ if (!origin)
137
+ return true; // Electron / VSCode 内进程调用没有 Origin
138
+ try {
139
+ const url = new URL(String(origin));
140
+ if (['localhost', '127.0.0.1', '::1'].includes(url.hostname))
141
+ return true;
142
+ return ['vscode-webview:', 'vscode:', 'file:'].includes(url.protocol);
143
+ }
144
+ catch {
145
+ return false;
146
+ }
147
+ }
77
148
  /** 深拷贝连接 options,并移除不应下发的远程访问令牌(混合版本兼容) */
78
149
  function cloneOptionsWithoutRemoteToken(options) {
79
150
  if (!options || typeof options !== 'object')
@@ -103,6 +174,10 @@ function extractConnId(pathname, body) {
103
174
  const parts = pathname.split('/').filter(Boolean);
104
175
  return parts[3];
105
176
  }
177
+ if (pathname.startsWith('/api/database/checkHealth/')) {
178
+ const parts = pathname.split('/').filter(Boolean);
179
+ return parts[3];
180
+ }
106
181
  if (body && typeof body.id === 'string')
107
182
  return body.id;
108
183
  return undefined;
@@ -194,7 +269,7 @@ function postRemoteByNodeHttp(url, body, headers, timeoutMs) {
194
269
  port: target.port || (target.protocol === 'https:' ? 443 : 80),
195
270
  path: (target.pathname || '/') + (target.search || ''),
196
271
  method: 'POST',
197
- headers: { ...headers, 'Content-Length': payload.length }
272
+ headers: { 'Content-Type': 'application/json', ...headers, 'Content-Length': payload.length }
198
273
  }, (res) => {
199
274
  let raw = '';
200
275
  res.setEncoding('utf8');
@@ -235,9 +310,27 @@ function buildRemoteHeaders(proxyConn, opts = {}) {
235
310
  headers[REMOTE_TOKEN_HEADER] = String(token);
236
311
  return headers;
237
312
  }
313
+ /** URL 归一化:忽略协议/主机大小写、默认端口与 localhost/127.0.0.1 别名,专用于环路判定。 */
314
+ function normalizeProxyBase(base) {
315
+ try {
316
+ const url = new URL(String(base || ''));
317
+ const hostname = url.hostname.toLowerCase();
318
+ const loopback = ['localhost', '127.0.0.1', '[::1]', '::1'].includes(hostname);
319
+ const host = loopback ? 'loopback' : hostname;
320
+ const defaultPort = (url.protocol === 'https:' && url.port === '443')
321
+ || (url.protocol === 'http:' && url.port === '80');
322
+ const port = url.port && !defaultPort ? `:${url.port}` : '';
323
+ const pathname = url.pathname.replace(/\/+$/, '');
324
+ return `${url.protocol.toLowerCase()}//${host}${port}${pathname}`;
325
+ }
326
+ catch {
327
+ return String(base || '').replace(/\/+$/, '');
328
+ }
329
+ }
238
330
  /** 纯判断:base 是否已出现在链路中(用于阻止代理互指导致的递归) */
239
331
  function hasProxyLoop(base, chain) {
240
- return !!base && chain.includes(base);
332
+ const key = normalizeProxyBase(base);
333
+ return !!key && chain.some((item) => normalizeProxyBase(item) === key);
241
334
  }
242
335
  /** 纯判断:链路深度是否已达到 5 跳上限(当前 URL 尚未加入 chain) */
243
336
  function isProxyHopLimitReached(chain) {
@@ -268,7 +361,9 @@ async function proxyToRemote(proxyConn, remoteConnId, pathname, body, chain = []
268
361
  targetPath = '/' + parts.join('/');
269
362
  }
270
363
  const targetBody = { ...body, id: remoteConnId };
271
- const env = await postRemote(`${base}${targetPath}`, targetBody, buildRemoteHeaders(proxyConn, { proxyMarker: false, chain: nextChain }), 60000);
364
+ // 大表导出可能远超默认 60s,避免代理链路先把请求掐断
365
+ const timeoutMs = /\/api\/database\/exportTableDataTo/i.test(pathname) ? 30 * 60 * 1000 : 60000;
366
+ const env = await postRemote(`${base}${targetPath}`, targetBody, buildRemoteHeaders(proxyConn, { proxyMarker: false, chain: nextChain }), timeoutMs);
272
367
  if (env && typeof env === 'object' && env.ret && env.ret !== 0) {
273
368
  throw new Error(env.msg || '远程服务执行失败');
274
369
  }
@@ -443,6 +538,20 @@ const backupScheduler = setInterval(() => {
443
538
  }, 60 * 1000);
444
539
  // 不阻止进程退出(VSCode 扩展宿主 / CLI 也会导入本模块)
445
540
  backupScheduler.unref?.();
541
+ /** 包一层导出调用:保持原有「返回文件路径」的响应契约,同时记录可轮询的进度。 */
542
+ async function runTableExport(options, exportFn) {
543
+ const jobId = typeof options?.jobId === 'string' ? options.jobId : undefined;
544
+ (0, export_progress_1.startExportJob)(jobId);
545
+ try {
546
+ const result = await exportFn({ ...(options || {}), jobId });
547
+ (0, export_progress_1.finishExportJob)(jobId, 'completed', { path: typeof result === 'string' ? result : undefined });
548
+ return result;
549
+ }
550
+ catch (error) {
551
+ (0, export_progress_1.finishExportJob)(jobId, 'failed', { message: error?.message || String(error) });
552
+ throw error;
553
+ }
554
+ }
446
555
  // 数据库相关路由处理
447
556
  async function handleDatabaseRoutes(pathname, body, headers) {
448
557
  try {
@@ -454,6 +563,12 @@ async function handleDatabaseRoutes(pathname, body, headers) {
454
563
  throw new Error('远程访问令牌无效');
455
564
  }
456
565
  }
566
+ validateStringParams(pathname, body);
567
+ if (pathname.startsWith('/api/database/checkHealth/')) {
568
+ const parts = pathname.split('/').filter(Boolean);
569
+ requireStringParam(parts[3], 'id');
570
+ requireStringParam(parts[4], 'databaseName');
571
+ }
457
572
  // 网关模式:合并远程服务暴露的连接
458
573
  if (pathname === '/api/database/getConnections') {
459
574
  // 请求本身来自代理时不再二次合并,避免远程地址指向自身(或互指)造成无限递归
@@ -470,7 +585,22 @@ async function handleDatabaseRoutes(pathname, body, headers) {
470
585
  // 覆盖数据操作(查询/建表/改结构等)与连接配置的增删改
471
586
  const proxy = await resolveRemoteProxy(pathname, body);
472
587
  if (proxy) {
473
- return await proxyToRemote(proxy.proxyConn, proxy.remoteConnId, pathname, body, chainFromHeaders(headers));
588
+ // 远程导出:本地登记 job 并记录路由,让客户端轮询能转发到真正写文件的远程服务
589
+ const localJobId = /\/api\/database\/exportTableDataTo/i.test(pathname)
590
+ ? (typeof body?.options?.jobId === 'string' ? body.options.jobId : undefined)
591
+ : undefined;
592
+ let forwardedBody = body;
593
+ if (localJobId) {
594
+ (0, export_progress_1.startExportJob)(localJobId);
595
+ const remoteJobId = `${proxy.proxyConn.id}::${localJobId}`;
596
+ (0, export_progress_1.linkExportJob)(localJobId, {
597
+ proxyConnId: proxy.proxyConn.id,
598
+ remoteConnId: proxy.remoteConnId,
599
+ remoteJobId
600
+ });
601
+ forwardedBody = { ...body, options: { ...(body.options || {}), jobId: remoteJobId } };
602
+ }
603
+ return await proxyToRemote(proxy.proxyConn, proxy.remoteConnId, pathname, forwardedBody, chainFromHeaders(headers));
474
604
  }
475
605
  // 对「远程代理配置」本身做数据操作时给出明确提示(配置本身的增删改是允许的)
476
606
  if (!CONNECTION_CONFIG_ROUTES.has(pathname)) {
@@ -621,9 +751,45 @@ async function handleDatabaseRoutes(pathname, body, headers) {
621
751
  throw Error('Missing parameters: id, sql');
622
752
  if (!sql.trim())
623
753
  throw Error('SQL语句不能为空');
624
- const result = await databaseService.executeQuery(id, sql, database);
754
+ const result = await databaseService.executeQuery(id, sql, database, 'editor');
625
755
  return result;
626
756
  }
757
+ // /api/database/getSlowQueries —— 本进程采集的慢查询(仅本地、仅指定连接)
758
+ if (pathname === '/api/database/getSlowQueries') {
759
+ if (!isTrustedLocalRequest(headers))
760
+ throw Error('Forbidden origin');
761
+ const { id, minDurationMs = 2000, limit = 50 } = body;
762
+ if (!id)
763
+ throw Error('Missing parameter: id');
764
+ return databaseService.getSlowQueries(id, Number(minDurationMs), Number(limit));
765
+ }
766
+ // /api/database/clearSlowQueries
767
+ if (pathname === '/api/database/clearSlowQueries') {
768
+ if (!isTrustedLocalRequest(headers))
769
+ throw Error('Forbidden origin');
770
+ const { id } = body;
771
+ if (!id)
772
+ throw Error('Missing parameter: id');
773
+ return { cleared: databaseService.clearSlowQueries(id) };
774
+ }
775
+ // /api/database/explainQuery —— 只读执行计划
776
+ if (pathname === '/api/database/explainQuery') {
777
+ if (!isTrustedLocalRequest(headers))
778
+ throw Error('Forbidden origin');
779
+ const { id, sql, database } = body;
780
+ if (!id || !sql)
781
+ throw Error('Missing parameters: id, sql');
782
+ return await databaseService.explainQuery(id, sql, database);
783
+ }
784
+ // /api/database/getResourceMetrics —— 只读资源指标(逐项降级)
785
+ if (pathname === '/api/database/getResourceMetrics') {
786
+ if (!isTrustedLocalRequest(headers))
787
+ throw Error('Forbidden origin');
788
+ const { id, database } = body;
789
+ if (!id)
790
+ throw Error('Missing parameter: id');
791
+ return await databaseService.getResourceMetrics(id, database);
792
+ }
627
793
  // /api/database/closeConnection
628
794
  if (pathname === '/api/database/closeConnection') {
629
795
  const { id } = body;
@@ -791,6 +957,16 @@ async function handleDatabaseRoutes(pathname, body, headers) {
791
957
  const results = await databaseService.repairTables(id, databaseName);
792
958
  return { success: true, results };
793
959
  }
960
+ // /api/database/checkHealth —— 只读健康检查(完整性/索引有效性/明确降级)
961
+ // 同时接受 POST body 与 /checkHealth/:id/:database 路径,和旧 health 路由风格保持一致。
962
+ if (pathname === '/api/database/checkHealth' || pathname.startsWith('/api/database/checkHealth/')) {
963
+ const parts = pathname.split('/').filter(Boolean);
964
+ const id = extractConnId(pathname, body);
965
+ const databaseName = body?.databaseName || body?.database || parts[4];
966
+ if (!id || !databaseName)
967
+ throw Error('Missing parameters: id, databaseName');
968
+ return await databaseService.checkDatabaseHealth(id, databaseName);
969
+ }
794
970
  // /api/database/exportTableData
795
971
  if (pathname === '/api/database/exportTableData') {
796
972
  const { id, database, table, format = 'json', where } = body;
@@ -800,41 +976,59 @@ async function handleDatabaseRoutes(pathname, body, headers) {
800
976
  const result = await databaseService.getTableData(id, database, table, 1, 10000, where);
801
977
  return result;
802
978
  }
979
+ // /api/database/getExportProgress —— 导出进行中时由客户端轮询
980
+ if (pathname === '/api/database/getExportProgress') {
981
+ const localJobId = body?.jobId;
982
+ const route = (0, export_progress_1.getExportJobRoute)(localJobId);
983
+ if (route) {
984
+ try {
985
+ const proxyConn = await connectionService.getConnectionById(route.proxyConnId);
986
+ if (proxyConn && isRemoteConnection(proxyConn)) {
987
+ const remote = await proxyToRemote(proxyConn, route.remoteConnId, '/api/database/getExportProgress', { jobId: route.remoteJobId }, chainFromHeaders(headers));
988
+ if (remote) {
989
+ // 同步到本地 job:即使转发暂时失败,客户端也能拿到最近一次快照
990
+ (0, export_progress_1.reportExportRows)(localJobId, Number(remote.rows) || 0, remote.phase);
991
+ if (remote.status === 'completed')
992
+ (0, export_progress_1.finishExportJob)(localJobId, 'completed', { path: remote.path });
993
+ else if (remote.status === 'failed')
994
+ (0, export_progress_1.finishExportJob)(localJobId, 'failed', { message: remote.message });
995
+ }
996
+ return remote;
997
+ }
998
+ }
999
+ catch {
1000
+ // 代理配置缺失或转发失败时回落到本地快照
1001
+ }
1002
+ }
1003
+ return (0, export_progress_1.getExportProgress)(localJobId);
1004
+ }
803
1005
  // /api/database/exportTableDataToSQL
804
1006
  if (pathname === '/api/database/exportTableDataToSQL') {
805
1007
  const { id, database, table, options } = body;
806
1008
  if (!id || !database || !table)
807
1009
  throw Error('Missing parameters: id, database, table');
808
- // 调用数据库服务导出表数据到SQL文件
809
- const exportPath = await databaseService.exportTableDataToSQL(id, database, table, options);
810
- return exportPath;
1010
+ return await runTableExport(options, (opts) => databaseService.exportTableDataToSQL(id, database, table, opts));
811
1011
  }
812
1012
  // /api/database/exportTableDataToCSV
813
1013
  if (pathname === '/api/database/exportTableDataToCSV') {
814
1014
  const { id, database, table, options } = body;
815
1015
  if (!id || !database || !table)
816
1016
  throw Error('Missing parameters: id, database, table');
817
- // 调用数据库服务导出表数据到CSV文件
818
- const exportPath = await databaseService.exportTableDataToCSV(id, database, table, options);
819
- return exportPath;
1017
+ return await runTableExport(options, (opts) => databaseService.exportTableDataToCSV(id, database, table, opts));
820
1018
  }
821
1019
  // /api/database/exportTableDataToJSON
822
1020
  if (pathname === '/api/database/exportTableDataToJSON') {
823
1021
  const { id, database, table, options } = body;
824
1022
  if (!id || !database || !table)
825
1023
  throw Error('Missing parameters: id, database, table');
826
- // 调用数据库服务导出表数据到JSON文件
827
- const exportPath = await databaseService.exportTableDataToJSON(id, database, table, options);
828
- return exportPath;
1024
+ return await runTableExport(options, (opts) => databaseService.exportTableDataToJSON(id, database, table, opts));
829
1025
  }
830
1026
  // /api/database/exportTableDataToExcel
831
1027
  if (pathname === '/api/database/exportTableDataToExcel') {
832
1028
  const { id, database, table, options } = body;
833
1029
  if (!id || !database || !table)
834
1030
  throw Error('Missing parameters: id, database, table');
835
- // 调用数据库服务导出表数据到Excel文件
836
- const exportPath = await databaseService.exportTableDataToExcel(id, database, table, options);
837
- return exportPath;
1031
+ return await runTableExport(options, (opts) => databaseService.exportTableDataToExcel(id, database, table, opts));
838
1032
  }
839
1033
  // /api/database/refreshTableCache(手动全量拉取表列表,忽略预览缓存)
840
1034
  if (pathname === '/api/database/refreshTableCache') {