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.
package/lib/sms.js ADDED
@@ -0,0 +1,172 @@
1
+ 'use strict';
2
+
3
+ // 短信通知(阿里云 dysmsapi)。零外部依赖。
4
+ // 配置优先级:环境变量 SMS_* > ~/.srvprice/sms.json(或 SRVPRICE_SMS_CONFIG)。
5
+ // 阿里云要求“已审核签名 + 已审核模板”,这里只负责调用,不绕过审核。
6
+
7
+ const fs = require('fs');
8
+ const os = require('os');
9
+ const path = require('path');
10
+ const https = require('https');
11
+ const crypto = require('crypto');
12
+
13
+ const CONFIG_PATH = () =>
14
+ process.env.SRVPRICE_SMS_CONFIG || path.join(process.env.SRVPRICE_HOME || path.join(os.homedir(), '.srvprice'), 'sms.json');
15
+
16
+ const EXAMPLE = {
17
+ provider: 'aliyun',
18
+ access_key_id: '',
19
+ access_key_secret: '',
20
+ sign_name: '',
21
+ template_code: '',
22
+ param_name: 'content',
23
+ phones: ['13800000000'],
24
+ };
25
+
26
+ function fromEnv() {
27
+ const e = {
28
+ access_key_id: process.env.SMS_ACCESS_KEY,
29
+ access_key_secret: process.env.SMS_ACCESS_SECRET,
30
+ sign_name: process.env.SMS_SIGN_NAME,
31
+ template_code: process.env.SMS_TEMPLATE_CODE,
32
+ param_name: process.env.SMS_PARAM_NAME || 'content',
33
+ phones: process.env.SMS_PHONE ? [process.env.SMS_PHONE] : [],
34
+ };
35
+ const has = ['access_key_id', 'access_key_secret', 'sign_name', 'template_code'].some((k) => e[k])
36
+ || (Array.isArray(e.phones) && e.phones.length > 0);
37
+ return has ? e : null;
38
+ }
39
+
40
+ function load() {
41
+ let file = null;
42
+ try {
43
+ file = JSON.parse(fs.readFileSync(CONFIG_PATH(), 'utf8'));
44
+ } catch (e) {
45
+ file = null;
46
+ }
47
+ const env = fromEnv();
48
+ if (!file && !env) return null;
49
+ const merged = Object.assign({ provider: 'aliyun', param_name: 'content' }, file || {});
50
+ if (env) {
51
+ for (const k of Object.keys(env)) {
52
+ if (env[k] !== undefined && env[k] !== '') merged[k] = env[k];
53
+ }
54
+ if (env.phones && env.phones.length) merged.phones = env.phones;
55
+ }
56
+ return merged;
57
+ }
58
+
59
+ function missing(conf) {
60
+ if (!conf) return ['配置文件或 SMS_* 环境变量'];
61
+ return ['access_key_id', 'access_key_secret', 'sign_name', 'template_code']
62
+ .filter((k) => !conf[k])
63
+ .concat((conf.phones && conf.phones.length) ? [] : ['phones']);
64
+ }
65
+
66
+ function mask(v) {
67
+ const s = String(v || '');
68
+ return s.length <= 8 ? (s ? '***' : '') : s.slice(0, 4) + '…' + s.slice(-4);
69
+ }
70
+
71
+ function maskPhone(p) {
72
+ const s = String(p || '');
73
+ return s.length === 11 ? s.slice(0, 3) + '****' + s.slice(-4) : s;
74
+ }
75
+
76
+ function status() {
77
+ const conf = load();
78
+ const miss = missing(conf);
79
+ return {
80
+ config_path: CONFIG_PATH(),
81
+ exists: !!conf,
82
+ provider: (conf && conf.provider) || 'aliyun',
83
+ access_key_id: conf ? mask(conf.access_key_id) : '',
84
+ sign_name: (conf && conf.sign_name) || '',
85
+ template_code: (conf && conf.template_code) || '',
86
+ param_name: (conf && conf.param_name) || 'content',
87
+ phones: ((conf && conf.phones) || []).map(maskPhone),
88
+ ready: miss.length === 0,
89
+ missing: miss,
90
+ };
91
+ }
92
+
93
+ function encode(v) {
94
+ return encodeURIComponent(String(v)).replace(/[!'()*]/g, (c) => '%' + c.charCodeAt(0).toString(16).toUpperCase());
95
+ }
96
+
97
+ function signParams(params, secret) {
98
+ const q = Object.keys(params)
99
+ .sort()
100
+ .map((k) => `${encode(k)}=${encode(params[k])}`)
101
+ .join('&');
102
+ const sts = `GET&%2F&${encode(q)}`;
103
+ const sig = crypto.createHmac('sha1', `${secret}&`).update(sts).digest('base64');
104
+ return `${q}&Signature=${encode(sig)}`;
105
+ }
106
+
107
+ function send(opts) {
108
+ const conf = load();
109
+ const miss = missing(conf);
110
+ if (miss.length) {
111
+ return Promise.resolve({ ok: false, error: 'sms_config_missing', missing: miss, config_path: CONFIG_PATH() });
112
+ }
113
+ const phones = (opts.to && opts.to.length ? opts.to : conf.phones || [])
114
+ .map((p) => String(p).replace(/[^0-9]/g, ''))
115
+ .filter((p) => p.length === 11);
116
+ if (!phones.length) return Promise.resolve({ ok: false, error: 'bad_phone' });
117
+ const text = String(opts.text || '');
118
+ if (!text) return Promise.resolve({ ok: false, error: 'empty_text' });
119
+
120
+ const params = {
121
+ AccessKeyId: conf.access_key_id,
122
+ Action: 'SendSms',
123
+ Format: 'JSON',
124
+ PhoneNumbers: phones.join(','),
125
+ RegionId: 'cn-hangzhou',
126
+ SignName: conf.sign_name,
127
+ SignatureMethod: 'HMAC-SHA1',
128
+ SignatureNonce: crypto.randomUUID().replace(/-/g, ''),
129
+ SignatureVersion: '1.0',
130
+ TemplateCode: conf.template_code,
131
+ TemplateParam: JSON.stringify({ [conf.param_name || 'content']: text }),
132
+ Timestamp: new Date().toISOString().replace(/\.\d{3}Z$/, 'Z'),
133
+ Version: '2017-05-25',
134
+ };
135
+ const query = signParams(params, conf.access_key_secret);
136
+ const url = `https://dysmsapi.aliyuncs.com/?${query}`;
137
+ if (opts.dryRun) {
138
+ return Promise.resolve({
139
+ ok: true,
140
+ dry_run: true,
141
+ provider: 'aliyun',
142
+ phones: phones.map(maskPhone),
143
+ sign_name: conf.sign_name,
144
+ template_code: conf.template_code,
145
+ param_name: conf.param_name,
146
+ text,
147
+ });
148
+ }
149
+ return new Promise((resolve) => {
150
+ const req = https.get(url, { timeout: 15000 }, (res) => {
151
+ let body = '';
152
+ res.on('data', (d) => { body += d; });
153
+ res.on('end', () => {
154
+ let j = {};
155
+ try { j = JSON.parse(body); } catch (e) { /* keep empty */ }
156
+ resolve({
157
+ ok: j.Code === 'OK',
158
+ provider: 'aliyun',
159
+ code: j.Code || `HTTP_${res.statusCode}`,
160
+ message: j.Message || '',
161
+ biz_id: j.BizId || '',
162
+ request_id: j.RequestId || '',
163
+ phones: phones.map(maskPhone),
164
+ });
165
+ });
166
+ });
167
+ req.on('timeout', () => req.destroy(new Error('timeout')));
168
+ req.on('error', (e) => resolve({ ok: false, provider: 'aliyun', error: e.message }));
169
+ });
170
+ }
171
+
172
+ module.exports = { CONFIG_PATH, EXAMPLE, load, status, send, mask };
@@ -0,0 +1,109 @@
1
+ 'use strict';
2
+
3
+ // 把站点的 /api/server-snapshot 转成 CLI 的 plans 结构。
4
+ // 口径:不猜。价格解析不出来就给 null;快照里没有的字段留空。
5
+
6
+ const REGION_MAP = [
7
+ [/^大陆/, 'cn'],
8
+ [/港台|香港|台北|海外/, 'hk'],
9
+ [/全球/, 'overseas']
10
+ ];
11
+
12
+ function mapRegion(raw) {
13
+ const s = String(raw || '');
14
+ for (const [re, key] of REGION_MAP) if (re.test(s)) return key;
15
+ return null;
16
+ }
17
+
18
+ function num(m) {
19
+ return m ? Number(m[1]) : null;
20
+ }
21
+
22
+ // "45 元/月、459 元/年" / "158 元/1 年" / "207.36 元/月、1 年 2134.02 元" / "831 元/年起"
23
+ function parsePrice(text) {
24
+ const s = String(text || '');
25
+ const monthly = num(s.match(/([\d.]+)\s*元\s*\/\s*月/));
26
+ let yearly = num(s.match(/([\d.]+)\s*元\s*\/\s*(?:1\s*)?年/));
27
+ if (yearly == null) yearly = num(s.match(/1\s*年\s*([\d.]+)\s*元/));
28
+ if (yearly == null) yearly = num(s.match(/([\d.]+)\s*元\s*\/\s*首年/));
29
+ if (yearly == null && monthly == null) yearly = num(s.match(/([\d.]+)\s*元/));
30
+ return { first_year_cny: yearly, monthly_cny: monthly };
31
+ }
32
+
33
+ // "2C2G/3M/40G ESSD" → {cpu:2, mem_gb:2, bandwidth_mbps:3, disk_gb:40}
34
+ function parseSpec(text) {
35
+ const s = String(text || '');
36
+ // 先抓 "2C2G" / "2 核 4G" 这种连写,避免把后面的 40G 盘当成内存
37
+ const pair = s.match(/(\d+)\s*[C核]\s*(\d+)\s*G/);
38
+ const cpu = pair ? Number(pair[1]) : num(s.match(/(\d+)\s*[C核]/));
39
+ const mem = pair ? Number(pair[2]) : null;
40
+ const bw = num(s.match(/(\d+)\s*M(?:bps)?(?=\s|\/|$)/));
41
+ const disk = num(s.match(/(\d+)\s*G\s*(?:ESSD|SSD|系统盘|数据盘|盘)/));
42
+ return { cpu, mem_gb: mem, bandwidth_mbps: bw, disk_gb: disk };
43
+ }
44
+
45
+ function eligibilityOf(item) {
46
+ const text = `${item.eligibility || ''} ${item.note || ''} ${item.limit || ''}`;
47
+ // ★ 先认「个人/企业均可」:那说明不是 enterprise-only
48
+ const mentionsPersonal = /个人/.test(text);
49
+ if (!mentionsPersonal && /须企业实名|仅企业|企业实名/.test(text)) return 'enterprise';
50
+ if (!/新老同享/.test(text) && /新用户|新客|新人|新手|首台/.test(text)) return 'new_user';
51
+ return 'all';
52
+ }
53
+
54
+ function toPlan(it) {
55
+ const price = parsePrice(it.price);
56
+ const specs = parseSpec(it.spec);
57
+ return {
58
+ id: it.id,
59
+ provider: providerId(it.vendor),
60
+ provider_label: it.vendor || null,
61
+ name: [it.product, it.spec].filter(Boolean).join(' / ') || it.product || it.id,
62
+ region: mapRegion(it.region),
63
+ region_label: it.region || null,
64
+ specs: {
65
+ cpu: specs.cpu,
66
+ mem_gb: specs.mem_gb,
67
+ disk_gb: specs.disk_gb,
68
+ bandwidth_mbps: specs.bandwidth_mbps,
69
+ traffic: null
70
+ },
71
+ price: {
72
+ first_year_cny: price.first_year_cny,
73
+ monthly_cny: price.monthly_cny,
74
+ renew: it.renewal || null,
75
+ note: it.note || null
76
+ },
77
+ eligibility: eligibilityOf(it),
78
+ requires_icp: mapRegion(it.region) === 'cn',
79
+ purchase_limit: it.limit || null,
80
+ source_url: it.source || null,
81
+ verified_at: it.source_date || null,
82
+ confidence: it.source_status === 'needs_browser' ? 'needs_browser' : (it.verified_this_week ? 'page' : 'unverified'),
83
+ deadlines: it.deadline || null
84
+ };
85
+ }
86
+
87
+ const VENDOR_IDS = {
88
+ '阿里云': 'aliyun', 'UCloud': 'ucloud', '西部数码': 'westcn',
89
+ '腾讯云': 'tencent', '京东云': 'jdcloud', '百度智能云': 'baidu',
90
+ '天翼云': 'ctyun', 'DigitalOcean': 'digitalocean', 'Vultr': 'vultr'
91
+ };
92
+
93
+ function providerId(vendor) {
94
+ return VENDOR_IDS[vendor] || String(vendor || '').toLowerCase();
95
+ }
96
+
97
+ function snapshotToPlans(doc) {
98
+ const items = (doc && doc.items) || [];
99
+ return {
100
+ schema: 2,
101
+ source: 'api:/api/server-snapshot',
102
+ snapshot_date: doc.as_of || null,
103
+ generated_at: doc.generated_at || null,
104
+ note: doc.usage || null,
105
+ plans: items.map(toPlan)
106
+ };
107
+ }
108
+
109
+ module.exports = { snapshotToPlans, parsePrice, parseSpec, mapRegion, providerId };
package/lib/west.js ADDED
@@ -0,0 +1,258 @@
1
+ 'use strict';
2
+
3
+ // 西部数码 弹性云服务器 API v2(https://api.west.cn/api/v2)
4
+ // 鉴权:token = md5(username + api_password + time),time 为毫秒时间戳,token 10 分钟有效。
5
+ // 凭据只从环境变量读取(由 vault 注入),不落盘、不打印。
6
+ // 文档:https://www.west.cn/CustomerCenter/doc/server_v2.html(服务器业务 11 组接口)
7
+
8
+ const https = require('https');
9
+ const crypto = require('crypto');
10
+
11
+ const BASE = 'https://api.west.cn/api/v2';
12
+ const USER_ENV = 'SRVPRICE_WEST_USER';
13
+ const PASS_ENV = 'SRVPRICE_WEST_API_PASSWORD';
14
+
15
+ function creds() {
16
+ // 兼容两种注入名:SRVPRICE_WEST_*(约定的物化变量)与 WEST_*(vault 条目原名)
17
+ return {
18
+ user: process.env[USER_ENV] || process.env.WEST_USERNAME || '',
19
+ pass: process.env[PASS_ENV] || process.env.WEST_API_PASSWORD || ''
20
+ };
21
+ }
22
+
23
+ function md5(s) {
24
+ return crypto.createHash('md5').update(String(s), 'utf8').digest('hex');
25
+ }
26
+
27
+ function tokenFor(user, pass, time) {
28
+ return md5(`${user}${pass}${time}`);
29
+ }
30
+
31
+ function decodeBody(buf) {
32
+ // 文档:请求/返回使用 GB2312/GBK;取不到 gbk 解码器时退回 utf-8(关键字段是 ASCII)
33
+ try { return new TextDecoder('gbk').decode(buf); } catch (_) { return buf.toString('utf8'); }
34
+ }
35
+
36
+ function request(pathname, query, timeout = 20000) {
37
+ const { user, pass } = creds();
38
+ if (!user || !pass) {
39
+ return Promise.reject(new Error(
40
+ `缺西部数码凭据:设置 ${USER_ENV} / ${PASS_ENV}(vault 物化时注入)`));
41
+ }
42
+ const time = String(Date.now());
43
+ const params = new URLSearchParams(Object.assign({}, query, {
44
+ username: user,
45
+ time,
46
+ token: tokenFor(user, pass, time)
47
+ }));
48
+ const url = `${BASE}${pathname}${pathname.includes('?') ? '&' : '?'}${params.toString()}`;
49
+ return new Promise((resolve, reject) => {
50
+ const req = https.get(url, { timeout }, (res) => {
51
+ const chunks = [];
52
+ res.on('data', (d) => chunks.push(d));
53
+ res.on('end', () => {
54
+ const text = decodeBody(Buffer.concat(chunks));
55
+ let j = null;
56
+ try { j = JSON.parse(text); } catch (_) {
57
+ reject(new Error(`西部 API 返回非 JSON:${text.slice(0, 200)}`));
58
+ return;
59
+ }
60
+ if (Number(j.result) !== 200) {
61
+ reject(new Error(`西部 API 失败:${j.msg || ('result=' + j.result)}`));
62
+ return;
63
+ }
64
+ resolve(j.data === undefined ? j : j.data);
65
+ });
66
+ });
67
+ req.on('timeout', () => { req.destroy(); reject(new Error('西部 API 超时')); });
68
+ req.on('error', reject);
69
+ });
70
+ }
71
+
72
+ // 获取服务器列表:GET /server/?act=list&pageno=&limit=&serverroom=
73
+ function listServers(opts = {}) {
74
+ const q = { act: 'list', pageno: String(opts.pageno || 1), limit: String(opts.limit || 100) };
75
+ if (opts.serverroom) q.serverroom = String(opts.serverroom);
76
+ return request('/server/', q, opts.timeout);
77
+ }
78
+
79
+ // 机房 ID → 名称(GET /server/config/?act=base 的 data.room[]);失败不影响列表
80
+ let _roomCache = null;
81
+ async function roomNames(opts = {}) {
82
+ if (_roomCache) return _roomCache;
83
+ try {
84
+ const d = await request('/server/config/', { act: 'base' }, opts.timeout);
85
+ const map = {};
86
+ for (const r of (d && d.room) || []) map[String(r.roomid)] = r.roomname;
87
+ _roomCache = map;
88
+ return map;
89
+ } catch (_) {
90
+ return {};
91
+ }
92
+ }
93
+
94
+ // 服务器详情:GET /server/manager/?act=info(ip 或 id 二选一,优先 id)
95
+ function detail(opts = {}) {
96
+ const q = { act: 'info' };
97
+ if (opts.id) q.id = String(opts.id);
98
+ else if (opts.ip) q.ip = String(opts.ip);
99
+ else return Promise.reject(new Error('detail 需要 id 或 ip'));
100
+ return request('/server/manager/', q, opts.timeout);
101
+ }
102
+
103
+ // ---- 安全组(防火墙)API v2 ----
104
+ // 文档:server_v2.html「安全组相关」;全部为 GET
105
+ // act=list 安全组列表
106
+ // act=add name(可空) + memo(必填)
107
+ // act=gropurules 按 groupid 取规则
108
+ // act=addgrouprule 加规则(proto 小写;srcip_type 0=所有/1=指定IP/2=IP段;
109
+ // porttype 0=指定端口/1=端口范围;action=pass|block;priority 1-1024)
110
+ // act=setgroupip groupid + sip(服务器IP) + actcmd 1=部署/0=取消部署
111
+ function listFirewallGroups(opts = {}) {
112
+ return request('/server/firewallgroup/', {
113
+ act: 'list',
114
+ pageno: String(opts.pageno || 1),
115
+ limit: String(opts.limit || 100)
116
+ }, opts.timeout);
117
+ }
118
+
119
+ function addFirewallGroup(opts = {}) {
120
+ if (!opts.name) return Promise.reject(new Error('addFirewallGroup 需要 name(文档写可选,实测必填)'));
121
+ // 注意:该 API 按 GBK 解析 query;参数里出现中文会把后面的 username/token 一并带崩
122
+ if (/[^\x00-\x7F]/.test(String(opts.name)) || /[^\x00-\x7F]/.test(String(opts.memo || ''))) {
123
+ return Promise.reject(new Error('安全组 name/memo 只能用 ASCII(中文会让接口丢鉴权参数)'));
124
+ }
125
+ const q = { act: 'add', name: String(opts.name) };
126
+ if (opts.memo) q.memo = String(opts.memo);
127
+ return request('/server/firewallgroup/', q, opts.timeout);
128
+ }
129
+
130
+ function groupRules(opts = {}) {
131
+ const q = { act: 'gropurules' };
132
+ if (opts.groupid) q.groupid = String(opts.groupid);
133
+ return request('/server/firewallgroup/', q, opts.timeout);
134
+ }
135
+
136
+ function addGroupRule(opts = {}) {
137
+ if (!opts.groupid) return Promise.reject(new Error('addGroupRule 需要 groupid'));
138
+ const proto = String(opts.proto || 'tcp').toLowerCase();
139
+ if (!['tcp', 'udp', 'icmp'].includes(proto)) {
140
+ return Promise.reject(new Error(`proto 只支持 tcp/udp/icmp(收到 ${opts.proto})`));
141
+ }
142
+ const port = Number(opts.port);
143
+ if (!Number.isInteger(port) || port < 0 || port > 65535) {
144
+ return Promise.reject(new Error(`port 非法:${opts.port}`));
145
+ }
146
+ const srcType = Number(opts.srcip_type === undefined ? 1 : opts.srcip_type);
147
+ if (![0, 1, 2].includes(srcType)) return Promise.reject(new Error('srcip_type 只能是 0/1/2'));
148
+ if (srcType === 1 && !opts.srcip) return Promise.reject(new Error('srcip_type=1 需要 srcip'));
149
+ if (srcType === 0 && !opts.allow_all) {
150
+ return Promise.reject(new Error('拒绝默认放开所有来源:显式传 allow_all=true 并确认'));
151
+ }
152
+ const action = String(opts.action || 'pass').toLowerCase();
153
+ if (!['pass', 'block'].includes(action)) return Promise.reject(new Error('action 只能是 pass/block'));
154
+ const priority = Number(opts.priority || 10);
155
+ if (!Number.isInteger(priority) || priority < 1 || priority > 1024) {
156
+ return Promise.reject(new Error('priority 须在 1-1024'));
157
+ }
158
+ return request('/server/firewallgroup/', {
159
+ act: 'addgrouprule',
160
+ groupid: String(opts.groupid),
161
+ proto,
162
+ srcip_type: String(srcType),
163
+ srcip: String(opts.srcip || '0.0.0.0'),
164
+ porttype: '0',
165
+ srcport: '0',
166
+ srcport_max: '0',
167
+ dstport: String(port),
168
+ dstport_max: '0',
169
+ priority: String(priority),
170
+ action
171
+ }, opts.timeout);
172
+ }
173
+
174
+ function deployGroup(opts = {}) {
175
+ if (!opts.groupid) return Promise.reject(new Error('deployGroup 需要 groupid'));
176
+ if (!opts.sip) return Promise.reject(new Error('deployGroup 需要 sip(服务器 IP)'));
177
+ return request('/server/firewallgroup/', {
178
+ act: 'setgroupip',
179
+ groupid: String(opts.groupid),
180
+ sip: String(opts.sip),
181
+ actcmd: opts.enable === false ? '0' : '1'
182
+ }, opts.timeout);
183
+ }
184
+
185
+ // 运行状态:GET /server/system/?act=status(按 ip)
186
+ // 状态码(文档原文):0 正常运行 / 1 关机 / 2 管理员关机 / 3 暂停
187
+ function serverStatus(opts = {}) {
188
+ if (!opts.ip) return Promise.reject(new Error('status 需要 ip'));
189
+ return request('/server/system/', { act: 'status', ip: String(opts.ip) }, opts.timeout);
190
+ }
191
+
192
+ const STATUS_MAP = { 0: 'running', 1: 'stopped', 2: 'stopped', 3: 'stopped' };
193
+ const STATUS_LABEL = { 0: '正常运行', 1: '关机', 2: '管理员关机', 3: '暂停' };
194
+
195
+ function mapStatus(data) {
196
+ const code = data && data.status !== undefined ? Number(data.status) : NaN;
197
+ return {
198
+ status: STATUS_MAP[code] !== undefined ? STATUS_MAP[code] : null,
199
+ status_code: Number.isNaN(code) ? null : code,
200
+ status_info: (data && data.info) || STATUS_LABEL[code] || null
201
+ };
202
+ }
203
+
204
+ // 云快照列表:GET /server/hostsnap/?act=list(按 ip)
205
+ function snapshots(opts = {}) {
206
+ if (!opts.ip) return Promise.reject(new Error('snapshots 需要 ip'));
207
+ return request('/server/hostsnap/', { act: 'list', ip: String(opts.ip) }, opts.timeout);
208
+ }
209
+
210
+ // 快照归一化(只读展示,不猜):类型 0-普通 1-高级 2-自定义
211
+ function mapSnapshots(data) {
212
+ const d = data || {};
213
+ const type = Number(d.snapadv);
214
+ const TYPES = { 0: '普通', 1: '高级', 2: '自定义' };
215
+ return {
216
+ type: TYPES[type] || null,
217
+ type_code: Number.isNaN(type) ? null : type,
218
+ period: d.snapperiod !== undefined ? Number(d.snapperiod) : null,
219
+ left_month: d.leftmonth !== undefined ? Number(d.leftmonth) : null,
220
+ expires_at: d.expiredate || null,
221
+ activated_at: d.snapadvtime || null,
222
+ os: Array.isArray(d.os) ? d.os : [],
223
+ data_disk: Array.isArray(d.data) ? d.data : [],
224
+ size: d.size !== undefined ? Number(d.size) : null,
225
+ free_size: d.nopaysize !== undefined ? Number(d.nopaysize) : null,
226
+ policy: d.snappolicy !== undefined ? Number(d.snappolicy) : null,
227
+ keep_days: d.snaprules && d.snaprules.keepday ? String(d.snaprules.keepday) : null
228
+ };
229
+ }
230
+
231
+ // 归一化成 srvprice host 结构(纯函数,便于测试)
232
+ // 真机字段(2026-11-20):id / os / allocateip(公网IP) / serverroom(机房ID) / expdate / cpu / memory
233
+ function mapItems(items, fallbackRegion, rooms) {
234
+ const roomMap = rooms || {};
235
+ return (items || []).map((it) => {
236
+ const id = it && it.id !== undefined && it.id !== null ? String(it.id) : '';
237
+ const ip = (it && (it.allocateip || it.ip)) || null;
238
+ const room = it && it.serverroom !== undefined ? String(it.serverroom) : '';
239
+ return {
240
+ id: `west:${id}`,
241
+ provider: 'west',
242
+ instance_id: id,
243
+ name: (it && (it.freedomain || it.framedomain)) || ip || `west-${id}`,
244
+ region: roomMap[room] || (it && it.roomname) || room || fallbackRegion || null,
245
+ // 列表接口没有运行状态字段 —— 不猜,留空(详情接口可补)
246
+ status: null,
247
+ public_ipv4: ip,
248
+ type: (it && it.os) || null
249
+ };
250
+ });
251
+ }
252
+
253
+ module.exports = {
254
+ BASE, USER_ENV, PASS_ENV, creds, md5, tokenFor, request,
255
+ listServers, roomNames, mapItems,
256
+ detail, serverStatus, mapStatus, snapshots, mapSnapshots,
257
+ listFirewallGroups, addFirewallGroup, groupRules, addGroupRule, deployGroup
258
+ };
package/package.json CHANGED
@@ -1,6 +1,45 @@
1
1
  {
2
2
  "name": "srvprice-cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "srvprice 集成 CLI — 跨厂商服务器选购比价与主机操作,为 AI agent 设计",
5
+ "type": "commonjs",
6
+ "bin": {
7
+ "srvprice": "bin/srvprice.js",
8
+ "sp": "bin/srvprice.js"
9
+ },
10
+ "files": [
11
+ "bin/",
12
+ "lib/",
13
+ "data/",
14
+ "README.md",
15
+ "LICENSE"
16
+ ],
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "https://github.com/yummy342/srvprice-client.git",
20
+ "directory": "cli"
21
+ },
22
+ "homepage": "https://github.com/yummy342/srvprice-client/tree/main/cli",
23
+ "keywords": [
24
+ "srvprice",
25
+ "cloud-server",
26
+ "cli",
27
+ "agent",
28
+ "aliyun",
29
+ "tencent-cloud",
30
+ "ucloud",
31
+ "aws"
32
+ ],
33
+ "publishConfig": {
34
+ "registry": "https://registry.npmjs.org",
35
+ "access": "public"
36
+ },
37
+ "scripts": {
38
+ "test": "node --test test/cli.test.js",
39
+ "introspect": "node bin/srvprice.js --introspect"
40
+ },
41
+ "engines": {
42
+ "node": ">=18.17.0"
43
+ },
44
+ "license": "MIT"
45
+ }