@zxlll/dsh-integration-env 0.0.0-stage → 0.1.1

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.
package/lib/mysql.js ADDED
@@ -0,0 +1,723 @@
1
+ /**
2
+ * 极简 MySQL 线协议客户端:只用 `node:net` + `node:crypto`,不依赖任何第三方驱动。
3
+ *
4
+ * 范围(契约 §8):
5
+ * - 握手 v10 解析;`mysql_native_password` / `caching_sha2_password`(含 0x03 fast auth、
6
+ * 0x04 full auth + RSA 公钥加密)。
7
+ * - 不设 `CLIENT_DEPRECATE_EOF`,结果集按 EOF 包边界解析。
8
+ * - 每连接用完即 `socket.destroy()`,不做连接池。
9
+ * - 只读实例在前置检查阶段拒绝写 SQL(不需要真实数据库就能拒绝)。
10
+ */
11
+ import net from 'node:net'
12
+ import crypto from 'node:crypto'
13
+
14
+ // ─────────────────────────── 协议常量 ───────────────────────────
15
+
16
+ const CLIENT_LONG_PASSWORD = 0x00000001
17
+ const CLIENT_CONNECT_WITH_DB = 0x00000008
18
+ const CLIENT_PROTOCOL_41 = 0x00000200
19
+ const CLIENT_SECURE_CONNECTION = 0x00008000
20
+ const CLIENT_PLUGIN_AUTH = 0x00080000
21
+
22
+ const COM_INIT_DB = 0x02
23
+ const COM_QUERY = 0x03
24
+
25
+ /** 45 = utf8mb4_general_ci(契约 §8 指定)。 */
26
+ const CHARSET_UTF8MB4 = 45
27
+ const MAX_PACKET_LENGTH = 0xffffff
28
+ const DEFAULT_QUERY_LIMIT = 200
29
+ const MAX_QUERY_LIMIT = 1000
30
+ const DEFAULT_TIMEOUT_MS = 8000
31
+
32
+ /** 只读模式下允许的 SQL 首关键字。 */
33
+ const READ_ONLY_PREFIXES = new Set(['select', 'show', 'desc', 'describe', 'explain', 'with'])
34
+
35
+ // ─────────────────────────── 错误与工具函数 ───────────────────────────
36
+
37
+ function userError(code, message) {
38
+ const error = new Error(message)
39
+ error.code = code
40
+ return error
41
+ }
42
+
43
+ /** 给任意 promise 加超时,超时消息统一成中文。 */
44
+ function withTimeout(promise, timeoutMs, message) {
45
+ let timer
46
+ const timeout = new Promise((_resolve, reject) => {
47
+ timer = setTimeout(() => reject(userError('connection-failed', message)), timeoutMs)
48
+ if (typeof timer.unref === 'function') timer.unref()
49
+ })
50
+ return Promise.race([promise, timeout]).finally(() => clearTimeout(timer))
51
+ }
52
+
53
+ function sha1(buffer) {
54
+ return crypto.createHash('sha1').update(buffer).digest()
55
+ }
56
+
57
+ function sha256(buffer) {
58
+ return crypto.createHash('sha256').update(buffer).digest()
59
+ }
60
+
61
+ /** 两段等长 buffer 逐字节 XOR(b 不够长时从头循环)。 */
62
+ function xorBuffers(left, right) {
63
+ const result = Buffer.allocUnsafe(left.length)
64
+ for (let index = 0; index < left.length; index += 1) {
65
+ result[index] = left[index] ^ right[index % right.length]
66
+ }
67
+ return result
68
+ }
69
+
70
+ /** 去掉 SQL 前导空白与注释,返回第一条语句的起始文本。 */
71
+ export function stripLeadingComments(sql) {
72
+ let text = String(sql ?? '')
73
+ let previous
74
+ do {
75
+ previous = text
76
+ text = text.replace(/^\s+/, '')
77
+ if (text.startsWith('--')) {
78
+ const end = text.indexOf('\n')
79
+ text = end < 0 ? '' : text.slice(end + 1)
80
+ continue
81
+ }
82
+ if (text.startsWith('#')) {
83
+ const end = text.indexOf('\n')
84
+ text = end < 0 ? '' : text.slice(end + 1)
85
+ continue
86
+ }
87
+ if (text.startsWith('/*')) {
88
+ const end = text.indexOf('*/', 2)
89
+ text = end < 0 ? '' : text.slice(end + 2)
90
+ continue
91
+ }
92
+ } while (text !== previous)
93
+ return text
94
+ }
95
+
96
+ /**
97
+ * 只读 SQL 校验:必须以 select/show/desc/describe/explain/with 开头(忽略前导注释与空白)。
98
+ * 该检查不建立连接,编辑态也能立刻拒绝。
99
+ */
100
+ export function assertReadOnlySql(sql) {
101
+ const text = stripLeadingComments(sql)
102
+ const match = /^([A-Za-z]+)/.exec(text)
103
+ const verb = match ? match[1].toLowerCase() : ''
104
+ if (!READ_ONLY_PREFIXES.has(verb)) {
105
+ throw userError(
106
+ 'read-only',
107
+ '该 MySQL 实例是只读模式:只允许 SELECT / SHOW / DESC / DESCRIBE / EXPLAIN / WITH 开头的语句。'
108
+ + '若确实需要写入,请用户在右侧「集成环境」面板关闭该实例的「只读」开关。',
109
+ )
110
+ }
111
+ return verb
112
+ }
113
+
114
+ /** 把网络层错误翻译成中文并保留可操作提示。 */
115
+ function mapNetError(error, host, port) {
116
+ if (error?.code === 'connection-failed' || error?.code === 'read-only' || error?.code === 'bad-request') {
117
+ return error
118
+ }
119
+ switch (error?.code) {
120
+ case 'ECONNREFUSED':
121
+ return userError('connection-failed', `无法连接 MySQL ${host}:${port}:连接被拒绝(服务未启动或端口不对)。`)
122
+ case 'ENOTFOUND':
123
+ case 'EAI_AGAIN':
124
+ return userError('connection-failed', `无法解析 MySQL 主机「${host}」,请检查地址是否正确。`)
125
+ case 'ETIMEDOUT':
126
+ case 'ESOCKETTIMEDOUT':
127
+ return userError('connection-failed', `连接 MySQL 超时:${host}:${port}`)
128
+ case 'ECONNRESET':
129
+ return userError('connection-failed', `MySQL 连接被重置:${host}:${port}(可能是服务端关闭了空闲连接)。`)
130
+ default:
131
+ break
132
+ }
133
+ return userError('connection-failed', `MySQL 连接失败(${host}:${port}):${error?.message ?? String(error)}`)
134
+ }
135
+
136
+ /** 服务端 ERR 包 → 中文错误(`stage` 是「认证失败」/「执行失败」等前缀)。 */
137
+ function serverError(payload, stage) {
138
+ const code = payload.length >= 3 ? payload.readUInt16LE(1) : 0
139
+ let offset = 3
140
+ let sqlstate = ''
141
+ if (payload[offset] === 0x23 && payload.length >= offset + 6) {
142
+ sqlstate = payload.toString('ascii', offset + 1, offset + 6)
143
+ offset += 6
144
+ }
145
+ const message = payload.toString('utf8', offset) || '(无错误信息)'
146
+ const sqlstatePart = sqlstate ? `(${sqlstate})` : ''
147
+ const hint = code === 1045
148
+ ? '(用户名或密码不正确)'
149
+ : code === 1044
150
+ ? '(该用户无权访问指定数据库)'
151
+ : ''
152
+ return userError('connection-failed', `${stage}:MySQL 错误 ${code}${sqlstatePart}:${message}${hint}`)
153
+ }
154
+
155
+ // ─────────────────────────── 长度编码(lenenc) ───────────────────────────
156
+
157
+ /** 读一个 lenenc 整数(0xfb 不在此处理)。 */
158
+ function readLenEncInt(payload, offset) {
159
+ if (offset >= payload.length) return { value: 0, offset }
160
+ const first = payload[offset]
161
+ if (first < 0xfb) return { value: first, offset: offset + 1 }
162
+ if (first === 0xfc) return { value: payload.readUInt16LE(offset + 1), offset: offset + 3 }
163
+ if (first === 0xfd) return { value: payload.readUIntLE(offset + 1, 3), offset: offset + 4 }
164
+ if (first === 0xfe) {
165
+ const value = payload.readBigUInt64LE(offset + 1)
166
+ return { value: value > BigInt(Number.MAX_SAFE_INTEGER) ? Number.MAX_SAFE_INTEGER : Number(value), offset: offset + 9 }
167
+ }
168
+ return { value: 0, offset: offset + 1 }
169
+ }
170
+
171
+ /** 读一个 lenenc 字符串;0xfb 返回 null。 */
172
+ function readLenEncString(payload, offset) {
173
+ if (offset >= payload.length) return { value: '', offset }
174
+ const first = payload[offset]
175
+ if (first === 0xfb) return { value: null, offset: offset + 1 }
176
+ const lengthInfo = readLenEncInt(payload, offset)
177
+ const start = lengthInfo.offset
178
+ const end = Math.min(payload.length, start + lengthInfo.value)
179
+ return { value: payload.toString('utf8', start, end), offset: end }
180
+ }
181
+
182
+ // ─────────────────────────── 认证 ───────────────────────────
183
+
184
+ /** mysql_native_password:SHA1(pwd) XOR SHA1(salt + SHA1(SHA1(pwd)))。 */
185
+ function nativeScramble(password, salt) {
186
+ if (!password) return Buffer.alloc(0)
187
+ const pwd = Buffer.from(password, 'utf8')
188
+ const stage1 = sha1(pwd)
189
+ const stage2 = sha1(stage1)
190
+ const stage3 = sha1(Buffer.concat([salt, stage2]))
191
+ return xorBuffers(stage1, stage3)
192
+ }
193
+
194
+ /** caching_sha2_password:SHA256(pwd) XOR SHA256(SHA256(SHA256(pwd)) + salt)。 */
195
+ function cachingSha2Scramble(password, salt) {
196
+ if (!password) return Buffer.alloc(0)
197
+ const pwd = Buffer.from(password, 'utf8')
198
+ const stage1 = sha256(pwd)
199
+ const stage2 = sha256(stage1)
200
+ const stage3 = sha256(stage2)
201
+ const salted = sha256(Buffer.concat([stage3, salt]))
202
+ return xorBuffers(stage1, salted)
203
+ }
204
+
205
+ /** 按插件名生成认证响应。 */
206
+ function buildAuthResponse(plugin, password, salt) {
207
+ switch (plugin) {
208
+ case 'caching_sha2_password':
209
+ return cachingSha2Scramble(password, salt)
210
+ case 'mysql_native_password':
211
+ return nativeScramble(password, salt)
212
+ case 'mysql_clear_password':
213
+ throw userError(
214
+ 'connection-failed',
215
+ 'MySQL 要求使用 mysql_clear_password(明文密码)插件,出于安全考虑本插件不支持;'
216
+ + '请改用 mysql_native_password 或 caching_sha2_password。',
217
+ )
218
+ default:
219
+ throw userError(
220
+ 'connection-failed',
221
+ `MySQL 认证插件「${plugin || '未知'}」暂不支持(支持 mysql_native_password / caching_sha2_password)。`,
222
+ )
223
+ }
224
+ }
225
+
226
+ /**
227
+ * caching_sha2_password full auth:password+'\0' 与 salt 循环 XOR,再用服务端 PEM 公钥加密。
228
+ */
229
+ function encryptPasswordWithPublicKey(password, salt, pem) {
230
+ const plain = Buffer.from(`${password}\0`, 'utf8')
231
+ const xored = Buffer.allocUnsafe(plain.length)
232
+ for (let index = 0; index < plain.length; index += 1) {
233
+ xored[index] = plain[index] ^ salt[index % salt.length]
234
+ }
235
+ return crypto.publicEncrypt(
236
+ { key: pem, padding: crypto.constants.RSA_PKCS1_OAEP_PADDING, oaepHash: 'sha1' },
237
+ xored,
238
+ )
239
+ }
240
+
241
+ /** 解析握手 v10 包。 */
242
+ function parseHandshake(payload) {
243
+ if (payload.length < 1) throw userError('connection-failed', 'MySQL 握手包为空')
244
+ const protocolVersion = payload[0]
245
+ if (protocolVersion !== 0x0a && protocolVersion !== 0x09) {
246
+ throw userError('connection-failed', `不支持的 MySQL 协议版本:${protocolVersion}`)
247
+ }
248
+ let offset = 1
249
+ const versionEnd = payload.indexOf(0, offset)
250
+ if (versionEnd < 0) throw userError('connection-failed', 'MySQL 握手包缺少 server version')
251
+ const serverVersion = payload.toString('utf8', offset, versionEnd)
252
+ offset = versionEnd + 1
253
+ offset += 4 // connection id
254
+ if (payload.length < offset + 8) throw userError('connection-failed', 'MySQL 握手包不完整')
255
+ const salt1 = payload.subarray(offset, offset + 8)
256
+ offset += 8
257
+ offset += 1 // filler
258
+ if (payload.length < offset + 2) throw userError('connection-failed', 'MySQL 握手包不完整')
259
+ const capabilitiesLower = payload.readUInt16LE(offset)
260
+ offset += 2
261
+ const charset = payload[offset] ?? CHARSET_UTF8MB4
262
+ offset += 1
263
+ offset += 2 // status flags
264
+ const capabilitiesUpper = payload.length >= offset + 2 ? payload.readUInt16LE(offset) : 0
265
+ offset += 2
266
+ const authPluginDataLength = payload[offset] ?? 0
267
+ offset += 1
268
+ offset += 10 // reserved
269
+ const capabilities = (capabilitiesUpper << 16) | capabilitiesLower
270
+ // 第二段 salt:长度 max(13, len-8),以 0x00 结尾。
271
+ const wantSalt = authPluginDataLength > 8 ? authPluginDataLength - 8 : 12
272
+ const salt2 = []
273
+ while (salt2.length < wantSalt && offset < payload.length) {
274
+ const byte = payload[offset]
275
+ offset += 1
276
+ if (byte === 0) break
277
+ salt2.push(byte)
278
+ }
279
+ while (offset < payload.length && payload[offset] === 0) offset += 1
280
+ let pluginName = ''
281
+ if (capabilities & CLIENT_PLUGIN_AUTH) {
282
+ let end = payload.indexOf(0, offset)
283
+ if (end < 0) end = payload.length
284
+ pluginName = payload.toString('utf8', offset, end)
285
+ offset = end + 1
286
+ }
287
+ return {
288
+ protocolVersion,
289
+ serverVersion,
290
+ capabilities,
291
+ charset,
292
+ authPluginDataLength,
293
+ salt: Buffer.concat([salt1, Buffer.from(salt2)]),
294
+ pluginName,
295
+ }
296
+ }
297
+
298
+ /** 解析 AuthSwitchRequest(0xfe + 插件名 \0 + salt)。 */
299
+ function parseAuthSwitch(payload) {
300
+ let offset = 1
301
+ let end = payload.indexOf(0, offset)
302
+ if (end < 0) end = payload.length
303
+ const plugin = payload.toString('utf8', offset, end)
304
+ offset = end + 1
305
+ let salt = payload.subarray(offset)
306
+ let saltEnd = salt.length
307
+ while (saltEnd > 0 && salt[saltEnd - 1] === 0) saltEnd -= 1
308
+ salt = salt.subarray(0, saltEnd)
309
+ return { plugin, salt }
310
+ }
311
+
312
+ // ─────────────────────────── 封包流 ───────────────────────────
313
+
314
+ /** 把 TCP 字节流切成 MySQL 包,并处理 >16MB 的续包。 */
315
+ class PacketStream {
316
+ constructor(socket) {
317
+ this.socket = socket
318
+ this.buffer = Buffer.alloc(0)
319
+ this.packets = []
320
+ this.waiters = []
321
+ this.failure = null
322
+ this.pendingChunks = []
323
+ this.pendingLength = -1
324
+ socket.on('data', (chunk) => {
325
+ if (this.failure) return
326
+ this.buffer = this.buffer.length === 0 ? chunk : Buffer.concat([this.buffer, chunk])
327
+ this.pump()
328
+ })
329
+ socket.on('error', (error) => this.fail(error))
330
+ socket.on('close', () => this.fail(userError('connection-failed', 'MySQL 连接已关闭')))
331
+ }
332
+
333
+ fail(error) {
334
+ if (this.failure) return
335
+ this.failure = error
336
+ const waiters = this.waiters
337
+ this.waiters = []
338
+ for (const waiter of waiters) waiter.reject(error)
339
+ }
340
+
341
+ deliver(packet) {
342
+ const waiter = this.waiters.shift()
343
+ if (waiter) waiter.resolve(packet)
344
+ else this.packets.push(packet)
345
+ }
346
+
347
+ pump() {
348
+ for (;;) {
349
+ if (this.failure) return
350
+ if (this.buffer.length < 4) return
351
+ const length = this.buffer.readUIntLE(0, 3)
352
+ if (this.buffer.length < 4 + length) return
353
+ const sequence = this.buffer[3]
354
+ const payload = this.buffer.subarray(4, 4 + length)
355
+ this.buffer = this.buffer.subarray(4 + length)
356
+ if (this.pendingLength >= 0) {
357
+ this.pendingChunks.push(payload)
358
+ this.pendingLength += length
359
+ if (length < MAX_PACKET_LENGTH) {
360
+ const full = Buffer.concat(this.pendingChunks)
361
+ this.pendingChunks = []
362
+ this.pendingLength = -1
363
+ this.deliver({ sequence, payload: full })
364
+ }
365
+ continue
366
+ }
367
+ if (length === MAX_PACKET_LENGTH) {
368
+ this.pendingLength = length
369
+ this.pendingChunks = [payload]
370
+ continue
371
+ }
372
+ this.deliver({ sequence, payload })
373
+ }
374
+ }
375
+
376
+ next() {
377
+ if (this.packets.length > 0) return Promise.resolve(this.packets.shift())
378
+ if (this.failure) return Promise.reject(this.failure)
379
+ return new Promise((resolve, reject) => this.waiters.push({ resolve, reject }))
380
+ }
381
+ }
382
+
383
+ // ─────────────────────────── 连接 ───────────────────────────
384
+
385
+ class MysqlConnection {
386
+ constructor(options) {
387
+ this.host = options.host
388
+ this.port = options.port
389
+ this.user = options.user
390
+ this.password = options.password ?? ''
391
+ this.database = options.database ?? ''
392
+ this.socket = null
393
+ this.stream = null
394
+ this.sequence = 0
395
+ this.serverVersion = ''
396
+ }
397
+
398
+ /** 建立 TCP、完成握手与认证;失败抛已翻译的错误。 */
399
+ async open() {
400
+ const socket = net.createConnection({ host: this.host, port: this.port })
401
+ this.socket = socket
402
+ this.stream = new PacketStream(socket)
403
+ socket.setNoDelay(true)
404
+ try {
405
+ await new Promise((resolve, reject) => {
406
+ socket.once('connect', resolve)
407
+ socket.once('error', reject)
408
+ })
409
+ const handshakePacket = await this.nextPacket()
410
+ const handshake = parseHandshake(handshakePacket.payload)
411
+ this.serverVersion = handshake.serverVersion
412
+ await this.authenticate(handshake)
413
+ } catch (error) {
414
+ throw mapNetError(error, this.host, this.port)
415
+ }
416
+ }
417
+
418
+ /** 发送一个客户端包(长度<16MB 足够 SQL 场景)。 */
419
+ send(payload) {
420
+ if (payload.length > MAX_PACKET_LENGTH) {
421
+ throw userError('bad-request', 'SQL 语句过长(超过 16MB),暂不支持。')
422
+ }
423
+ const header = Buffer.allocUnsafe(4)
424
+ header.writeUIntLE(payload.length, 0, 3)
425
+ header[3] = this.sequence
426
+ this.sequence = (this.sequence + 1) & 0xff
427
+ this.socket.write(Buffer.concat([header, payload]))
428
+ }
429
+
430
+ async nextPacket() {
431
+ const packet = await this.stream.next()
432
+ this.sequence = (packet.sequence + 1) & 0xff
433
+ return packet
434
+ }
435
+
436
+ /** 构造 HandshakeResponse41。 */
437
+ buildHandshakeResponse(handshake, authResponse) {
438
+ let capabilities = CLIENT_LONG_PASSWORD | CLIENT_PROTOCOL_41 | CLIENT_SECURE_CONNECTION | CLIENT_PLUGIN_AUTH
439
+ if (this.database) capabilities |= CLIENT_CONNECT_WITH_DB
440
+ const header = Buffer.alloc(4 + 4 + 1 + 23)
441
+ header.writeUInt32LE(capabilities >>> 0, 0)
442
+ header.writeUInt32LE(0x01000000, 4)
443
+ header[8] = CHARSET_UTF8MB4
444
+ // 后面 23 字节 filler 保持 0。
445
+ const chunks = [
446
+ header,
447
+ Buffer.from(this.user, 'utf8'),
448
+ Buffer.from([0]),
449
+ Buffer.from([authResponse.length]),
450
+ authResponse,
451
+ ]
452
+ if (this.database) chunks.push(Buffer.from(this.database, 'utf8'), Buffer.from([0]))
453
+ chunks.push(Buffer.from(handshake.pluginName || 'mysql_native_password', 'utf8'), Buffer.from([0]))
454
+ return Buffer.concat(chunks)
455
+ }
456
+
457
+ async authenticate(handshake) {
458
+ let plugin = handshake.pluginName || 'mysql_native_password'
459
+ let salt = handshake.salt
460
+ let authResponse
461
+ try {
462
+ authResponse = buildAuthResponse(plugin, this.password, salt)
463
+ } catch (error) {
464
+ throw mapNetError(error, this.host, this.port)
465
+ }
466
+ this.send(this.buildHandshakeResponse(handshake, authResponse))
467
+ for (;;) {
468
+ const packet = await this.nextPacket()
469
+ const payload = packet.payload
470
+ if (payload.length === 0) continue
471
+ const first = payload[0]
472
+ if (first === 0x00) return
473
+ if (first === 0xff) throw serverError(payload, 'MySQL 认证失败')
474
+ if (first === 0xfe) {
475
+ // AuthSwitchRequest:换插件后重发响应。
476
+ const switched = parseAuthSwitch(payload)
477
+ plugin = switched.plugin
478
+ salt = switched.salt
479
+ this.send(buildAuthResponse(plugin, this.password, salt))
480
+ continue
481
+ }
482
+ if (first === 0x01) {
483
+ const data = payload.subarray(1)
484
+ if (data.length === 0) continue
485
+ if (data[0] === 0x03) {
486
+ // fast auth success,下一包通常是 OK。
487
+ continue
488
+ }
489
+ if (data[0] === 0x04) {
490
+ // full auth:请求公钥(本实现不走 TLS)。
491
+ this.send(Buffer.from([0x02]))
492
+ const keyPacket = await this.nextPacket()
493
+ if (keyPacket.payload[0] === 0xff) throw serverError(keyPacket.payload, 'MySQL 认证失败')
494
+ const pem = keyPacket.payload[0] === 0x01
495
+ ? keyPacket.payload.subarray(1).toString('utf8')
496
+ : keyPacket.payload.toString('utf8')
497
+ this.send(encryptPasswordWithPublicKey(this.password, salt, pem))
498
+ continue
499
+ }
500
+ if (data[0] === 0x2d) {
501
+ // 少数服务端直接回 PEM。
502
+ this.send(encryptPasswordWithPublicKey(this.password, salt, data.toString('utf8')))
503
+ continue
504
+ }
505
+ continue
506
+ }
507
+ throw userError('connection-failed', `MySQL 认证失败:收到无法识别的认证报文(0x${first.toString(16)})`)
508
+ }
509
+ }
510
+
511
+ /** COM_INIT_DB:切换数据库(payload.database 覆盖实例默认库时用)。 */
512
+ async useDatabase(database) {
513
+ // 认证结束后,每个命令包的序号必须从 0 重新开始,否则服务端回 1156 Got packets out of order。
514
+ this.sequence = 0
515
+ this.send(Buffer.concat([Buffer.from([COM_INIT_DB]), Buffer.from(database, 'utf8')]))
516
+ const packet = await this.nextPacket()
517
+ if (packet.payload[0] === 0xff) throw serverError(packet.payload, 'MySQL 切换数据库失败')
518
+ }
519
+
520
+ /**
521
+ * 执行一条 SQL,返回 `{ columns, rows, truncated, affectedRows? }`。
522
+ * 行数达到 limit 时停止读取并标记 truncated。
523
+ */
524
+ async query(sql, limit) {
525
+ // 同上:新命令的包序号从 0 起算(握手/认证用的序号不延续到命令阶段)。
526
+ this.sequence = 0
527
+ this.send(Buffer.concat([Buffer.from([COM_QUERY]), Buffer.from(sql, 'utf8')]))
528
+ const first = await this.nextPacket()
529
+ const firstByte = first.payload[0]
530
+ if (firstByte === 0xff) throw serverError(first.payload, 'MySQL 执行失败')
531
+ if (firstByte === 0x00) {
532
+ const ok = this.parseOk(first.payload)
533
+ return { columns: [], rows: [], truncated: false, affectedRows: ok.affectedRows }
534
+ }
535
+ const columnCount = readLenEncInt(first.payload, 0).value
536
+ const columns = []
537
+ for (let index = 0; index < columnCount; index += 1) {
538
+ const packet = await this.nextPacket()
539
+ if (packet.payload[0] === 0xff) throw serverError(packet.payload, 'MySQL 执行失败')
540
+ columns.push(parseColumnName(packet.payload))
541
+ }
542
+ await this.readEof()
543
+ const rows = []
544
+ let truncated = false
545
+ for (;;) {
546
+ const packet = await this.nextPacket()
547
+ const payload = packet.payload
548
+ const byte = payload[0]
549
+ if (byte === 0xfe && payload.length < 9) break
550
+ if (byte === 0xff) throw serverError(payload, 'MySQL 执行失败')
551
+ rows.push(parseTextRow(payload, columnCount))
552
+ if (rows.length >= limit) {
553
+ const next = await this.nextPacket()
554
+ const nextByte = next.payload[0]
555
+ if (nextByte === 0xff) throw serverError(next.payload, 'MySQL 执行失败')
556
+ const ended = nextByte === 0xfe && next.payload.length < 9
557
+ truncated = !ended
558
+ break
559
+ }
560
+ }
561
+ return { columns, rows, truncated }
562
+ }
563
+
564
+ parseOk(payload) {
565
+ let offset = 1
566
+ const affected = readLenEncInt(payload, offset)
567
+ offset = affected.offset
568
+ const inserted = readLenEncInt(payload, offset)
569
+ return { affectedRows: affected.value, lastInsertId: inserted.value }
570
+ }
571
+
572
+ async readEof() {
573
+ const packet = await this.nextPacket()
574
+ if (packet.payload[0] === 0xff) throw serverError(packet.payload, 'MySQL 执行失败')
575
+ // 0xfe EOF;若服务端仍发 OK(0x00) 也接受。
576
+ return packet
577
+ }
578
+
579
+ destroy() {
580
+ try {
581
+ this.socket?.destroy()
582
+ } catch {
583
+ // 忽略销毁异常。
584
+ }
585
+ }
586
+ }
587
+
588
+ /** 读取 column definition 里的列名(第 5 个 lenenc 字符串)。 */
589
+ function parseColumnName(payload) {
590
+ let offset = 0
591
+ let name = ''
592
+ for (let index = 0; index < 5; index += 1) {
593
+ const item = readLenEncString(payload, offset)
594
+ if (index === 4) name = item.value ?? ''
595
+ offset = item.offset
596
+ if (offset >= payload.length) break
597
+ }
598
+ return name
599
+ }
600
+
601
+ /** 一行文本结果集:lenenc 字符串,0xfb 表示 NULL。 */
602
+ function parseTextRow(payload, columnCount) {
603
+ const values = []
604
+ let offset = 0
605
+ for (let index = 0; index < columnCount; index += 1) {
606
+ if (offset >= payload.length) {
607
+ values.push(null)
608
+ continue
609
+ }
610
+ if (payload[offset] === 0xfb) {
611
+ values.push(null)
612
+ offset += 1
613
+ continue
614
+ }
615
+ const item = readLenEncString(payload, offset)
616
+ values.push(convertValue(item.value))
617
+ offset = item.offset
618
+ }
619
+ return values
620
+ }
621
+
622
+ /** 文本协议值:能安全转数字就转,超出安全整数保持字符串,NULL → null。 */
623
+ export function convertValue(text) {
624
+ if (text === null || text === undefined) return null
625
+ if (text === '') return ''
626
+ if (/^[+-]?\d+$/.test(text)) {
627
+ const number = Number(text)
628
+ return Number.isSafeInteger(number) ? number : text
629
+ }
630
+ if (/^[+-]?(?:\d+\.\d*|\.\d+)(?:[eE][+-]?\d+)?$/.test(text)) {
631
+ const number = Number(text)
632
+ return Number.isFinite(number) && Math.abs(number) < 1e15 ? number : text
633
+ }
634
+ return text
635
+ }
636
+
637
+ function escapeIdentifier(name) {
638
+ return String(name).replace(/`/g, '``')
639
+ }
640
+
641
+ function clampLimit(value) {
642
+ const number = Number(value)
643
+ if (!Number.isFinite(number)) return DEFAULT_QUERY_LIMIT
644
+ return Math.min(MAX_QUERY_LIMIT, Math.max(1, Math.trunc(number)))
645
+ }
646
+
647
+ /**
648
+ * 连接器统一入口:`run(instance, payload)` → 结果对象;失败抛 Error。
649
+ * @param instance - 存储态实例(含明文 config)。
650
+ * @param payload - `{ action, sql?, database?, table?, limit? }`。
651
+ */
652
+ export async function runMysql(instance, payload = {}) {
653
+ const config = instance?.config ?? {}
654
+ const host = String(config.host ?? '').trim()
655
+ if (!host) throw userError('bad-request', `实例「${instance?.name ?? ''}」缺少主机地址,请先在面板里补全。`)
656
+ const port = Number(config.port ?? 3306)
657
+ if (!Number.isFinite(port) || port <= 0) {
658
+ throw userError('bad-request', `实例「${instance?.name ?? ''}」的端口不合法:${config.port}`)
659
+ }
660
+ const user = String(config.user ?? '').trim()
661
+ if (!user) throw userError('bad-request', `实例「${instance?.name ?? ''}」缺少用户名,请先在面板里补全。`)
662
+ const action = String(payload.action ?? 'query')
663
+ const limit = clampLimit(payload.limit)
664
+ const defaultDatabase = String(config.database ?? '').trim()
665
+ const overrideDatabase = String(payload.database ?? '').trim()
666
+ const effectiveDatabase = overrideDatabase || defaultDatabase
667
+
668
+ let sql
669
+ switch (action) {
670
+ case 'query': {
671
+ sql = String(payload.sql ?? '').trim()
672
+ if (!sql) throw userError('bad-request', 'query 动作需要 sql 参数。')
673
+ if (config.readOnly !== false) assertReadOnlySql(sql)
674
+ break
675
+ }
676
+ case 'databases':
677
+ sql = 'SHOW DATABASES'
678
+ break
679
+ case 'tables':
680
+ sql = 'SHOW TABLES'
681
+ break
682
+ case 'describe': {
683
+ const table = String(payload.table ?? payload.sql ?? '').trim()
684
+ if (!table) throw userError('bad-request', 'describe 动作需要 table 或 sql 参数(表名)。')
685
+ sql = `DESCRIBE \`${escapeIdentifier(table)}\``
686
+ break
687
+ }
688
+ default:
689
+ throw userError('bad-request', `未知的 mysql 动作「${action}」,可用:query / databases / tables / describe。`)
690
+ }
691
+
692
+ const connection = new MysqlConnection({
693
+ host,
694
+ port,
695
+ user,
696
+ password: String(config.password ?? ''),
697
+ database: defaultDatabase,
698
+ })
699
+ const timeoutMs = Number(payload.timeoutMs) > 0 ? Number(payload.timeoutMs) : DEFAULT_TIMEOUT_MS
700
+ try {
701
+ const result = await withTimeout(
702
+ (async () => {
703
+ await connection.open()
704
+ if (overrideDatabase && overrideDatabase !== defaultDatabase) {
705
+ await connection.useDatabase(overrideDatabase)
706
+ }
707
+ return connection.query(sql, limit)
708
+ })(),
709
+ timeoutMs,
710
+ `连接 MySQL 超时(${timeoutMs}ms):${host}:${port}`,
711
+ )
712
+ return {
713
+ columns: result.columns,
714
+ rows: result.rows,
715
+ rowCount: result.rows.length,
716
+ truncated: result.truncated,
717
+ database: effectiveDatabase,
718
+ ...(result.affectedRows === undefined ? {} : { affectedRows: result.affectedRows }),
719
+ }
720
+ } finally {
721
+ connection.destroy()
722
+ }
723
+ }