srvprice-cli 0.0.0-stage → 0.1.0

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.
@@ -0,0 +1,634 @@
1
+ 'use strict';
2
+
3
+ // 多厂商安全组「开端口」适配器(2026-11-21 第二期)。
4
+ // 红线(派单):只新建专用安全组 + 加规则;不修改现有组、不绑定实例、不 deploy。
5
+ // 所有写操作默认不执行,由 bin 的 --dry-run/--yes 闸门控制;本模块只提供命令构造与解析。
6
+ //
7
+ // 三家 CLI 均以 JSON 输出;参数名按 2026-11-21 的 --help 核实。
8
+
9
+ const { spawn } = require('child_process');
10
+ const fs = require('fs');
11
+
12
+ // Windows 上 jdc 是 .cmd 包了一层 py311 的 jdc.exe;直接 spawn .cmd 会 ENOENT。
13
+ // 路径因机器而异,这里只留可执行名兜底,实际路径用环境变量指定:
14
+ // SRVPRICE_JDC_BIN / SRVPRICE_CTYUN_BIN
15
+ const KNOWN_BIN = {
16
+ jdc: process.env.SRVPRICE_JDC_BIN ? [process.env.SRVPRICE_JDC_BIN] : ['jdc'],
17
+ 'ctyun-cli': process.env.SRVPRICE_CTYUN_BIN ? [process.env.SRVPRICE_CTYUN_BIN] : ['ctyun-cli']
18
+ };
19
+
20
+ function resolveBin(bin) {
21
+ if (process.env[`SRVPRICE_BIN_${String(bin).toUpperCase()}`]) {
22
+ return process.env[`SRVPRICE_BIN_${String(bin).toUpperCase()}`];
23
+ }
24
+ for (const c of KNOWN_BIN[bin] || []) {
25
+ if (fs.existsSync(c)) return c;
26
+ }
27
+ return bin;
28
+ }
29
+
30
+ function run(bin, args, opts = {}) {
31
+ bin = resolveBin(bin);
32
+ const timeout = opts.timeout || 60000;
33
+ return new Promise((resolve, reject) => {
34
+ const child = spawn(bin, args, {
35
+ env: Object.assign({}, process.env, opts.env || {}),
36
+ windowsHide: true
37
+ });
38
+ let out = '';
39
+ let err = '';
40
+ const timer = setTimeout(() => {
41
+ try { child.kill(); } catch (_) { /* noop */ }
42
+ reject(new Error(`${bin} ${args[0] || ''} 超时(${timeout}ms)`));
43
+ }, timeout);
44
+ child.stdout.on('data', (d) => { out += d; });
45
+ child.stderr.on('data', (d) => { err += d; });
46
+ child.on('error', (e) => { clearTimeout(timer); reject(e); });
47
+ child.on('close', (code) => {
48
+ clearTimeout(timer);
49
+ if (code !== 0) {
50
+ const msg = (err || out || '').trim().split('\n').slice(0, 3).join(' ').slice(0, 300);
51
+ reject(new Error(`${bin} 退出码 ${code}:${msg || '(无输出)'}`));
52
+ return;
53
+ }
54
+ resolve({ stdout: out, stderr: err });
55
+ });
56
+ });
57
+ }
58
+
59
+ function parseJson(text, what) {
60
+ const t = String(text || '').trim();
61
+ if (!t) throw new Error(`${what} 没有输出`);
62
+ try { return JSON.parse(t); } catch (_) {
63
+ throw new Error(`${what} 返回非 JSON:${t.slice(0, 200)}`);
64
+ }
65
+ }
66
+
67
+ function normalizeCidr(source) {
68
+ return source.includes('/') ? source : `${source}/32`;
69
+ }
70
+
71
+ // 组名/描述只允许 ASCII(火山/阿里对中文名有限制,且跨 CLI 解析易出问题)
72
+ function groupNameFor(ip, port) {
73
+ return `srvprice-${ip.replace(/\./g, '-')}-${port}`;
74
+ }
75
+
76
+ function arr(v) {
77
+ return Array.isArray(v) ? v : [];
78
+ }
79
+
80
+ // ---------------------------------------------------------------------------
81
+ // 阿里云
82
+ // ---------------------------------------------------------------------------
83
+ const aliyun = {
84
+ id: 'aliyun',
85
+ bin: 'aliyun',
86
+ needsRegion: true,
87
+ _base(ctx) {
88
+ return ctx.vendorProfile ? ['--profile', ctx.vendorProfile] : [];
89
+ },
90
+ async serverByIp(ctx, ip) {
91
+ const { stdout } = await run('aliyun', [
92
+ 'ecs', 'DescribeInstances',
93
+ '--RegionId', ctx.region,
94
+ '--PageSize', '100',
95
+ ...this._base(ctx)
96
+ ], ctx);
97
+ const j = parseJson(stdout, 'aliyun DescribeInstances');
98
+ const list = arr(j.Instances && j.Instances.Instance);
99
+ const hit = list.find((it) => {
100
+ const pub = arr(it.PublicIpAddress && it.PublicIpAddress.IpAddress);
101
+ const eip = it.EipAddress && it.EipAddress.IpAddress;
102
+ return pub.includes(ip) || eip === ip;
103
+ });
104
+ if (!hit) return null;
105
+ return {
106
+ id: hit.InstanceId,
107
+ name: hit.InstanceName || hit.InstanceId,
108
+ region: hit.RegionId || ctx.region,
109
+ vpcId: hit.VpcAttributes && hit.VpcAttributes.VpcId || null
110
+ };
111
+ },
112
+ async listGroups(ctx) {
113
+ const { stdout } = await run('aliyun', [
114
+ 'ecs', 'DescribeSecurityGroups',
115
+ '--RegionId', ctx.region,
116
+ '--PageSize', '100',
117
+ ...this._base(ctx)
118
+ ], ctx);
119
+ const j = parseJson(stdout, 'aliyun DescribeSecurityGroups');
120
+ return arr(j.SecurityGroups && j.SecurityGroups.SecurityGroup).map((g) => ({
121
+ id: g.SecurityGroupId,
122
+ name: g.SecurityGroupName,
123
+ vpcId: g.VpcId || null
124
+ }));
125
+ },
126
+ async listRules(ctx, gid) {
127
+ const { stdout } = await run('aliyun', [
128
+ 'ecs', 'DescribeSecurityGroupAttribute',
129
+ '--RegionId', ctx.region,
130
+ '--SecurityGroupId', gid,
131
+ ...this._base(ctx)
132
+ ], ctx);
133
+ const j = parseJson(stdout, 'aliyun DescribeSecurityGroupAttribute');
134
+ return arr(j.Permissions && j.Permissions.Permission).map((r) => ({
135
+ proto: String(r.IpProtocol || '').toLowerCase(),
136
+ port: String(r.PortRange || '').split('/')[0],
137
+ source: r.SourceCidrIp || null,
138
+ action: String(r.Policy || '').toLowerCase(),
139
+ priority: r.Priority !== undefined ? Number(r.Priority) : null
140
+ }));
141
+ },
142
+ createArgs(ctx, server, name, description) {
143
+ const a = ['ecs', 'CreateSecurityGroup', '--RegionId', ctx.region, '--VpcId', server.vpcId];
144
+ if (name) a.push('--SecurityGroupName', name);
145
+ if (description) a.push('--Description', description);
146
+ return a.concat(this._base(ctx));
147
+ },
148
+ addRuleArgs(ctx, gid, rule) {
149
+ return [
150
+ 'ecs', 'AuthorizeSecurityGroup',
151
+ '--RegionId', ctx.region,
152
+ '--SecurityGroupId', gid,
153
+ '--Permissions.0.IpProtocol', rule.proto,
154
+ '--Permissions.0.PortRange', `${rule.port}/${rule.port}`,
155
+ '--Permissions.0.SourceCidrIp', normalizeCidr(rule.source),
156
+ '--Permissions.0.Policy', 'accept',
157
+ // 数字越小优先级越高:默认放低(100),避免抢占现有规则
158
+ '--Permissions.0.Priority', String(Math.min(100, Math.max(1, rule.priority || 100))),
159
+ ...this._base(ctx)
160
+ ];
161
+ },
162
+ groupIdFrom(createOut) {
163
+ const j = parseJson(createOut, 'aliyun CreateSecurityGroup');
164
+ return j.SecurityGroupId || null;
165
+ }
166
+ };
167
+
168
+ // ---------------------------------------------------------------------------
169
+ // 腾讯云
170
+ // ---------------------------------------------------------------------------
171
+ const tencent = {
172
+ id: 'tencent',
173
+ bin: 'tccli',
174
+ needsRegion: true,
175
+ _base(ctx) {
176
+ const a = [];
177
+ if (ctx.region) a.push('--region', ctx.region);
178
+ if (ctx.vendorProfile) a.push('--profile', ctx.vendorProfile);
179
+ return a;
180
+ },
181
+ async serverByIp(ctx, ip) {
182
+ const { stdout } = await run('tccli', [
183
+ 'cvm', 'DescribeInstances', '--Limit', '100', ...this._base(ctx)
184
+ ], ctx);
185
+ const j = parseJson(stdout, 'tccli DescribeInstances');
186
+ const hit = arr(j.InstanceSet).find((it) => arr(it.PublicIpAddresses).includes(ip));
187
+ if (!hit) return null;
188
+ return {
189
+ id: hit.InstanceId,
190
+ name: hit.InstanceName || hit.InstanceId,
191
+ region: hit.Placement && hit.Placement.Zone ? String(hit.Placement.Zone).replace(/\d+$/, '') : ctx.region,
192
+ vpcId: hit.VirtualPrivateCloud && hit.VirtualPrivateCloud.VpcId || null
193
+ };
194
+ },
195
+ async listGroups(ctx) {
196
+ const { stdout } = await run('tccli', ['vpc', 'DescribeSecurityGroups', ...this._base(ctx)], ctx);
197
+ const j = parseJson(stdout, 'tccli DescribeSecurityGroups');
198
+ return arr(j.SecurityGroupSet).map((g) => ({
199
+ id: g.SecurityGroupId,
200
+ name: g.SecurityGroupName,
201
+ vpcId: g.VpcId || null
202
+ }));
203
+ },
204
+ async listRules(ctx, gid) {
205
+ const { stdout } = await run('tccli', ['vpc', 'DescribeSecurityGroupPolicies', '--SecurityGroupId', gid, ...this._base(ctx)], ctx);
206
+ const j = parseJson(stdout, 'tccli DescribeSecurityGroupPolicies');
207
+ const set = j.SecurityGroupPolicySet || {};
208
+ return arr(set.Ingress).map((r) => ({
209
+ proto: String(r.Protocol || '').toLowerCase(),
210
+ port: String(r.Port || '').split(/[-/]/)[0],
211
+ source: r.CidrBlock || null,
212
+ action: String(r.Action || '').toLowerCase(),
213
+ priority: r.PolicyIndex !== undefined ? Number(r.PolicyIndex) : null
214
+ }));
215
+ },
216
+ createArgs(ctx, server, name, description) {
217
+ const a = ['vpc', 'CreateSecurityGroup', '--GroupName', name, '--GroupDescription', description, ...this._base(ctx)];
218
+ return a;
219
+ },
220
+ addRuleArgs(ctx, gid, rule) {
221
+ const set = {
222
+ Ingress: [{
223
+ Protocol: rule.proto,
224
+ Port: String(rule.port),
225
+ CidrBlock: normalizeCidr(rule.source),
226
+ Action: 'ACCEPT',
227
+ PolicyDescription: 'srvprice open-port'
228
+ }]
229
+ };
230
+ return ['vpc', 'CreateSecurityGroupPolicies', '--SecurityGroupId', gid,
231
+ '--SecurityGroupPolicySet', JSON.stringify(set), ...this._base(ctx)];
232
+ },
233
+ groupIdFrom(createOut) {
234
+ const j = parseJson(createOut, 'tccli CreateSecurityGroup');
235
+ return (j.SecurityGroup && j.SecurityGroup.SecurityGroupId) || null;
236
+ }
237
+ };
238
+
239
+ // ---------------------------------------------------------------------------
240
+ // 火山引擎
241
+ // ---------------------------------------------------------------------------
242
+ const volcengine = {
243
+ id: 'volcengine',
244
+ bin: 've',
245
+ needsRegion: true,
246
+ _base(ctx) {
247
+ const a = [];
248
+ if (ctx.region) a.push('--region', ctx.region);
249
+ if (ctx.vendorProfile) a.push('--profile', ctx.vendorProfile);
250
+ return a;
251
+ },
252
+ async serverByIp(ctx, ip) {
253
+ const { stdout } = await run('ve', ['ecs', 'DescribeInstances', '--MaxResults', '100', ...this._base(ctx)], ctx);
254
+ const j = parseJson(stdout, 've DescribeInstances');
255
+ const res = j.Result || j.result || {};
256
+ const hit = arr(res.Instances).find((it) => {
257
+ const eip = it.EipAddress && it.EipAddress.IpAddress;
258
+ const pub = it.PublicIpAddress || null;
259
+ return eip === ip || pub === ip;
260
+ });
261
+ if (!hit) return null;
262
+ return {
263
+ id: hit.InstanceId,
264
+ name: hit.InstanceName || hit.InstanceId,
265
+ region: hit.RegionId || ctx.region,
266
+ vpcId: hit.VpcId || null,
267
+ zoneId: hit.ZoneId || null
268
+ };
269
+ },
270
+ async listGroups(ctx) {
271
+ const { stdout } = await run('ve', ['vpc', 'DescribeSecurityGroups', '--MaxResults', '100', ...this._base(ctx)], ctx);
272
+ const j = parseJson(stdout, 've DescribeSecurityGroups');
273
+ const res = j.Result || j.result || {};
274
+ return arr(res.SecurityGroups || res.SecurityGroupSet).map((g) => ({
275
+ id: g.SecurityGroupId,
276
+ name: g.SecurityGroupName,
277
+ vpcId: g.VpcId || null
278
+ }));
279
+ },
280
+ async listRules(ctx, gid) {
281
+ const { stdout } = await run('ve', ['vpc', 'DescribeSecurityGroupAttributes', '--SecurityGroupId', gid, ...this._base(ctx)], ctx);
282
+ const j = parseJson(stdout, 've DescribeSecurityGroupAttributes');
283
+ const res = j.Result || j.result || {};
284
+ return arr(res.Permissions).map((r) => ({
285
+ proto: String(r.Protocol || '').toLowerCase(),
286
+ port: r.PortStart !== undefined ? String(r.PortStart) : null,
287
+ source: r.CidrIp || null,
288
+ action: String(r.Policy || '').toLowerCase(),
289
+ priority: r.Priority !== undefined ? Number(r.Priority) : null
290
+ }));
291
+ },
292
+ createArgs(ctx, server, name, description) {
293
+ const a = ['vpc', 'CreateSecurityGroup', '--VpcId', server.vpcId];
294
+ if (name) a.push('--SecurityGroupName', name);
295
+ if (description) a.push('--Description', description);
296
+ return a.concat(this._base(ctx));
297
+ },
298
+ addRuleArgs(ctx, gid, rule) {
299
+ return [
300
+ 'vpc', 'AuthorizeSecurityGroupIngress',
301
+ '--SecurityGroupId', gid,
302
+ '--Protocol', rule.proto,
303
+ '--PortStart', String(rule.port),
304
+ '--PortEnd', String(rule.port),
305
+ '--CidrIp', normalizeCidr(rule.source),
306
+ '--Policy', 'accept',
307
+ '--Priority', String(Math.min(100, Math.max(1, rule.priority || 100))),
308
+ ...this._base(ctx)
309
+ ];
310
+ },
311
+ groupIdFrom(createOut) {
312
+ const j = parseJson(createOut, 've CreateSecurityGroup');
313
+ const res = j.Result || j.result || {};
314
+ return res.SecurityGroupId || null;
315
+ }
316
+ };
317
+
318
+ // ---------------------------------------------------------------------------
319
+ // 百度智能云(bce vpc)
320
+ // ---------------------------------------------------------------------------
321
+ const baidu = {
322
+ id: 'baidu',
323
+ bin: 'bce',
324
+ needsRegion: true,
325
+ _base(ctx) {
326
+ const a = ['--region', ctx.region];
327
+ if (ctx.vendorProfile) a.push('--profile', ctx.vendorProfile);
328
+ return a;
329
+ },
330
+ async serverByIp(ctx, ip) {
331
+ const { stdout } = await run('bce', ['bcc', 'ListInstances', '--maxKeys', '100', ...this._base(ctx)], ctx);
332
+ const j = parseJson(stdout, 'bce ListInstances');
333
+ const list = arr(j.instances || (j.result && j.result.instances));
334
+ const hit = list.find((it) => (it.publicIp || it.publicIpAddress) === ip);
335
+ if (!hit) return null;
336
+ return {
337
+ id: String(hit.id || hit.instanceId),
338
+ name: hit.name || '',
339
+ region: ctx.region,
340
+ vpcId: hit.vpcId || (hit.vpc && hit.vpc.id) || null
341
+ };
342
+ },
343
+ async listGroups(ctx) {
344
+ const { stdout } = await run('bce', ['vpc', 'QuerySecurityGroupsList', ...this._base(ctx)], ctx);
345
+ const j = parseJson(stdout, 'bce QuerySecurityGroupsList');
346
+ return arr(j.securityGroups || j.securityGroupList).map((g) => ({
347
+ id: g.securityGroupId,
348
+ name: g.name || g.securityGroupName,
349
+ vpcId: g.vpcId || null
350
+ }));
351
+ },
352
+ async listRules(ctx, gid) {
353
+ const { stdout } = await run('bce', ['vpc', 'GetSecurityGroupDetails', '--securityGroupId', gid, ...this._base(ctx)], ctx);
354
+ const j = parseJson(stdout, 'bce GetSecurityGroupDetails');
355
+ return arr(j.rules || j.securityGroupRules).map((r) => ({
356
+ proto: String(r.protocol || '').toLowerCase(),
357
+ port: String(r.portRange || '').split('-')[0],
358
+ source: r.sourceIp || null,
359
+ action: 'accept',
360
+ priority: null
361
+ }));
362
+ },
363
+ createArgs(ctx, server, name, description) {
364
+ return ['vpc', 'CreateSecurityGroup', '--vpcId', server.vpcId,
365
+ '--name', name, '--desc', description, ...this._base(ctx)];
366
+ },
367
+ addRuleArgs(ctx, gid, rule) {
368
+ const r = {
369
+ direction: 'ingress',
370
+ ethertype: 'IPv4',
371
+ portRange: String(rule.port),
372
+ protocol: rule.proto,
373
+ sourceIp: normalizeCidr(rule.source),
374
+ remark: 'srvprice open-port'
375
+ };
376
+ return ['vpc', 'AuthorizeSecurityGroupRules', '--securityGroupId', gid,
377
+ '--rule', JSON.stringify(r), ...this._base(ctx)];
378
+ },
379
+ groupIdFrom(createOut) {
380
+ const j = parseJson(createOut, 'bce CreateSecurityGroup');
381
+ return j.securityGroupId || (j.result && j.result.securityGroupId) || null;
382
+ }
383
+ };
384
+
385
+ // ---------------------------------------------------------------------------
386
+ // 京东云(jdc vpc)
387
+ // 注意:规则字段名按 jdc help 的示意写成 best-effort,首次真写前需核对响应。
388
+ // ---------------------------------------------------------------------------
389
+ const jdcloud = {
390
+ id: 'jdcloud',
391
+ bin: 'jdc',
392
+ needsRegion: true,
393
+ _base(ctx) {
394
+ return ['--region-id', ctx.region];
395
+ },
396
+ async serverByIp(ctx, ip) {
397
+ const { stdout } = await run('jdc', ['vm', 'describe-instances', '--page-size', '100', ...this._base(ctx)], ctx);
398
+ const j = parseJson(stdout, 'jdc describe-instances');
399
+ const res = j.result || j;
400
+ const list = arr(res.instances);
401
+ const hit = list.find((it) => (it.publicIpAddress || it.elasticIpAddress || it.privateIpAddress) === ip);
402
+ if (!hit) return null;
403
+ return {
404
+ id: String(hit.instanceId),
405
+ name: hit.instanceName || hit.instanceId,
406
+ region: ctx.region,
407
+ vpcId: hit.vpcId || null
408
+ };
409
+ },
410
+ async listGroups(ctx) {
411
+ const { stdout } = await run('jdc', ['vpc', 'describe-network-security-groups', '--page-size', '100', ...this._base(ctx)], ctx);
412
+ const j = parseJson(stdout, 'jdc describe-network-security-groups');
413
+ const res = j.result || j;
414
+ return arr(res.networkSecurityGroups).map((g) => ({
415
+ id: g.networkSecurityGroupId,
416
+ name: g.networkSecurityGroupName,
417
+ vpcId: g.vpcId || null
418
+ }));
419
+ },
420
+ async listRules(ctx, gid) {
421
+ const { stdout } = await run('jdc', ['vpc', 'describe-network-security-group', '--network-security-group-id', gid, ...this._base(ctx)], ctx);
422
+ const j = parseJson(stdout, 'jdc describe-network-security-group');
423
+ const res = j.result || j;
424
+ const g = res.networkSecurityGroup || res;
425
+ return arr(g.securityGroupRules || g.rules).map((r) => ({
426
+ proto: String(r.protocol || '').toLowerCase(),
427
+ port: String(r.portRangeMin != null ? r.portRangeMin : '').split('-')[0],
428
+ source: r.addressPrefix || r.sourceIp || null,
429
+ action: String(r.ruleAction || '').toLowerCase(),
430
+ priority: null
431
+ }));
432
+ },
433
+ createArgs(ctx, server, name, description) {
434
+ return ['vpc', 'create-network-security-group',
435
+ '--network-security-group-name', name,
436
+ '--vpc-id', server.vpcId,
437
+ '--description', description, ...this._base(ctx)];
438
+ },
439
+ addRuleArgs(ctx, gid, rule) {
440
+ const specs = [{
441
+ protocol: rule.proto,
442
+ portRangeMin: rule.port,
443
+ portRangeMax: rule.port,
444
+ direction: 'ingress',
445
+ addressPrefix: normalizeCidr(rule.source),
446
+ ruleAction: 'allow'
447
+ }];
448
+ return ['vpc', 'add-network-security-group-rules',
449
+ '--network-security-group-id', gid,
450
+ '--network-security-group-rule-specs', JSON.stringify(specs), ...this._base(ctx)];
451
+ },
452
+ groupIdFrom(createOut) {
453
+ const j = parseJson(createOut, 'jdc create-network-security-group');
454
+ const res = j.result || j;
455
+ return res.networkSecurityGroupId || (res.networkSecurityGroup && res.networkSecurityGroup.networkSecurityGroupId) || null;
456
+ }
457
+ };
458
+
459
+ // ---------------------------------------------------------------------------
460
+ // 天翼云(ctyun-cli vpc)
461
+ // ---------------------------------------------------------------------------
462
+ const ctyun = {
463
+ id: 'ctyun',
464
+ bin: 'ctyun-cli',
465
+ needsRegion: true,
466
+ _base(ctx) {
467
+ const a = ['--regionID', ctx.region, '--output', 'json'];
468
+ if (ctx.vendorProfile) a.push('--cli-profile', ctx.vendorProfile);
469
+ return a;
470
+ },
471
+ async serverByIp(ctx, ip) {
472
+ const { stdout } = await run('ctyun-cli', ['ecs', 'ListEcsInstances', '--pageSize', '50', ...this._base(ctx)], ctx);
473
+ const j = parseJson(stdout, 'ctyun ListEcsInstances');
474
+ const body = j.returnObj || j.result || j;
475
+ const list = arr(body.results || body.instances);
476
+ const hit = list.find((it) => (it.publicIP || it.eipAddress || it.publicIp) === ip);
477
+ if (!hit) return null;
478
+ return {
479
+ id: String(hit.instanceID || hit.instanceId || hit.id),
480
+ name: hit.displayName || hit.instanceName || '',
481
+ region: ctx.region,
482
+ vpcId: hit.vpcID || hit.vpcId || (hit.vpc && hit.vpc.vpcID) || null
483
+ };
484
+ },
485
+ async listGroups(ctx) {
486
+ const { stdout } = await run('ctyun-cli', ['vpc', 'QueryVpcSecurityGroups', ...this._base(ctx)], ctx);
487
+ const j = parseJson(stdout, 'ctyun QueryVpcSecurityGroups');
488
+ const body = j.returnObj || j.result || j;
489
+ return arr(body.securityGroups || body.results).map((g) => ({
490
+ id: g.securityGroupID || g.securityGroupId,
491
+ name: g.securityGroupName || g.name,
492
+ vpcId: g.vpcID || g.vpcId || null
493
+ }));
494
+ },
495
+ async listRules(ctx, gid) {
496
+ const { stdout } = await run('ctyun-cli', ['vpc', 'DescribeVpcSecurityGroupRules', '--securityGroupID', gid, ...this._base(ctx)], ctx);
497
+ const j = parseJson(stdout, 'ctyun DescribeVpcSecurityGroupRules');
498
+ const body = j.returnObj || j.result || j;
499
+ return arr(body.securityGroupRules || body.results).map((r) => ({
500
+ proto: String(r.protocol || '').toLowerCase(),
501
+ port: String(r.range || '').split('-')[0],
502
+ source: r.destCidrIp || r.srcCidrIp || null, // 官方字段名 destCidrIp 表示远端地址
503
+ action: String(r.action || '').toLowerCase(),
504
+ priority: r.priority !== undefined ? Number(r.priority) : null
505
+ }));
506
+ },
507
+ createArgs(ctx, server, name, description) {
508
+ const token = require('crypto').randomBytes(16).toString('hex');
509
+ const a = ['vpc', 'CreateVpcSecurityGroup',
510
+ '--clientToken', token,
511
+ '--name', name,
512
+ '--vpcID', server.vpcId,
513
+ '--regionID', ctx.region, '--output', 'json'];
514
+ if (description) a.push('--description', description);
515
+ if (ctx.vendorProfile) a.push('--cli-profile', ctx.vendorProfile);
516
+ return a;
517
+ },
518
+ addRuleArgs(ctx, gid, rule) {
519
+ const token = require('crypto').randomBytes(16).toString('hex');
520
+ const rules = [{
521
+ direction: 'ingress',
522
+ remoteType: 0,
523
+ action: 'accept',
524
+ priority: Math.min(100, Math.max(1, rule.priority || 100)),
525
+ protocol: String(rule.proto || 'tcp').toUpperCase(),
526
+ ethertype: 'IPv4',
527
+ destCidrIp: normalizeCidr(rule.source),
528
+ range: String(rule.port),
529
+ description: 'srvprice open-port'
530
+ }];
531
+ return ['vpc', 'CreateVpcSecurityGroupIngress',
532
+ '--clientToken', token,
533
+ '--regionID', ctx.region,
534
+ '--securityGroupID', gid,
535
+ '--securityGroupRules', JSON.stringify(rules),
536
+ '--output', 'json',
537
+ ...(ctx.vendorProfile ? ['--cli-profile', ctx.vendorProfile] : [])];
538
+ },
539
+ groupIdFrom(createOut) {
540
+ const j = parseJson(createOut, 'ctyun CreateVpcSecurityGroup');
541
+ const body = j.returnObj || j.result || j;
542
+ return body.securityGroupID || body.securityGroupId || null;
543
+ }
544
+ };
545
+
546
+ // ---------------------------------------------------------------------------
547
+ // UCloud(公共云 VPC API,经 ucloud api 调用)
548
+ // 注意:UCloud 有两套 API,这里用的是公共云 VPC:CreateSecGroup / DescribeSecGroup / CreateSecGroupRule
549
+ // ---------------------------------------------------------------------------
550
+ const ucloud = {
551
+ id: 'ucloud',
552
+ bin: 'ucloud',
553
+ needsRegion: true,
554
+ _base(ctx) {
555
+ const a = ['--region', ctx.region, '--output', 'json'];
556
+ if (ctx.vendorProfile) a.push('--profile', ctx.vendorProfile);
557
+ return a;
558
+ },
559
+ async serverByIp(ctx, ip) {
560
+ const { stdout } = await run('ucloud', ['uhost', 'list', ...this._base(ctx)], ctx);
561
+ const j = parseJson(stdout, 'ucloud uhost list');
562
+ const list = arr(j.UHostSet);
563
+ const hit = list.find((it) => {
564
+ const ips = arr(it.IPSet).map((x) => x.IP);
565
+ return it.PublicIP === ip || ips.includes(ip);
566
+ });
567
+ if (!hit) return null;
568
+ return {
569
+ id: String(hit.UHostId || hit.ResourceID || hit.Id),
570
+ name: hit.UHostName || hit.Name || '',
571
+ region: ctx.region,
572
+ vpcId: hit.VPCId || hit.VPCID || null
573
+ };
574
+ },
575
+ async listGroups(ctx) {
576
+ const { stdout } = await run('ucloud', ['api', '--Action', 'DescribeSecGroup', '--Limit', '100', ...this._base(ctx)], ctx);
577
+ const j = parseJson(stdout, 'ucloud DescribeSecGroup');
578
+ return arr(j.DataSet).map((g) => ({
579
+ id: g.SecGroupId || g.SecGroupID,
580
+ name: g.SecGroupName || g.Name,
581
+ vpcId: g.VPCId || g.VPCID || null,
582
+ raw: g
583
+ }));
584
+ },
585
+ async listRules(ctx, gid) {
586
+ const { stdout } = await run('ucloud', ['api', '--Action', 'DescribeSecGroup', '--SecGroupId.0', gid, ...this._base(ctx)], ctx);
587
+ const j = parseJson(stdout, 'ucloud DescribeSecGroup');
588
+ const g = arr(j.DataSet).find((x) => (x.SecGroupId || x.SecGroupID) === gid) || {};
589
+ const rules = arr(g.SGRuleInfo || g.Rules);
590
+ return rules.map((r) => ({
591
+ proto: String(r.ProtocolType || '').toLowerCase(),
592
+ port: String(r.DstPort || '').split(',')[0],
593
+ source: r.SrcIP || null,
594
+ action: String(r.RuleAction || '').toLowerCase(),
595
+ priority: r.Priority !== undefined ? r.Priority : null
596
+ }));
597
+ },
598
+ createArgs(ctx, server, name, description) {
599
+ const a = ['api', '--Action', 'CreateSecGroup', '--Name', name, '--VPCID', server.vpcId,
600
+ ...this._base(ctx)];
601
+ if (description) a.push('--Remark', description);
602
+ return a;
603
+ },
604
+ addRuleArgs(ctx, gid, rule) {
605
+ const priority = Math.min(200, Math.max(1, rule.priority || 100));
606
+ return ['api', '--Action', 'CreateSecGroupRule',
607
+ '--SecGroupId', gid,
608
+ '--Rule.0.Direction', 'Ingress',
609
+ '--Rule.0.IPRange', normalizeCidr(rule.source),
610
+ '--Rule.0.Priority', String(priority),
611
+ '--Rule.0.ProtocolType', String(rule.proto || 'tcp').toUpperCase(),
612
+ '--Rule.0.DstPort', String(rule.port),
613
+ '--Rule.0.RuleAction', 'Accept',
614
+ '--Rule.0.Remark', 'srvprice open-port',
615
+ '--Rule.0.IPVersion', 'IPv4',
616
+ ...this._base(ctx)];
617
+ },
618
+ groupIdFrom(createOut) {
619
+ const j = parseJson(createOut, 'ucloud CreateSecGroup');
620
+ return j.SecGroupId || j.SecGroupID || null;
621
+ }
622
+ };
623
+
624
+ const ADAPTERS = { aliyun, tencent, volcengine, baidu, jdcloud, ctyun, ucloud };
625
+
626
+ function get(id) {
627
+ return ADAPTERS[id] || null;
628
+ }
629
+
630
+ function ids() {
631
+ return Object.keys(ADAPTERS);
632
+ }
633
+
634
+ module.exports = { get, ids, groupNameFor, normalizeCidr, run };