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/LICENSE +21 -0
- package/README.md +200 -3
- package/bin/srvprice.js +1865 -0
- package/data/deals.json +126 -0
- package/data/plans.json +632 -0
- package/data/promos.json +427 -0
- package/data/providers.json +142 -0
- package/data/setup.json +94 -0
- package/lib/core.js +522 -0
- package/lib/firewall.js +634 -0
- package/lib/host.js +1156 -0
- package/lib/sms.js +172 -0
- package/lib/snapshot.js +109 -0
- package/lib/west.js +258 -0
- package/package.json +43 -4
package/bin/srvprice.js
ADDED
|
@@ -0,0 +1,1865 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
// srvprice 集成 CLI — 两条线:
|
|
5
|
+
// 选购线(只读,零凭据):plan / recommend / deal / provider / buy / setup / config
|
|
6
|
+
// 主机线(经适配层转发厂商 CLI):host / vendor
|
|
7
|
+
//
|
|
8
|
+
// 为 agent 设计:默认非交互;非 TTY 时默认输出 JSON;stdout 只放业务结果,
|
|
9
|
+
// 诊断与警告走 stderr(JSON 模式下为 JSONL);退出码固定。
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
const { spawn } = require('child_process');
|
|
13
|
+
const fs = require('fs');
|
|
14
|
+
const path = require('path');
|
|
15
|
+
const core = require('../lib/core');
|
|
16
|
+
const hostlib = require('../lib/host');
|
|
17
|
+
const westlib = require('../lib/west');
|
|
18
|
+
const firewall = require('../lib/firewall');
|
|
19
|
+
const smslib = require('../lib/sms');
|
|
20
|
+
|
|
21
|
+
const { EXIT, CliError, asArray } = core;
|
|
22
|
+
|
|
23
|
+
const HELP = `srvprice ${core.VERSION} — 跨厂商服务器选购比价与主机操作
|
|
24
|
+
|
|
25
|
+
用法:srvprice <命令> [子命令] [选项]
|
|
26
|
+
|
|
27
|
+
选购线(只读,无需凭据)
|
|
28
|
+
plan list 列出套餐(--provider --cpu --mem --region --budget-max --new-user-only)
|
|
29
|
+
plan get --id 查看单个套餐
|
|
30
|
+
plan compare --id 并排对比多个套餐(--id 可重复)
|
|
31
|
+
recommend 按需求推荐(--use-case blog|app|game|ai --budget --region --visitors --explain)
|
|
32
|
+
recommend wizard 交互式问答(仅终端可用)
|
|
33
|
+
deal list 优惠活动(--provider --new-user-only --ends-before --include-expired)
|
|
34
|
+
deal get --id 查看单个活动
|
|
35
|
+
provider list 厂商与渠道入口
|
|
36
|
+
provider get --name 单家厂商详情
|
|
37
|
+
promo list 变现线概览:联盟推广 / 代理商(--line affiliate|agent --status ready|apply|none|unknown)
|
|
38
|
+
promo get --name 单家厂商的变现线详情、待办与未核实项
|
|
39
|
+
promo actions 汇总待办动作(--line --status),与 providers.json 的链接对账
|
|
40
|
+
promo sync 拉站点 /api/promos 到本机缓存;无接口时降级为本地对账(--local-only --stale-days N)
|
|
41
|
+
promo link show|set|unset 维护客户侧推广链接(默认写本机缓存;--bundled 写仓库数据并自动备份)
|
|
42
|
+
buy url --plan-id|--provider 只打印购买/推广链接(--provider 用于无套餐数据的厂商)
|
|
43
|
+
buy open --plan-id|--provider 打印摘要并打开浏览器(--no-open 只打印)
|
|
44
|
+
setup list 购后维护指引目录
|
|
45
|
+
setup show <主题> 查看指引步骤(open-port / ssh-key / swap / docker-install / icp-filing)
|
|
46
|
+
config show|list|use|set|reset 选购偏好 profile(不含厂商凭据)
|
|
47
|
+
|
|
48
|
+
主机线(经适配层转发厂商 CLI,用用户自己的厂商账号)
|
|
49
|
+
vendor list 各厂商 CLI 安装情况与接入方式
|
|
50
|
+
vendor add --name 录入厂商 API 密钥(交互输入或环境变量,不走命令行参数)
|
|
51
|
+
vendor status 逐厂商校验 CLI 与凭据
|
|
52
|
+
vendor remove --name 删除某厂商凭据(需确认)
|
|
53
|
+
host list 跨厂商列出服务器(--provider --region --status)
|
|
54
|
+
host status --id 单台详情
|
|
55
|
+
host start|stop|reboot --id [--wait] [--yes] [--dry-run]
|
|
56
|
+
host wait --id --until running|stopped
|
|
57
|
+
host snapshots --id 云快照列表(目前仅西部数码,只读)
|
|
58
|
+
host open-port --ip --port --source 开端口:west(可 --deploy)/ aliyun / tencent / volcengine / baidu / jdcloud / ctyun
|
|
59
|
+
默认只出计划;写操作需 --yes;三家新云不绑定实例
|
|
60
|
+
|
|
61
|
+
通知线(需短信服务商凭据)
|
|
62
|
+
sms status 查看短信配置(~/.srvprice/sms.json 或 SMS_* 环境变量)
|
|
63
|
+
sms send --text 发送短信(--to 手机号,可重复;默认配置里的 phones;--dry-run 只签名不发送)
|
|
64
|
+
sms config 打印配置模板与路径
|
|
65
|
+
|
|
66
|
+
全局选项
|
|
67
|
+
--output json|text|auto 默认 auto:终端 text、管道 json
|
|
68
|
+
--page N --page-size N 分页
|
|
69
|
+
--refresh 尝试从站点刷新数据快照
|
|
70
|
+
--profile <名> 选购偏好 profile(也可用 SRVPRICE_PROFILE)
|
|
71
|
+
--vendor-profile <名> 透传给厂商 CLI 的 profile / context(如 aws --profile)
|
|
72
|
+
--region <地域> 主机操作地域
|
|
73
|
+
--dry-run 只校验并打印将要执行的厂商命令,不真执行
|
|
74
|
+
--yes 跳过写操作确认(仅供脚本,必须显式写)
|
|
75
|
+
read_only 偏好 config set --key read_only --value true,或 SRVPRICE_READONLY=1:一律拒绝写操作
|
|
76
|
+
--introspect 输出机器可读的命令结构
|
|
77
|
+
-h, --help / -v, --version
|
|
78
|
+
|
|
79
|
+
${core.EXIT_HELP}
|
|
80
|
+
`;
|
|
81
|
+
|
|
82
|
+
// ---------------------------------------------------------------------------
|
|
83
|
+
// 入口
|
|
84
|
+
// ---------------------------------------------------------------------------
|
|
85
|
+
|
|
86
|
+
async function main(argv) {
|
|
87
|
+
process.on('SIGINT', () => process.exit(EXIT.INTERRUPT));
|
|
88
|
+
|
|
89
|
+
const { words, opts } = core.parseArgs(argv);
|
|
90
|
+
|
|
91
|
+
if (opts.version) { process.stdout.write(core.VERSION + '\n'); return EXIT.OK; }
|
|
92
|
+
if (opts.json) opts.output = 'json';
|
|
93
|
+
|
|
94
|
+
const config = core.loadConfig();
|
|
95
|
+
const io = core.makeIO(opts, config);
|
|
96
|
+
|
|
97
|
+
if (opts.introspect) { io.data(introspect()); return EXIT.OK; }
|
|
98
|
+
|
|
99
|
+
if (opts.help || words.length === 0) {
|
|
100
|
+
process.stdout.write(HELP);
|
|
101
|
+
return words.length === 0 && !opts.help ? EXIT.USAGE : EXIT.OK;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const [cmd, sub, ...rest] = words;
|
|
105
|
+
const profilePick = () => core.resolveProfile(config, opts);
|
|
106
|
+
|
|
107
|
+
switch (cmd) {
|
|
108
|
+
case 'plan': return cmdPlan(io, opts, profilePick, sub, rest);
|
|
109
|
+
case 'recommend': return cmdRecommend(io, opts, profilePick, sub);
|
|
110
|
+
case 'deal': return cmdDeal(io, opts, profilePick, sub);
|
|
111
|
+
case 'provider': return cmdProvider(io, opts, profilePick, sub);
|
|
112
|
+
case 'promo': return cmdPromo(io, opts, profilePick, sub, rest);
|
|
113
|
+
case 'buy': return cmdBuy(io, opts, profilePick, sub);
|
|
114
|
+
case 'setup': return cmdSetup(io, opts, profilePick, sub, rest);
|
|
115
|
+
case 'config': return cmdConfig(io, opts, config, sub);
|
|
116
|
+
case 'host': return cmdHost(io, opts, profilePick, sub);
|
|
117
|
+
case 'vendor': return cmdVendor(io, opts, config, sub);
|
|
118
|
+
case 'sms': return cmdSms(io, opts, sub);
|
|
119
|
+
default:
|
|
120
|
+
throw new CliError(EXIT.USAGE, `未知命令:${cmd}(srvprice --help 查看全部命令)`);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function need(sub, allowed, cmdName) {
|
|
125
|
+
if (!sub || !allowed.includes(sub)) {
|
|
126
|
+
throw new CliError(EXIT.USAGE, `用法:srvprice ${cmdName} ${allowed.join('|')}`);
|
|
127
|
+
}
|
|
128
|
+
return sub;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function val(opts, key, flag) {
|
|
132
|
+
const v = opts[key];
|
|
133
|
+
if (v === undefined || v === true) return null;
|
|
134
|
+
return String(v);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// ---------------------------------------------------------------------------
|
|
138
|
+
// 选购线
|
|
139
|
+
// ---------------------------------------------------------------------------
|
|
140
|
+
|
|
141
|
+
function dataFor(io, opts, table) {
|
|
142
|
+
return core.loadData(table);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function freshness(io, opts, profile, records, label) {
|
|
146
|
+
return core.checkFreshness(io, records, Number(profile.stale_hours) || 24, label);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function priceText(p) {
|
|
150
|
+
if (!p) return '—';
|
|
151
|
+
if (p.first_year_cny != null) return `${p.first_year_cny} 元`;
|
|
152
|
+
if (p.monthly_cny != null) return `${p.monthly_cny} 元/月`;
|
|
153
|
+
return '未知';
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function planRow(p) {
|
|
157
|
+
return {
|
|
158
|
+
id: p.id,
|
|
159
|
+
provider: p.provider_label,
|
|
160
|
+
name: p.name,
|
|
161
|
+
region: p.region_label,
|
|
162
|
+
first_year: p.price && p.price.first_year_cny != null ? p.price.first_year_cny : null,
|
|
163
|
+
eligibility: p.eligibility
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function matchProvider(p, wanted) {
|
|
168
|
+
return !wanted.length || wanted.includes(p.provider);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
function matchRegion(p, region) {
|
|
172
|
+
if (!region) return true;
|
|
173
|
+
const r = String(region).toLowerCase();
|
|
174
|
+
if (['cn', '大陆', 'china'].includes(r)) return p.region === 'cn';
|
|
175
|
+
if (['hk', '香港'].includes(r)) return p.region === 'hk';
|
|
176
|
+
if (['overseas', '海外', '海外/台'].includes(r)) return p.region === 'overseas';
|
|
177
|
+
return p.region_label.includes(region) || p.provider === r;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
async function cmdPlan(io, opts, profilePick, sub) {
|
|
181
|
+
need(sub, ['list', 'get', 'compare'], 'plan');
|
|
182
|
+
const { values: profile } = profilePick();
|
|
183
|
+
// ★ 先刷新再装载:否则 --refresh 这一次仍然读旧的内置快照
|
|
184
|
+
if (opts.refresh) await core.refreshData(io, 'plans');
|
|
185
|
+
const data = dataFor(io, opts, 'plans');
|
|
186
|
+
// 站点快照里 source_status=needs_browser 的条目是 JS 渲染页读数,提醒一次
|
|
187
|
+
const nb = (data.plans || []).filter((p) => p.confidence === 'needs_browser').length;
|
|
188
|
+
if (nb) io.warn(`快照里有 ${nb} 条来自 JS 渲染页,需浏览器复核后才算现价`);
|
|
189
|
+
|
|
190
|
+
if (sub === 'get') {
|
|
191
|
+
const id = Array.isArray(opts.id) ? String(opts.id[0]) : val(opts, 'id');
|
|
192
|
+
if (!id) throw new CliError(EXIT.USAGE, '用法:srvprice plan get --id <plan-id>');
|
|
193
|
+
const p = data.plans.find((x) => x.id === id);
|
|
194
|
+
if (!p) throw new CliError(EXIT.NOT_FOUND, `未找到套餐:${id}`, { plan_id: id });
|
|
195
|
+
const fresh = freshness(io, opts, profile, [p], '该套餐');
|
|
196
|
+
io.data(Object.assign({ plan: p, data_freshness: fresh }, { data_source: data._source }));
|
|
197
|
+
return EXIT.OK;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
if (sub === 'compare') {
|
|
201
|
+
const ids = asArray(opts.id).map(String);
|
|
202
|
+
if (ids.length < 2) throw new CliError(EXIT.USAGE, '用法:srvprice plan compare --id <id1> --id <id2> [--id <id3>]');
|
|
203
|
+
const items = ids.map((id) => {
|
|
204
|
+
const p = data.plans.find((x) => x.id === id);
|
|
205
|
+
if (!p) throw new CliError(EXIT.NOT_FOUND, `未找到套餐:${id}`, { plan_id: id });
|
|
206
|
+
return p;
|
|
207
|
+
});
|
|
208
|
+
freshness(io, opts, profile, items, '对比数据');
|
|
209
|
+
io.data({ items, compared_at: core.nowIso() });
|
|
210
|
+
return EXIT.OK;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// list
|
|
214
|
+
const providers = val(opts, 'provider') ? asArray(opts.provider).map(String) : profile.providers;
|
|
215
|
+
const region = val(opts, 'region') || profile.default_region;
|
|
216
|
+
const cpu = opts.cpu ? Number(opts.cpu) : null;
|
|
217
|
+
const mem = opts.mem ? Number(opts.mem) : null;
|
|
218
|
+
const budgetMax = opts.budgetMax ? Number(opts.budgetMax) : null;
|
|
219
|
+
const newUserOnly = !!opts.newUserOnly || profile.new_user_only === true;
|
|
220
|
+
|
|
221
|
+
let rows = data.plans.slice();
|
|
222
|
+
if (providers && providers.length) rows = rows.filter((p) => matchProvider(p, providers));
|
|
223
|
+
if (region) rows = rows.filter((p) => matchRegion(p, region));
|
|
224
|
+
if (cpu) rows = rows.filter((p) => p.specs.cpu === cpu);
|
|
225
|
+
if (mem) rows = rows.filter((p) => p.specs.mem_gb === mem);
|
|
226
|
+
if (budgetMax != null) rows = rows.filter((p) => p.price.first_year_cny != null && p.price.first_year_cny <= budgetMax);
|
|
227
|
+
if (newUserOnly) rows = rows.filter((p) => p.eligibility !== 'all');
|
|
228
|
+
|
|
229
|
+
rows.sort((a, b) => (a.price.first_year_cny ?? Infinity) - (b.price.first_year_cny ?? Infinity));
|
|
230
|
+
const fresh = freshness(io, opts, profile, rows, '价格');
|
|
231
|
+
|
|
232
|
+
if (io.json) {
|
|
233
|
+
const pg = core.paging(rows, opts);
|
|
234
|
+
io.data({
|
|
235
|
+
query: { providers, region, cpu, mem, budget_max: budgetMax, new_user_only: newUserOnly },
|
|
236
|
+
page: pg.page, page_size: pg.page_size, total: pg.total, has_more: pg.has_more,
|
|
237
|
+
items: pg.items, data_freshness: fresh, data_source: data._source
|
|
238
|
+
});
|
|
239
|
+
} else {
|
|
240
|
+
const pg = core.paging(rows, opts);
|
|
241
|
+
io.data({
|
|
242
|
+
rows: pg.items.map(planRow),
|
|
243
|
+
columns: [
|
|
244
|
+
{ key: 'id', label: 'ID' },
|
|
245
|
+
{ key: 'provider', label: '厂商' },
|
|
246
|
+
{ key: 'name', label: '方案' },
|
|
247
|
+
{ key: 'region', label: '地域' },
|
|
248
|
+
{ key: 'first_year', label: '首年(元)', null: '未知' },
|
|
249
|
+
{ key: 'eligibility', label: '资格' }
|
|
250
|
+
],
|
|
251
|
+
footer: `共 ${pg.total} 条,第 ${pg.page} 页(--page/--page-size 翻页)。价格核验于 ${fresh.newest || '未知'},以官网实时价为准。`
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
return EXIT.OK;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
const USE_CASES = {
|
|
258
|
+
blog: { label: '个人博客 / 小站', mem: 2, bw: 3, budget: 150, note: '低预算优先,带宽够访问即可' },
|
|
259
|
+
app: { label: '应用 / API 服务', mem: 2, bw: 5, budget: 600, note: '稳定性与续费价要比首年价更看重' },
|
|
260
|
+
game: { label: '游戏服 / 定时任务', mem: 4, bw: 5, budget: 800, note: '内存与带宽优先,注意不限流量档' },
|
|
261
|
+
ai: { label: 'AI 推理 / 数据处理', mem: 4, bw: 5, budget: 1500, note: '内存与 CPU 优先,海外机型可免备案' }
|
|
262
|
+
};
|
|
263
|
+
|
|
264
|
+
async function cmdRecommend(io, opts, profilePick, sub) {
|
|
265
|
+
const { values: profile } = profilePick();
|
|
266
|
+
const data = dataFor(io, opts, 'plans');
|
|
267
|
+
|
|
268
|
+
if (sub === 'wizard') {
|
|
269
|
+
if (!process.stdin.isTTY) {
|
|
270
|
+
throw new CliError(EXIT.USAGE,
|
|
271
|
+
'recommend wizard 需要交互终端;非交互环境请用带参数的 recommend --use-case ... (交互是可选增强,默认不打扰)');
|
|
272
|
+
}
|
|
273
|
+
return wizard(io, opts, profile, data);
|
|
274
|
+
}
|
|
275
|
+
if (sub) throw new CliError(EXIT.USAGE, '用法:srvprice recommend [--use-case ...] 或 srvprice recommend wizard');
|
|
276
|
+
|
|
277
|
+
const useCase = val(opts, 'useCase') || null;
|
|
278
|
+
const budget = opts.budget ? Number(opts.budget) : (useCase && USE_CASES[useCase] ? USE_CASES[useCase].budget : null);
|
|
279
|
+
const region = val(opts, 'region') || profile.default_region;
|
|
280
|
+
const visitors = opts.visitors ? Number(opts.visitors) : null;
|
|
281
|
+
const explain = !!opts.explain;
|
|
282
|
+
|
|
283
|
+
if (useCase && !USE_CASES[useCase]) {
|
|
284
|
+
throw new CliError(EXIT.USAGE, `--use-case 支持:${Object.keys(USE_CASES).join(' | ')}`);
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
const result = recommend(data.plans, { useCase, budget, region, visitors, profile });
|
|
288
|
+
if (result.items.length) freshness(io, opts, profile, result.items.map((i) => i.plan), '推荐依据的价格');
|
|
289
|
+
|
|
290
|
+
if (io.json) {
|
|
291
|
+
io.data(Object.assign({ query: { use_case: useCase, budget, region, visitors } }, result));
|
|
292
|
+
} else {
|
|
293
|
+
const lines = [];
|
|
294
|
+
const best = result.items[0];
|
|
295
|
+
if (!best) {
|
|
296
|
+
lines.push('没有符合条件的套餐。放宽 --budget 或去掉 --region 再试。');
|
|
297
|
+
} else {
|
|
298
|
+
lines.push(`推荐:${best.plan.provider_label} ${best.plan.name} — ${priceText(best.plan.price)}`);
|
|
299
|
+
for (const r of best.reasons) lines.push(` · ${r}`);
|
|
300
|
+
if (result.items.length > 1) {
|
|
301
|
+
lines.push('', '备选:');
|
|
302
|
+
for (const alt of result.items.slice(1)) {
|
|
303
|
+
lines.push(` · ${alt.plan.id} ${alt.plan.provider_label} ${alt.plan.name} ${priceText(alt.plan.price)}`);
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
if (!explain) lines.push('', '(--explain 可看每条理由与备选)');
|
|
307
|
+
}
|
|
308
|
+
io.data({ text: lines.join('\n') });
|
|
309
|
+
}
|
|
310
|
+
return EXIT.OK;
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
function recommend(plans, q) {
|
|
314
|
+
const uc = q.useCase ? USE_CASES[q.useCase] : null;
|
|
315
|
+
const budget = q.budget;
|
|
316
|
+
const scored = [];
|
|
317
|
+
|
|
318
|
+
for (const p of plans) {
|
|
319
|
+
if (q.region && !matchRegion(p, q.region)) continue;
|
|
320
|
+
const price = p.price.first_year_cny;
|
|
321
|
+
if (budget != null && price != null && price > budget) continue;
|
|
322
|
+
|
|
323
|
+
const reasons = [];
|
|
324
|
+
let score = 0;
|
|
325
|
+
|
|
326
|
+
if (price != null) {
|
|
327
|
+
score += Math.max(0, 100 - Math.log10(Math.max(price, 1)) * 25);
|
|
328
|
+
if (uc && price <= uc.budget) { score += 25; reasons.push(`首年 ${price} 元,在 ${uc.label} 的常见预算内`); }
|
|
329
|
+
else if (budget != null) reasons.push(`首年 ${price} 元,未超预算 ${budget} 元`);
|
|
330
|
+
} else {
|
|
331
|
+
reasons.push('首年价未知,按未核实处理');
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
const mem = p.specs.mem_gb;
|
|
335
|
+
if (uc && mem != null) {
|
|
336
|
+
if (mem >= uc.mem) { score += 20; reasons.push(`${mem}G 内存满足「${uc.label}」的最小建议 ${uc.mem}G`); }
|
|
337
|
+
else { score -= 15; reasons.push(`${mem}G 内存低于「${uc.label}」建议的 ${uc.mem}G`); }
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
if (p.eligibility === 'new_user') {
|
|
341
|
+
reasons.push('新用户专享:已买过该厂商服务则用不了');
|
|
342
|
+
if (q.profile && q.profile.new_user_only === false) score -= 8;
|
|
343
|
+
}
|
|
344
|
+
if (p.eligibility === 'enterprise') { reasons.push('需企业实名'); score -= 10; }
|
|
345
|
+
|
|
346
|
+
if (/续费同价|续费同价/.test(p.price.renew || '')) { score += 10; reasons.push('续费同价,不是首年诱饵价'); }
|
|
347
|
+
else if (/续费待核|未写|未找到|回归原价/.test(p.price.renew || '')) { reasons.push(`续费口径:${p.price.renew}`); }
|
|
348
|
+
|
|
349
|
+
if (p.region === 'cn') reasons.push('大陆节点:建站需要 ICP 备案');
|
|
350
|
+
if (p.region !== 'cn' && p.requires_icp === false) reasons.push('非大陆节点:不需工信部 ICP 备案(个别厂商另有公安联网备案要求)');
|
|
351
|
+
if (p.confidence === 'calculator') reasons.push('价格为计算器读数,非活动页原文');
|
|
352
|
+
|
|
353
|
+
if (q.visitors && q.visitors > 50000 && p.specs.mem_gb && p.specs.mem_gb <= 2) {
|
|
354
|
+
score -= 10;
|
|
355
|
+
reasons.push(`日访 ${q.visitors} 偏高,2G 内存可能吃紧`);
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
scored.push({ plan: p, score: Math.round(score * 10) / 10, reasons });
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
scored.sort((a, b) => b.score - a.score);
|
|
362
|
+
const top = scored.slice(0, 3);
|
|
363
|
+
return {
|
|
364
|
+
items: top,
|
|
365
|
+
note: '推荐是规则打分(预算 / 内存 / 资格 / 续费口径),不是实时比价;下单前请核对官网价。'
|
|
366
|
+
};
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
async function wizard(io, opts, profile, data) {
|
|
370
|
+
const readline = require('readline');
|
|
371
|
+
const rl = readline.createInterface({ input: process.stdin, output: process.stderr });
|
|
372
|
+
const ask = (q) => new Promise((res) => rl.question(q, (a) => res(String(a).trim())));
|
|
373
|
+
try {
|
|
374
|
+
io.info('用途? blog=个人博客 / app=应用服务 / game=游戏服 / ai=AI 推理');
|
|
375
|
+
const useCase = (await ask('用途 [blog]: ')) || 'blog';
|
|
376
|
+
const budgetRaw = await ask('预算(元/年,回车跳过): ');
|
|
377
|
+
const regionRaw = await ask('地域 cn=大陆 / hk=香港 / overseas=海外(回车不限): ');
|
|
378
|
+
rl.close();
|
|
379
|
+
|
|
380
|
+
const q = {
|
|
381
|
+
useCase: USE_CASES[useCase] ? useCase : 'blog',
|
|
382
|
+
budget: budgetRaw ? Number(budgetRaw) : null,
|
|
383
|
+
region: regionRaw || null,
|
|
384
|
+
profile
|
|
385
|
+
};
|
|
386
|
+
const result = recommend(data.plans, q);
|
|
387
|
+
freshness(io, opts, profile, result.items.map((i) => i.plan), '推荐依据的价格');
|
|
388
|
+
const best = result.items[0];
|
|
389
|
+
if (!best) { io.data({ text: '没有符合条件的套餐。' }); return EXIT.OK; }
|
|
390
|
+
const lines = [`推荐:${best.plan.provider_label} ${best.plan.name} — ${priceText(best.plan.price)}`];
|
|
391
|
+
for (const r of best.reasons) lines.push(` · ${r}`);
|
|
392
|
+
io.data({ text: lines.join('\n') });
|
|
393
|
+
return EXIT.OK;
|
|
394
|
+
} finally {
|
|
395
|
+
rl.close();
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
async function cmdDeal(io, opts, profilePick, sub) {
|
|
400
|
+
need(sub, ['list', 'get'], 'deal');
|
|
401
|
+
const { values: profile } = profilePick();
|
|
402
|
+
if (opts.refresh) await core.refreshData(io, 'deals');
|
|
403
|
+
const data = dataFor(io, opts, 'deals');
|
|
404
|
+
|
|
405
|
+
if (sub === 'get') {
|
|
406
|
+
const id = Array.isArray(opts.id) ? opts.id[0] : val(opts, 'id');
|
|
407
|
+
if (!id) throw new CliError(EXIT.USAGE, '用法:srvprice deal get --id <deal-id>');
|
|
408
|
+
const d = data.deals.find((x) => x.id === id);
|
|
409
|
+
if (!d) throw new CliError(EXIT.NOT_FOUND, `未找到活动:${id}`, { deal_id: id });
|
|
410
|
+
freshness(io, opts, profile, [d], '活动数据');
|
|
411
|
+
io.data({ deal: Object.assign({}, d, { expired: isExpired(d) }) });
|
|
412
|
+
return EXIT.OK;
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
const providers = val(opts, 'provider') ? asArray(opts.provider).map(String) : [];
|
|
416
|
+
const endsBefore = val(opts, 'endsBefore');
|
|
417
|
+
const newUserOnly = !!opts.newUserOnly;
|
|
418
|
+
|
|
419
|
+
let rows = data.deals.slice();
|
|
420
|
+
if (providers.length) rows = rows.filter((d) => providers.includes(d.provider));
|
|
421
|
+
if (!opts.includeExpired) rows = rows.filter((d) => !isExpired(d));
|
|
422
|
+
if (endsBefore) rows = rows.filter((d) => d.ends_at && d.ends_at <= endsBefore);
|
|
423
|
+
if (newUserOnly) rows = rows.filter((d) => /新用户|新人|新客/.test(`${d.eligibility} ${d.summary}`));
|
|
424
|
+
|
|
425
|
+
freshness(io, opts, profile, rows, '活动数据');
|
|
426
|
+
if (io.json) { io.data({ count: rows.length, items: rows }); return EXIT.OK; }
|
|
427
|
+
io.data({
|
|
428
|
+
rows: rows.map((d) => ({
|
|
429
|
+
id: d.id, provider: d.provider_label, title: d.title,
|
|
430
|
+
ends_at: d.ends_at || '未写', status: isExpired(d) ? '已过期' : '进行中'
|
|
431
|
+
})),
|
|
432
|
+
columns: [
|
|
433
|
+
{ key: 'id', label: 'ID' },
|
|
434
|
+
{ key: 'provider', label: '厂商' },
|
|
435
|
+
{ key: 'title', label: '活动' },
|
|
436
|
+
{ key: 'ends_at', label: '截止' },
|
|
437
|
+
{ key: 'status', label: '状态' }
|
|
438
|
+
],
|
|
439
|
+
footer: '已过期活动默认不列出(--include-expired 查看)。'
|
|
440
|
+
});
|
|
441
|
+
return EXIT.OK;
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
function isExpired(deal) {
|
|
445
|
+
if (!deal.ends_at) return false;
|
|
446
|
+
return deal.ends_at < core.todayIso();
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
async function cmdProvider(io, opts, profilePick, sub) {
|
|
450
|
+
need(sub, ['list', 'get'], 'provider');
|
|
451
|
+
const { values: profile } = profilePick();
|
|
452
|
+
const data = dataFor(io, opts, 'providers');
|
|
453
|
+
freshness(io, opts, profile, data.providers, '渠道入口');
|
|
454
|
+
|
|
455
|
+
if (sub === 'get') {
|
|
456
|
+
const name = val(opts, 'name');
|
|
457
|
+
if (!name) throw new CliError(EXIT.USAGE, '用法:srvprice provider get --name <provider-id>');
|
|
458
|
+
const p = data.providers.find((x) => x.id === name);
|
|
459
|
+
if (!p) throw new CliError(EXIT.NOT_FOUND, `未找到厂商:${name}`, { provider: name });
|
|
460
|
+
io.data({ provider: p });
|
|
461
|
+
return EXIT.OK;
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
if (io.json) {
|
|
465
|
+
io.data({ count: data.providers.length, items: data.providers, overseas_credits: data.overseas_credits });
|
|
466
|
+
return EXIT.OK;
|
|
467
|
+
}
|
|
468
|
+
io.data({
|
|
469
|
+
rows: data.providers.map((p) => ({ id: p.id, label: p.label, kind: p.kind, url: p.channel_url })),
|
|
470
|
+
columns: [
|
|
471
|
+
{ key: 'id', label: 'ID' },
|
|
472
|
+
{ key: 'label', label: '厂商' },
|
|
473
|
+
{ key: 'kind', label: '类型' },
|
|
474
|
+
{ key: 'url', label: '渠道入口' }
|
|
475
|
+
],
|
|
476
|
+
footer: '渠道链接含归因参数;站内与 CLI 都不代下单、不收款。'
|
|
477
|
+
});
|
|
478
|
+
return EXIT.OK;
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
// ---- 变现线:联盟推广 / 代理商(只读,不做申请/签约)----
|
|
482
|
+
|
|
483
|
+
const PROMO_STATUS_LABEL = { ready: '已就绪', apply: '待申请', none: '无路', unknown: '待核' };
|
|
484
|
+
const PROMO_LINES = ['affiliate', 'agent'];
|
|
485
|
+
const PROMO_STATUSES = Object.keys(PROMO_STATUS_LABEL);
|
|
486
|
+
|
|
487
|
+
function promoValidate(opts) {
|
|
488
|
+
const line = val(opts, 'line');
|
|
489
|
+
if (line && !PROMO_LINES.includes(line)) {
|
|
490
|
+
throw new CliError(EXIT.USAGE, `--line 支持:${PROMO_LINES.join(' | ')}`);
|
|
491
|
+
}
|
|
492
|
+
const status = val(opts, 'status');
|
|
493
|
+
if (status && !PROMO_STATUSES.includes(status)) {
|
|
494
|
+
throw new CliError(EXIT.USAGE, `--status 支持:${PROMO_STATUSES.join(' | ')}`);
|
|
495
|
+
}
|
|
496
|
+
return { line, status };
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
async function cmdPromo(io, opts, profilePick, sub, rest) {
|
|
500
|
+
need(sub, ['list', 'get', 'actions', 'sync', 'link'], 'promo');
|
|
501
|
+
if (sub === 'sync') return promoRunSync(io, opts);
|
|
502
|
+
if (sub === 'link') return promoLink(io, opts, rest || []);
|
|
503
|
+
const { line: lineFilter, status: statusFilter } = promoValidate(opts);
|
|
504
|
+
const data = dataFor(io, opts, 'promos');
|
|
505
|
+
const provs = dataFor(io, opts, 'providers');
|
|
506
|
+
|
|
507
|
+
// 与 providers.json 对账:变现线有没有已配置的渠道链接
|
|
508
|
+
const cliLink = (id) => {
|
|
509
|
+
const p = provs.providers.find((x) => x.id === id);
|
|
510
|
+
if (!p) return null;
|
|
511
|
+
return {
|
|
512
|
+
url: p.channel_url || null,
|
|
513
|
+
note: p.entry_note || null,
|
|
514
|
+
verified_at: p.verified_at || null
|
|
515
|
+
};
|
|
516
|
+
};
|
|
517
|
+
const enrich = (p) => Object.assign({}, p, { cli_link: cliLink(p.id) });
|
|
518
|
+
|
|
519
|
+
if (sub === 'get') {
|
|
520
|
+
const name = val(opts, 'name');
|
|
521
|
+
if (!name) throw new CliError(EXIT.USAGE, '用法:srvprice promo get --name <provider-id>');
|
|
522
|
+
const p = data.providers.find((x) => x.id === name || x.label === name);
|
|
523
|
+
if (!p) throw new CliError(EXIT.NOT_FOUND, `未找到厂商:${name}`, { provider: name });
|
|
524
|
+
io.data({
|
|
525
|
+
provider: enrich(p),
|
|
526
|
+
snapshot_date: data.snapshot_date,
|
|
527
|
+
count_rule: data.count_rule,
|
|
528
|
+
status_help: data.status_help,
|
|
529
|
+
note: data.note
|
|
530
|
+
});
|
|
531
|
+
return EXIT.OK;
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
if (sub === 'actions') {
|
|
535
|
+
const items = [];
|
|
536
|
+
for (const p of data.providers) {
|
|
537
|
+
const st = p.status || {};
|
|
538
|
+
for (const t of p.todo || []) {
|
|
539
|
+
if (lineFilter && t.line !== lineFilter) continue;
|
|
540
|
+
const lineStatus = st[t.line] || 'unknown';
|
|
541
|
+
if (statusFilter && lineStatus !== statusFilter) continue;
|
|
542
|
+
items.push({
|
|
543
|
+
provider: p.id,
|
|
544
|
+
label: p.label,
|
|
545
|
+
line: t.line,
|
|
546
|
+
line_status: lineStatus,
|
|
547
|
+
action: t.action,
|
|
548
|
+
blocker: t.blocker || null,
|
|
549
|
+
url: t.url || (p.lines && p.lines[t.line] && p.lines[t.line].url) || null,
|
|
550
|
+
materials: t.materials || []
|
|
551
|
+
});
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
if (io.json) {
|
|
555
|
+
io.data({ count: items.length, items, snapshot_date: data.snapshot_date });
|
|
556
|
+
return EXIT.OK;
|
|
557
|
+
}
|
|
558
|
+
io.data({
|
|
559
|
+
rows: items.map((i, n) => ({
|
|
560
|
+
n: n + 1,
|
|
561
|
+
provider: i.label,
|
|
562
|
+
line: i.line === 'affiliate' ? '联盟' : '代理',
|
|
563
|
+
action: i.action,
|
|
564
|
+
blocker: i.blocker || '—'
|
|
565
|
+
})),
|
|
566
|
+
columns: [
|
|
567
|
+
{ key: 'n', label: '#' },
|
|
568
|
+
{ key: 'provider', label: '厂商' },
|
|
569
|
+
{ key: 'line', label: '线' },
|
|
570
|
+
{ key: 'action', label: '待办' },
|
|
571
|
+
{ key: 'blocker', label: '卡点' }
|
|
572
|
+
],
|
|
573
|
+
footer: 'CLI 不代申请/代签约;链接与材料仅作指引,最终以厂商官方页面为准。'
|
|
574
|
+
});
|
|
575
|
+
return EXIT.OK;
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
// list
|
|
579
|
+
let items = data.providers.map(enrich);
|
|
580
|
+
if (lineFilter) items = items.filter((p) => p.lines && p.lines[lineFilter]);
|
|
581
|
+
if (statusFilter) {
|
|
582
|
+
items = items.filter((p) => Object.values(p.status || {}).includes(statusFilter));
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
if (io.json) {
|
|
586
|
+
io.data({
|
|
587
|
+
count: items.length,
|
|
588
|
+
items,
|
|
589
|
+
snapshot_date: data.snapshot_date,
|
|
590
|
+
count_rule: data.count_rule,
|
|
591
|
+
status_help: data.status_help
|
|
592
|
+
});
|
|
593
|
+
return EXIT.OK;
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
const cell = (p, line) => {
|
|
597
|
+
const st = (p.status || {})[line] || 'unknown';
|
|
598
|
+
const l = (p.lines || {})[line];
|
|
599
|
+
const label = PROMO_STATUS_LABEL[st] || st;
|
|
600
|
+
return l && l.verified === false ? `${label}*` : label;
|
|
601
|
+
};
|
|
602
|
+
io.data({
|
|
603
|
+
rows: items.map((p) => ({
|
|
604
|
+
label: p.label,
|
|
605
|
+
affiliate: cell(p, 'affiliate'),
|
|
606
|
+
agent: cell(p, 'agent'),
|
|
607
|
+
link: p.cli_link && p.cli_link.url ? '有' : '—'
|
|
608
|
+
})),
|
|
609
|
+
columns: [
|
|
610
|
+
{ key: 'label', label: '厂商' },
|
|
611
|
+
{ key: 'affiliate', label: '联盟推广' },
|
|
612
|
+
{ key: 'agent', label: '代理商' },
|
|
613
|
+
{ key: 'link', label: '本机链接' }
|
|
614
|
+
],
|
|
615
|
+
footer: '* = 该线官方来源未核实(数字不可当作已核实口径)。「本机链接」指 providers.json 是否已配渠道入口;详情用 promo get --name。'
|
|
616
|
+
});
|
|
617
|
+
return EXIT.OK;
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
// ---- promo sync:站点拉取(可选)+ 本地对账 ----
|
|
621
|
+
|
|
622
|
+
function hostOf(url) {
|
|
623
|
+
try { return new URL(url).hostname.toLowerCase(); } catch (_) { return null; }
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
function registrable(host) {
|
|
627
|
+
if (!host) return null;
|
|
628
|
+
const parts = host.split('.').filter(Boolean);
|
|
629
|
+
return parts.length < 2 ? host : parts.slice(-2).join('.');
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
// 官方域:official + promos.json 里该厂商各线的程序页;用于发现「链接跑到别的域」
|
|
633
|
+
function officialDomains(provider, entry) {
|
|
634
|
+
const set = new Set();
|
|
635
|
+
const push = (u) => { const h = hostOf(u); if (h) set.add(registrable(h)); };
|
|
636
|
+
if (provider && provider.official) push(provider.official);
|
|
637
|
+
if (entry && entry.lines) {
|
|
638
|
+
for (const line of PROMO_LINES) {
|
|
639
|
+
const l = entry.lines[line];
|
|
640
|
+
if (l && l.url) push(l.url);
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
return [...set].filter(Boolean);
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
// 写入允许域:官方域 + 现有渠道链接所在域(已知生态内可继续用)
|
|
647
|
+
function writableDomains(provider, provs, entry) {
|
|
648
|
+
const set = new Set(officialDomains(provider, entry));
|
|
649
|
+
const push = (u) => { const h = hostOf(u); if (h) set.add(registrable(h)); };
|
|
650
|
+
if (provider) {
|
|
651
|
+
push(provider.channel_url);
|
|
652
|
+
if (provider.channel_urls) Object.values(provider.channel_urls).forEach(push);
|
|
653
|
+
}
|
|
654
|
+
return [...set].filter(Boolean);
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
function promoFindings(promos, provs, staleDays) {
|
|
658
|
+
const findings = [];
|
|
659
|
+
const now = Date.now();
|
|
660
|
+
for (const p of promos.providers) {
|
|
661
|
+
const prov = provs.providers.find((x) => x.id === p.id) || null;
|
|
662
|
+
const link = prov ? (prov.channel_url || (prov.channel_urls && Object.values(prov.channel_urls)[0])) : null;
|
|
663
|
+
|
|
664
|
+
for (const line of PROMO_LINES) {
|
|
665
|
+
const l = p.lines && p.lines[line];
|
|
666
|
+
if (!l) continue;
|
|
667
|
+
|
|
668
|
+
// providers.json 的渠道链接是客户购买入口,只和联盟推广线对账;
|
|
669
|
+
// 代理商线是伙伴注册入口,不该进 providers.json。
|
|
670
|
+
if (line === 'affiliate' && link && l.verified === false) {
|
|
671
|
+
findings.push({
|
|
672
|
+
provider: p.id, line, kind: 'link_present_but_unverified',
|
|
673
|
+
message: '本机已有渠道链接,但该线官方来源未核实(providers.json 与调研结论对不上,需登录后台确认归属)'
|
|
674
|
+
});
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
const st = (p.status || {})[line];
|
|
678
|
+
if (line === 'affiliate' && !link && (st === 'ready' || st === 'apply')) {
|
|
679
|
+
findings.push({
|
|
680
|
+
provider: p.id, line, kind: 'missing_link',
|
|
681
|
+
message: `状态为 ${st},但 providers.json 没有客户侧推广链接`
|
|
682
|
+
});
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
if (l.verified_at) {
|
|
686
|
+
const age = Math.floor((now - new Date(`${l.verified_at}T00:00:00Z`).getTime()) / 86400000);
|
|
687
|
+
if (age > staleDays) {
|
|
688
|
+
findings.push({
|
|
689
|
+
provider: p.id, line, kind: 'stale', age_days: age,
|
|
690
|
+
message: `核验于 ${l.verified_at},已 ${age} 天(阈值 ${staleDays})`
|
|
691
|
+
});
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
if (prov && link && p.kind === 'domestic') {
|
|
697
|
+
const allowed = officialDomains(prov, p);
|
|
698
|
+
const h = registrable(hostOf(link));
|
|
699
|
+
if (h && allowed.length && !allowed.includes(h)) {
|
|
700
|
+
findings.push({
|
|
701
|
+
provider: p.id, line: 'affiliate', kind: 'link_host_mismatch',
|
|
702
|
+
message: `渠道链接在 ${h},不在官方域(${allowed.join(', ')})`
|
|
703
|
+
});
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
return findings;
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
async function promoRunSync(io, opts) {
|
|
711
|
+
const staleDays = Math.max(1, parseInt(opts.staleDays || '30', 10) || 30);
|
|
712
|
+
let source = 'local';
|
|
713
|
+
let siteNote = null;
|
|
714
|
+
|
|
715
|
+
if (!opts.localOnly) {
|
|
716
|
+
const apiBase = (process.env.SRVPRICE_API || 'https://www.srvprice.com').replace(/\/+$/, '');
|
|
717
|
+
const url = `${apiBase}/api/promos`;
|
|
718
|
+
try {
|
|
719
|
+
const res = await fetch(url, { signal: AbortSignal.timeout(8000) });
|
|
720
|
+
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
|
721
|
+
const doc = await res.json();
|
|
722
|
+
if (!doc || !Array.isArray(doc.providers) || !doc.providers.length) {
|
|
723
|
+
throw new Error('返回结构不对(缺少 providers)');
|
|
724
|
+
}
|
|
725
|
+
const bad = doc.providers.find((p) => !p || !p.id || !p.lines);
|
|
726
|
+
if (bad) throw new Error('返回里有缺少 id/lines 的条目');
|
|
727
|
+
core.ensureDir(path.dirname(core.cachePath('promos')), 0o700);
|
|
728
|
+
core.writeJson0600(core.cachePath('promos'), doc);
|
|
729
|
+
source = 'site';
|
|
730
|
+
siteNote = `已从 ${url} 更新 ${doc.providers.length} 家`;
|
|
731
|
+
} catch (e) {
|
|
732
|
+
siteNote = `站点暂无可用 promos 接口(${url}:${e.message}),本次只做本地对账`;
|
|
733
|
+
io.warn(siteNote, { source: 'local', url });
|
|
734
|
+
}
|
|
735
|
+
} else {
|
|
736
|
+
siteNote = '--local-only:跳过站点同步';
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
const promos = dataFor(io, opts, 'promos');
|
|
740
|
+
const provs = dataFor(io, opts, 'providers');
|
|
741
|
+
const findings = promoFindings(promos, provs, staleDays);
|
|
742
|
+
|
|
743
|
+
if (io.json) {
|
|
744
|
+
io.data({
|
|
745
|
+
source,
|
|
746
|
+
site_note: siteNote,
|
|
747
|
+
snapshot_date: promos.snapshot_date,
|
|
748
|
+
stale_days: staleDays,
|
|
749
|
+
count: findings.length,
|
|
750
|
+
findings
|
|
751
|
+
});
|
|
752
|
+
return EXIT.OK;
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
io.data({
|
|
756
|
+
rows: findings.map((f, n) => ({
|
|
757
|
+
n: n + 1,
|
|
758
|
+
provider: f.provider,
|
|
759
|
+
line: f.line === 'affiliate' ? '联盟' : '代理',
|
|
760
|
+
kind: f.kind,
|
|
761
|
+
message: f.message
|
|
762
|
+
})),
|
|
763
|
+
columns: [
|
|
764
|
+
{ key: 'n', label: '#' },
|
|
765
|
+
{ key: 'provider', label: '厂商' },
|
|
766
|
+
{ key: 'line', label: '线' },
|
|
767
|
+
{ key: 'kind', label: '类型' },
|
|
768
|
+
{ key: 'message', label: '说明' }
|
|
769
|
+
],
|
|
770
|
+
footer: `数据源:${source};核验阈值 ${staleDays} 天。findings 是提示不是错误;确认后可用 promo link set 更新链接。`
|
|
771
|
+
});
|
|
772
|
+
return EXIT.OK;
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
// ---- promo link:维护客户侧推广链接(默认写本机缓存,--bundled 写仓库并备份)----
|
|
776
|
+
|
|
777
|
+
function stripPrivate(obj) {
|
|
778
|
+
const out = Object.assign({}, obj);
|
|
779
|
+
delete out._source;
|
|
780
|
+
return out;
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
function readRawJson(file) {
|
|
784
|
+
try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch (_) { return null; }
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
async function promoLink(io, opts, rest) {
|
|
788
|
+
const action = rest[0];
|
|
789
|
+
if (!['show', 'set', 'unset'].includes(action)) {
|
|
790
|
+
throw new CliError(EXIT.USAGE, '用法:srvprice promo link show|set|unset(--name --url --key --bundled)');
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
const bundledFile = path.join(core.dataOrigin('providers'), 'providers.json');
|
|
794
|
+
const cacheFile = core.cachePath('providers');
|
|
795
|
+
const bundledRaw = readRawJson(bundledFile);
|
|
796
|
+
if (!bundledRaw) throw new CliError(EXIT.GENERAL, `数据表缺失:${bundledFile}`);
|
|
797
|
+
const cacheRaw = readRawJson(cacheFile);
|
|
798
|
+
const effective = stripPrivate(core.loadData('providers'));
|
|
799
|
+
|
|
800
|
+
if (action === 'show') {
|
|
801
|
+
const name = val(opts, 'name');
|
|
802
|
+
const items = [];
|
|
803
|
+
for (const p of effective.providers) {
|
|
804
|
+
if (name && p.id !== name) continue;
|
|
805
|
+
const source = cacheRaw && cacheRaw.providers.some((x) => x.id === p.id) ? 'cache' : 'bundled';
|
|
806
|
+
if (p.channel_url) {
|
|
807
|
+
items.push({ provider: p.id, label: p.label, key: null, url: p.channel_url, source, verified_at: p.verified_at || null, note: p.entry_note || null });
|
|
808
|
+
}
|
|
809
|
+
for (const [key, url] of Object.entries(p.channel_urls || {})) {
|
|
810
|
+
items.push({ provider: p.id, label: p.label, key, url, source, verified_at: p.verified_at || null, note: p.entry_note || null });
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
if (name && !items.length) {
|
|
814
|
+
throw new CliError(EXIT.NOT_FOUND, `未找到厂商或其链接:${name}`, { provider: name });
|
|
815
|
+
}
|
|
816
|
+
if (io.json) {
|
|
817
|
+
io.data({ count: items.length, items });
|
|
818
|
+
return EXIT.OK;
|
|
819
|
+
}
|
|
820
|
+
io.data({
|
|
821
|
+
rows: items.map((i) => ({ provider: i.label, key: i.key || '(主链接)', url: i.url, source: i.source })),
|
|
822
|
+
columns: [
|
|
823
|
+
{ key: 'provider', label: '厂商' },
|
|
824
|
+
{ key: 'key', label: '位置' },
|
|
825
|
+
{ key: 'url', label: '链接' },
|
|
826
|
+
{ key: 'source', label: '来源' }
|
|
827
|
+
],
|
|
828
|
+
footer: '来源 cache = 本机覆盖(promo link set 写入);bundled = 仓库内置数据。'
|
|
829
|
+
});
|
|
830
|
+
return EXIT.OK;
|
|
831
|
+
}
|
|
832
|
+
|
|
833
|
+
const name = val(opts, 'name');
|
|
834
|
+
if (!name) throw new CliError(EXIT.USAGE, `用法:srvprice promo link ${action} --name <provider-id>`);
|
|
835
|
+
|
|
836
|
+
if (action === 'set') {
|
|
837
|
+
const url = val(opts, 'url');
|
|
838
|
+
const key = val(opts, 'key');
|
|
839
|
+
if (!url) throw new CliError(EXIT.USAGE, '用法:srvprice promo link set --name <id> --url <https://...> [--key <子键>]');
|
|
840
|
+
if (!/^https:\/\//i.test(url)) throw new CliError(EXIT.USAGE, '只接受 https 链接');
|
|
841
|
+
|
|
842
|
+
const promos = dataFor(io, opts, 'promos');
|
|
843
|
+
const entry = promos.providers.find((x) => x.id === name);
|
|
844
|
+
const provider = effective.providers.find((x) => x.id === name);
|
|
845
|
+
if (!provider && !entry) throw new CliError(EXIT.NOT_FOUND, `未找到厂商:${name}`, { provider: name });
|
|
846
|
+
|
|
847
|
+
const allowed = writableDomains(provider, effective, entry);
|
|
848
|
+
const host = registrable(hostOf(url));
|
|
849
|
+
if (allowed.length && !allowed.includes(host)) {
|
|
850
|
+
throw new CliError(EXIT.USAGE,
|
|
851
|
+
`链接域 ${host || '(无法解析)'} 不在该厂商允许域(${allowed.join(', ')});确认无误可先手工改 providers.json`);
|
|
852
|
+
}
|
|
853
|
+
|
|
854
|
+
if (opts.bundled && !opts.yes && !process.stdin.isTTY) {
|
|
855
|
+
throw new CliError(EXIT.UNCONFIRMED, '写仓库数据需要确认:非交互环境请显式加 --yes');
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
const base = opts.bundled ? JSON.parse(JSON.stringify(bundledRaw)) : stripPrivate(effective);
|
|
859
|
+
let target = base.providers.find((x) => x.id === name);
|
|
860
|
+
if (!target) {
|
|
861
|
+
target = {
|
|
862
|
+
id: name,
|
|
863
|
+
label: entry ? entry.label : name,
|
|
864
|
+
kind: entry ? entry.kind : 'domestic',
|
|
865
|
+
official: entry && entry.lines && entry.lines.affiliate && entry.lines.affiliate.url
|
|
866
|
+
? new URL(entry.lines.affiliate.url).origin + '/'
|
|
867
|
+
: null,
|
|
868
|
+
verified_at: core.todayIso()
|
|
869
|
+
};
|
|
870
|
+
base.providers.push(target);
|
|
871
|
+
}
|
|
872
|
+
const previous = key
|
|
873
|
+
? (target.channel_urls && target.channel_urls[key]) || null
|
|
874
|
+
: (target.channel_url || null);
|
|
875
|
+
|
|
876
|
+
if (key) {
|
|
877
|
+
target.channel_urls = Object.assign({}, target.channel_urls);
|
|
878
|
+
target.channel_urls[key] = url;
|
|
879
|
+
} else {
|
|
880
|
+
target.channel_url = url;
|
|
881
|
+
}
|
|
882
|
+
target.entry_note = val(opts, 'note') || `promo link set(${core.todayIso()})`;
|
|
883
|
+
target.verified_at = val(opts, 'verifiedAt') || core.todayIso();
|
|
884
|
+
|
|
885
|
+
const file = opts.bundled ? bundledFile : cacheFile;
|
|
886
|
+
core.ensureDir(path.dirname(file), 0o700);
|
|
887
|
+
let backup = null;
|
|
888
|
+
if (opts.bundled && fs.existsSync(file)) {
|
|
889
|
+
backup = `${file}.bak-${core.nowIso().replace(/[-:T]/g, '').slice(0, 15)}`;
|
|
890
|
+
fs.copyFileSync(file, backup);
|
|
891
|
+
}
|
|
892
|
+
core.writeJson0600(file, base);
|
|
893
|
+
|
|
894
|
+
const summary = {
|
|
895
|
+
provider: name,
|
|
896
|
+
key: key || null,
|
|
897
|
+
url,
|
|
898
|
+
previous,
|
|
899
|
+
target: opts.bundled ? 'bundled' : 'cache',
|
|
900
|
+
file,
|
|
901
|
+
backup,
|
|
902
|
+
verified_at: target.verified_at,
|
|
903
|
+
note: opts.bundled ? '已写入仓库数据;缓存若存在会覆盖它,必要时清理本机 cache/providers.json' : '已写入本机覆盖;仓库数据未改'
|
|
904
|
+
};
|
|
905
|
+
if (io.json) io.data(summary);
|
|
906
|
+
else io.data({ text: `${opts.bundled ? '仓库数据' : '本机缓存'}已更新:${name}${key ? '.' + key : ''} → ${url}` });
|
|
907
|
+
return EXIT.OK;
|
|
908
|
+
}
|
|
909
|
+
|
|
910
|
+
// unset:只回滚本机覆盖
|
|
911
|
+
if (!cacheRaw) {
|
|
912
|
+
const out = { provider: name, removed: false, reason: '没有本机覆盖,链接本来就是仓库数据' };
|
|
913
|
+
if (io.json) io.data(out); else io.data({ text: out.reason });
|
|
914
|
+
return EXIT.OK;
|
|
915
|
+
}
|
|
916
|
+
const key = val(opts, 'key');
|
|
917
|
+
const cp = cacheRaw.providers.find((x) => x.id === name);
|
|
918
|
+
if (!cp) {
|
|
919
|
+
const out = { provider: name, removed: false, reason: '本机覆盖里没有这家厂商' };
|
|
920
|
+
if (io.json) io.data(out); else io.data({ text: out.reason });
|
|
921
|
+
return EXIT.OK;
|
|
922
|
+
}
|
|
923
|
+
const before = key ? (cp.channel_urls && cp.channel_urls[key]) : cp.channel_url;
|
|
924
|
+
const bp0 = bundledRaw.providers.find((x) => x.id === name);
|
|
925
|
+
const restored = key
|
|
926
|
+
? (bp0 && bp0.channel_urls ? bp0.channel_urls[key] : undefined)
|
|
927
|
+
: (bp0 ? bp0.channel_url : undefined);
|
|
928
|
+
if (key) {
|
|
929
|
+
cp.channel_urls = Object.assign({}, cp.channel_urls);
|
|
930
|
+
if (restored) cp.channel_urls[key] = restored;
|
|
931
|
+
else delete cp.channel_urls[key];
|
|
932
|
+
} else if (restored) {
|
|
933
|
+
cp.channel_url = restored;
|
|
934
|
+
} else {
|
|
935
|
+
delete cp.channel_url;
|
|
936
|
+
}
|
|
937
|
+
if (!cp.channel_url && (!cp.channel_urls || !Object.keys(cp.channel_urls).length)) {
|
|
938
|
+
cacheRaw.providers = cacheRaw.providers.filter((x) => x.id !== name);
|
|
939
|
+
} else {
|
|
940
|
+
// 覆盖时改过的元数据(entry_note / verified_at 等)一并回到仓库口径
|
|
941
|
+
const bp = bundledRaw.providers.find((x) => x.id === name);
|
|
942
|
+
if (bp) {
|
|
943
|
+
for (const k of Object.keys(bp)) {
|
|
944
|
+
if (k === 'channel_url' || k === 'channel_urls') continue;
|
|
945
|
+
cp[k] = bp[k];
|
|
946
|
+
}
|
|
947
|
+
}
|
|
948
|
+
}
|
|
949
|
+
const sameAsBundled = JSON.stringify(cacheRaw) === JSON.stringify(bundledRaw);
|
|
950
|
+
if (sameAsBundled) {
|
|
951
|
+
fs.unlinkSync(cacheFile);
|
|
952
|
+
} else {
|
|
953
|
+
core.writeJson0600(cacheFile, cacheRaw);
|
|
954
|
+
}
|
|
955
|
+
const out = { provider: name, key: key || null, removed_value: before || null, cache_kept: !sameAsBundled };
|
|
956
|
+
if (io.json) io.data(out);
|
|
957
|
+
else io.data({ text: `已恢复仓库链接:${name}${key ? '.' + key : ''}${before ? `(移除覆盖 ${before})` : ''}` });
|
|
958
|
+
return EXIT.OK;
|
|
959
|
+
}
|
|
960
|
+
|
|
961
|
+
async function cmdBuy(io, opts, profilePick, sub) {
|
|
962
|
+
need(sub, ['url', 'open'], 'buy');
|
|
963
|
+
const { values: profile } = profilePick();
|
|
964
|
+
const planId = val(opts, 'planId') || val(opts, 'id');
|
|
965
|
+
const providerId = val(opts, 'provider');
|
|
966
|
+
|
|
967
|
+
const provs = dataFor(io, opts, 'providers');
|
|
968
|
+
// ★ 2026-11-20 第二期「走优惠」:没有套餐数据的厂商(DO/Vultr 等)按 provider 级入口
|
|
969
|
+
if (!planId && providerId) {
|
|
970
|
+
return buyProvider(io, opts, provs, providerId, sub);
|
|
971
|
+
}
|
|
972
|
+
if (!planId) throw new CliError(EXIT.USAGE,
|
|
973
|
+
'用法:srvprice buy url|open --plan-id <plan-id>(或 --provider <provider-id>)');
|
|
974
|
+
|
|
975
|
+
const plans = dataFor(io, opts, 'plans');
|
|
976
|
+
const plan = plans.plans.find((x) => x.id === planId);
|
|
977
|
+
if (!plan) throw new CliError(EXIT.NOT_FOUND, `未找到套餐:${planId}`, { plan_id: planId });
|
|
978
|
+
const provider = provs.providers.find((p) => p.id === plan.provider);
|
|
979
|
+
const url = pickChannel(provider, plan.region);
|
|
980
|
+
if (!url) throw new CliError(EXIT.NOT_FOUND, `厂商 ${plan.provider} 没有可用的渠道入口`, { provider: plan.provider });
|
|
981
|
+
|
|
982
|
+
const summary = {
|
|
983
|
+
plan_id: plan.id,
|
|
984
|
+
provider: plan.provider_label,
|
|
985
|
+
name: plan.name,
|
|
986
|
+
region: plan.region_label,
|
|
987
|
+
price_snapshot_cny: plan.price.first_year_cny,
|
|
988
|
+
price_note: plan.price.note,
|
|
989
|
+
verified_at: plan.verified_at,
|
|
990
|
+
url,
|
|
991
|
+
promo_note: (provider && provider.entry_note) || null,
|
|
992
|
+
attribution: ATTRIBUTION_NOTE,
|
|
993
|
+
warning: '价格以厂商官网实时价为准;CLI 显示的是核验时间的快照。CLI 不代下单、不收款。'
|
|
994
|
+
};
|
|
995
|
+
|
|
996
|
+
if (sub === 'url' || opts.noOpen) {
|
|
997
|
+
if (io.json) io.data(summary);
|
|
998
|
+
else io.data({ text: url });
|
|
999
|
+
return EXIT.OK;
|
|
1000
|
+
}
|
|
1001
|
+
|
|
1002
|
+
// open:先打印摘要(含厂商/机型/价格/地域/链接),再开浏览器
|
|
1003
|
+
io.data(summary);
|
|
1004
|
+
if (!process.stdout.isTTY && !opts.yes) {
|
|
1005
|
+
io.warn('非交互环境不会自动打开浏览器;需要 URL 请用 buy url,或显式加 --yes 打开');
|
|
1006
|
+
return EXIT.OK;
|
|
1007
|
+
}
|
|
1008
|
+
openBrowser(url);
|
|
1009
|
+
return EXIT.OK;
|
|
1010
|
+
}
|
|
1011
|
+
|
|
1012
|
+
// 归因说明统一口径:第二期「走优惠」只做链接引导,不做 API 埋链(腾讯明确禁止,且归因不认)。
|
|
1013
|
+
const ATTRIBUTION_NOTE = '链接含推荐归因:只有从该链接进入厂商官网、在官网注册并购买才计入推荐;API 下单带不上归因,客户端不会在 API 调用里埋链接。';
|
|
1014
|
+
|
|
1015
|
+
// provider 级入口:给没有套餐数据的厂商(DO / Vultr 等)一个「走优惠」入口
|
|
1016
|
+
async function buyProvider(io, opts, provs, providerId, sub) {
|
|
1017
|
+
const p = provs.providers.find((x) => x.id === providerId);
|
|
1018
|
+
if (!p) throw new CliError(EXIT.NOT_FOUND, `未找到厂商:${providerId}`, { provider: providerId });
|
|
1019
|
+
const url = pickChannel(p, null);
|
|
1020
|
+
if (!url) throw new CliError(EXIT.NOT_FOUND, `厂商 ${providerId} 没有已核实的渠道入口`, { provider: providerId });
|
|
1021
|
+
|
|
1022
|
+
const summary = {
|
|
1023
|
+
provider: p.id,
|
|
1024
|
+
provider_label: p.label,
|
|
1025
|
+
kind: p.kind || null,
|
|
1026
|
+
url,
|
|
1027
|
+
promo_note: p.entry_note || null,
|
|
1028
|
+
promo_verified_at: p.verified_at || null,
|
|
1029
|
+
official: p.official || null,
|
|
1030
|
+
attribution: ATTRIBUTION_NOTE,
|
|
1031
|
+
warning: 'CLI 只打印/打开链接,不代下单、不收款;优惠口径以官网实时页面为准。'
|
|
1032
|
+
};
|
|
1033
|
+
|
|
1034
|
+
if (sub === 'url' || opts.noOpen) {
|
|
1035
|
+
if (io.json) io.data(summary);
|
|
1036
|
+
else io.data({ text: url });
|
|
1037
|
+
return EXIT.OK;
|
|
1038
|
+
}
|
|
1039
|
+
|
|
1040
|
+
io.data(summary);
|
|
1041
|
+
if (!process.stdout.isTTY && !opts.yes) {
|
|
1042
|
+
io.warn('非交互环境不会自动打开浏览器;需要 URL 请用 buy url,或显式加 --yes 打开');
|
|
1043
|
+
return EXIT.OK;
|
|
1044
|
+
}
|
|
1045
|
+
openBrowser(url);
|
|
1046
|
+
return EXIT.OK;
|
|
1047
|
+
}
|
|
1048
|
+
|
|
1049
|
+
function pickChannel(provider, region) {
|
|
1050
|
+
if (!provider) return null;
|
|
1051
|
+
// 厂商级入口(不给地域):主链接优先——promo link set 改的就是它
|
|
1052
|
+
if (region == null && provider.channel_url) return provider.channel_url;
|
|
1053
|
+
if (provider.channel_urls) {
|
|
1054
|
+
const key = region === 'hk' ? 'hk' : region === 'overseas' ? 'overseas' : 'cn';
|
|
1055
|
+
if (provider.channel_urls[key]) return provider.channel_urls[key];
|
|
1056
|
+
}
|
|
1057
|
+
return provider.channel_url || null;
|
|
1058
|
+
}
|
|
1059
|
+
|
|
1060
|
+
function openBrowser(url) {
|
|
1061
|
+
const p = process.platform;
|
|
1062
|
+
const args = p === 'win32' ? ['/c', 'start', '""', url]
|
|
1063
|
+
: p === 'darwin' ? [url] : [url];
|
|
1064
|
+
const bin = p === 'win32' ? 'cmd' : p === 'darwin' ? 'open' : 'xdg-open';
|
|
1065
|
+
try {
|
|
1066
|
+
const child = spawn(bin, args, { detached: true, stdio: 'ignore', windowsHide: true });
|
|
1067
|
+
child.unref();
|
|
1068
|
+
} catch (e) {
|
|
1069
|
+
// 打开失败不影响已打印的 URL
|
|
1070
|
+
}
|
|
1071
|
+
}
|
|
1072
|
+
|
|
1073
|
+
async function cmdSetup(io, opts, profilePick, sub, rest) {
|
|
1074
|
+
need(sub, ['list', 'show'], 'setup');
|
|
1075
|
+
const { values: profile } = profilePick();
|
|
1076
|
+
const data = dataFor(io, opts, 'setup');
|
|
1077
|
+
freshness(io, opts, profile, data.topics, '指引');
|
|
1078
|
+
|
|
1079
|
+
if (sub === 'show') {
|
|
1080
|
+
const topic = rest[0] || val(opts, 'name') || val(opts, 'topic');
|
|
1081
|
+
if (!topic) throw new CliError(EXIT.USAGE, `用法:srvprice setup show <主题>(可用:${data.topics.map((t) => t.id).join(', ')})`);
|
|
1082
|
+
const t = data.topics.find((x) => x.id === topic);
|
|
1083
|
+
if (!t) throw new CliError(EXIT.NOT_FOUND, `未找到主题:${topic}`, { topic, available: data.topics.map((x) => x.id) });
|
|
1084
|
+
const provider = val(opts, 'provider');
|
|
1085
|
+
if (io.json) {
|
|
1086
|
+
io.data({ topic: t, provider_filter: provider, note: '只给指引,不远程执行;命令由用户在自己服务器上运行。' });
|
|
1087
|
+
return EXIT.OK;
|
|
1088
|
+
}
|
|
1089
|
+
const lines = [`${t.title} — ${t.summary}`, ''];
|
|
1090
|
+
for (const s of t.steps) lines.push(`${s.n}. ${s.text}`);
|
|
1091
|
+
lines.push('', `验证:${t.verify}`);
|
|
1092
|
+
if (t.confidence === 'generic') lines.push('(通用指引,未绑定厂商原文;与厂商控制台文案对不上时以厂商文档为准)');
|
|
1093
|
+
io.data({ text: lines.join('\n') });
|
|
1094
|
+
return EXIT.OK;
|
|
1095
|
+
}
|
|
1096
|
+
|
|
1097
|
+
const provider = val(opts, 'provider');
|
|
1098
|
+
const os = val(opts, 'os');
|
|
1099
|
+
let topics = data.topics.slice();
|
|
1100
|
+
if (provider) topics = topics.filter((t) => t.applies_to.includes(provider) || t.applies_to.includes('*'));
|
|
1101
|
+
if (os) topics = topics.filter((t) => t.os.includes(os) || t.os.includes('*'));
|
|
1102
|
+
|
|
1103
|
+
if (io.json) { io.data({ count: topics.length, items: topics }); return EXIT.OK; }
|
|
1104
|
+
io.data({
|
|
1105
|
+
rows: topics.map((t) => ({ id: t.id, title: t.title, os: t.os.join(','), confidence: t.confidence })),
|
|
1106
|
+
columns: [
|
|
1107
|
+
{ key: 'id', label: '主题' },
|
|
1108
|
+
{ key: 'title', label: '标题' },
|
|
1109
|
+
{ key: 'os', label: '系统' },
|
|
1110
|
+
{ key: 'confidence', label: '证据' }
|
|
1111
|
+
],
|
|
1112
|
+
footer: 'setup 只给文本指引,不 SSH、不改你的服务器。'
|
|
1113
|
+
});
|
|
1114
|
+
return EXIT.OK;
|
|
1115
|
+
}
|
|
1116
|
+
|
|
1117
|
+
// ---------------------------------------------------------------------------
|
|
1118
|
+
// 配置
|
|
1119
|
+
// ---------------------------------------------------------------------------
|
|
1120
|
+
|
|
1121
|
+
async function cmdSms(io, opts, sub) {
|
|
1122
|
+
need(sub, ['status', 'send', 'config'], 'sms');
|
|
1123
|
+
|
|
1124
|
+
if (sub === 'status') {
|
|
1125
|
+
const st = smslib.status();
|
|
1126
|
+
io.data(st);
|
|
1127
|
+
return st.ready ? EXIT.OK : EXIT.CRED;
|
|
1128
|
+
}
|
|
1129
|
+
|
|
1130
|
+
if (sub === 'config') {
|
|
1131
|
+
io.data({
|
|
1132
|
+
config_path: smslib.CONFIG_PATH(),
|
|
1133
|
+
template: smslib.EXAMPLE,
|
|
1134
|
+
note: '阿里云需已审核签名和模板;也可用 SMS_ACCESS_KEY / SMS_ACCESS_SECRET / SMS_SIGN_NAME / SMS_TEMPLATE_CODE / SMS_PHONE 环境变量',
|
|
1135
|
+
});
|
|
1136
|
+
return EXIT.OK;
|
|
1137
|
+
}
|
|
1138
|
+
|
|
1139
|
+
const text = val(opts, 'text');
|
|
1140
|
+
if (!text) throw new CliError(EXIT.USAGE, '用法:srvprice sms send --text "..." [--to 手机号] [--dry-run]');
|
|
1141
|
+
const to = asArray(opts.to).filter(Boolean);
|
|
1142
|
+
const r = await smslib.send({ text, to, dryRun: !!opts.dryRun });
|
|
1143
|
+
io.data(r);
|
|
1144
|
+
if (r.error === 'sms_config_missing') {
|
|
1145
|
+
throw new CliError(EXIT.CRED, `短信配置缺失:${r.config_path};缺少 ${(r.missing || []).join(', ')}`);
|
|
1146
|
+
}
|
|
1147
|
+
if (r.error) throw new CliError(EXIT.GENERAL, `短信发送失败:${r.error}`);
|
|
1148
|
+
return r.ok ? EXIT.OK : EXIT.VENDOR;
|
|
1149
|
+
}
|
|
1150
|
+
|
|
1151
|
+
async function cmdConfig(io, opts, config, sub) {
|
|
1152
|
+
need(sub, ['show', 'list', 'use', 'set', 'reset'], 'config');
|
|
1153
|
+
|
|
1154
|
+
if (sub === 'list') {
|
|
1155
|
+
const names = Object.keys(config.profiles);
|
|
1156
|
+
io.data(io.json
|
|
1157
|
+
? { active: config.active_profile, profiles: names.map((n) => ({ name: n, active: n === config.active_profile, values: config.profiles[n] })) }
|
|
1158
|
+
: {
|
|
1159
|
+
rows: names.map((n) => ({ name: n, active: n === config.active_profile ? '*' : '', currency: config.profiles[n].currency, region: config.profiles[n].default_region || '—' })),
|
|
1160
|
+
columns: [{ key: 'name', label: '名字' }, { key: 'active', label: '激活' }, { key: 'currency', label: '币种' }, { key: 'region', label: '默认地域' }],
|
|
1161
|
+
footer: `配置文件:${core.CONFIG_PATH()}`
|
|
1162
|
+
});
|
|
1163
|
+
return EXIT.OK;
|
|
1164
|
+
}
|
|
1165
|
+
|
|
1166
|
+
if (sub === 'show') {
|
|
1167
|
+
const pick = core.resolveProfile(config, opts);
|
|
1168
|
+
io.data({ profile: pick.name, source: pick.source, values: pick.values, config_path: core.CONFIG_PATH() });
|
|
1169
|
+
return EXIT.OK;
|
|
1170
|
+
}
|
|
1171
|
+
|
|
1172
|
+
if (sub === 'use') {
|
|
1173
|
+
const name = val(opts, 'name');
|
|
1174
|
+
if (!name) throw new CliError(EXIT.USAGE, '用法:srvprice config use --name <profile>');
|
|
1175
|
+
if (!config.profiles[name]) throw new CliError(EXIT.NOT_FOUND, `profile 不存在:${name}`);
|
|
1176
|
+
config.active_profile = name;
|
|
1177
|
+
core.saveConfig(config);
|
|
1178
|
+
io.data({ active_profile: name, config_path: core.CONFIG_PATH() });
|
|
1179
|
+
return EXIT.OK;
|
|
1180
|
+
}
|
|
1181
|
+
|
|
1182
|
+
if (sub === 'set') {
|
|
1183
|
+
const key = val(opts, 'key');
|
|
1184
|
+
const value = val(opts, 'value');
|
|
1185
|
+
if (!key) throw new CliError(EXIT.USAGE, '用法:srvprice config set --key <key> --value <value>');
|
|
1186
|
+
if (/key|secret|token|password/i.test(key)) {
|
|
1187
|
+
throw new CliError(EXIT.USAGE,
|
|
1188
|
+
'厂商密钥不放选购偏好:用 srvprice vendor add --name <厂商>(凭据单独存 ~/.srvprice/credentials.json)');
|
|
1189
|
+
}
|
|
1190
|
+
const pick = core.resolveProfile(config, opts);
|
|
1191
|
+
const allowed = Object.keys(core.DEFAULT_PROFILE);
|
|
1192
|
+
if (!allowed.includes(key)) {
|
|
1193
|
+
throw new CliError(EXIT.USAGE, `不支持的配置键:${key}(可用:${allowed.join(', ')})`);
|
|
1194
|
+
}
|
|
1195
|
+
let parsed = value;
|
|
1196
|
+
if (value === 'true') parsed = true;
|
|
1197
|
+
else if (value === 'false') parsed = false;
|
|
1198
|
+
else if (/^\d+$/.test(String(value))) parsed = Number(value);
|
|
1199
|
+
else if (key === 'providers') parsed = String(value).split(',').map((s) => s.trim()).filter(Boolean);
|
|
1200
|
+
config.profiles[pick.name][key] = parsed;
|
|
1201
|
+
core.saveConfig(config);
|
|
1202
|
+
io.data({ profile: pick.name, key, value: parsed });
|
|
1203
|
+
return EXIT.OK;
|
|
1204
|
+
}
|
|
1205
|
+
|
|
1206
|
+
// reset
|
|
1207
|
+
const name = val(opts, 'name') || config.active_profile;
|
|
1208
|
+
if (!config.profiles[name]) throw new CliError(EXIT.NOT_FOUND, `profile 不存在:${name}`);
|
|
1209
|
+
config.profiles[name] = Object.assign({}, core.DEFAULT_PROFILE);
|
|
1210
|
+
core.saveConfig(config);
|
|
1211
|
+
io.data({ profile: name, reset: true });
|
|
1212
|
+
return EXIT.OK;
|
|
1213
|
+
}
|
|
1214
|
+
|
|
1215
|
+
// ---------------------------------------------------------------------------
|
|
1216
|
+
// 主机线
|
|
1217
|
+
// ---------------------------------------------------------------------------
|
|
1218
|
+
|
|
1219
|
+
function hostRow(h) {
|
|
1220
|
+
return {
|
|
1221
|
+
id: h.id,
|
|
1222
|
+
provider: h.provider,
|
|
1223
|
+
name: h.name || '—',
|
|
1224
|
+
region: h.region || '—',
|
|
1225
|
+
status: h.status,
|
|
1226
|
+
ip: h.public_ipv4 || '—'
|
|
1227
|
+
};
|
|
1228
|
+
}
|
|
1229
|
+
|
|
1230
|
+
const HOST_COLUMNS = [
|
|
1231
|
+
{ key: 'id', label: 'ID' },
|
|
1232
|
+
{ key: 'name', label: '名称' },
|
|
1233
|
+
{ key: 'region', label: '地域' },
|
|
1234
|
+
{ key: 'status', label: '状态' },
|
|
1235
|
+
{ key: 'ip', label: '公网 IP' }
|
|
1236
|
+
];
|
|
1237
|
+
|
|
1238
|
+
// ---- 开端口(目前仅西部数码安全组 API)----
|
|
1239
|
+
function asList(v) {
|
|
1240
|
+
if (Array.isArray(v)) return v;
|
|
1241
|
+
if (v && Array.isArray(v.items)) return v.items;
|
|
1242
|
+
if (v && Array.isArray(v.data)) return v.data;
|
|
1243
|
+
if (v && v.data && Array.isArray(v.data.items)) return v.data.items;
|
|
1244
|
+
return [];
|
|
1245
|
+
}
|
|
1246
|
+
|
|
1247
|
+
function openPortError(e) {
|
|
1248
|
+
const msg = String((e && e.message) || e);
|
|
1249
|
+
if (/IAM permission|RetCode:\s*299|permission error/i.test(msg)) {
|
|
1250
|
+
return new CliError(EXIT.CRED, `厂商权限不足:${msg}`, { reason: 'permission_denied' });
|
|
1251
|
+
}
|
|
1252
|
+
if (/auth|credential|Unauthorized|InvalidAccessKey|AuthFailure|not logged in|No credential|InvalidClientTokenId|secretId is invalid|access token is required/i.test(msg)) {
|
|
1253
|
+
return new CliError(EXIT.CRED, `厂商鉴权失败:${msg}`, { reason: 'auth_failed' });
|
|
1254
|
+
}
|
|
1255
|
+
return new CliError(EXIT.VENDOR, msg);
|
|
1256
|
+
}
|
|
1257
|
+
|
|
1258
|
+
// 阿里 / 腾讯 / 火山:只新建专用组 + 加规则,不绑实例(派单红线)
|
|
1259
|
+
async function cmdOpenPortVendor(io, opts, adapter, provider) {
|
|
1260
|
+
const ip = val(opts, 'ip');
|
|
1261
|
+
if (!ip) throw new CliError(EXIT.USAGE, '用法:srvprice host open-port --provider <aliyun|tencent|volcengine> --region <r> --ip <公网IP> --port <n> --source <IP>');
|
|
1262
|
+
const port = Number(val(opts, 'port'));
|
|
1263
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) throw new CliError(EXIT.USAGE, '--port 需要 1-65535');
|
|
1264
|
+
const proto = String(val(opts, 'proto') || 'tcp').toLowerCase();
|
|
1265
|
+
if (!['tcp', 'udp', 'icmp'].includes(proto)) throw new CliError(EXIT.USAGE, '--proto 只支持 tcp/udp/icmp');
|
|
1266
|
+
const source = val(opts, 'source');
|
|
1267
|
+
if (!source) throw new CliError(EXIT.USAGE, '必须给 --source 限来源 IP;确要放开所有来源请显式 --source 0.0.0.0 --yes');
|
|
1268
|
+
if (source === '0.0.0.0' && !opts.yes) throw new CliError(EXIT.UNCONFIRMED, '放开所有来源需要 --yes');
|
|
1269
|
+
const region = val(opts, 'region');
|
|
1270
|
+
if (!region) throw new CliError(EXIT.USAGE, '--region 必填(查实例与安全组都要地域)');
|
|
1271
|
+
if (val(opts, 'group')) {
|
|
1272
|
+
throw new CliError(EXIT.USAGE, '本轮红线:只新建专用安全组,不接受 --group 去改现有组');
|
|
1273
|
+
}
|
|
1274
|
+
const priority = Number(val(opts, 'priority') || 100);
|
|
1275
|
+
if (!Number.isInteger(priority) || priority < 1 || priority > 100) throw new CliError(EXIT.USAGE, '--priority 须在 1-100(数字越小优先级越高)');
|
|
1276
|
+
|
|
1277
|
+
const ctx = { region, vendorProfile: val(opts, 'vendorProfile'), timeout: 120000 };
|
|
1278
|
+
let server;
|
|
1279
|
+
let groups;
|
|
1280
|
+
try {
|
|
1281
|
+
server = await adapter.serverByIp(ctx, ip);
|
|
1282
|
+
if (!server) {
|
|
1283
|
+
throw new CliError(EXIT.NOT_FOUND, `没在 ${provider}(${region})账号下找到 IP 为 ${ip} 的实例`, { ip, region });
|
|
1284
|
+
}
|
|
1285
|
+
if (!server.vpcId) throw new CliError(EXIT.VENDOR, '实例缺少 VpcId,无法新建安全组', { ip });
|
|
1286
|
+
groups = await adapter.listGroups(ctx);
|
|
1287
|
+
} catch (e) {
|
|
1288
|
+
throw e instanceof CliError ? e : openPortError(e);
|
|
1289
|
+
}
|
|
1290
|
+
|
|
1291
|
+
const name = val(opts, 'name') || firewall.groupNameFor(ip, port);
|
|
1292
|
+
if (/[^\x00-\x7F]/.test(name)) throw new CliError(EXIT.USAGE, '安全组名只能用 ASCII');
|
|
1293
|
+
const description = `srvprice open-port ${port} ${core.todayIso()}`;
|
|
1294
|
+
const existing = groups.find((g) => g.name === name) || null;
|
|
1295
|
+
const rule = { proto, port, source, priority };
|
|
1296
|
+
const createArgs = adapter.createArgs(ctx, server, name, description);
|
|
1297
|
+
const addArgs = existing ? adapter.addRuleArgs(ctx, existing.id, rule) : null;
|
|
1298
|
+
|
|
1299
|
+
const plan = {
|
|
1300
|
+
provider,
|
|
1301
|
+
region,
|
|
1302
|
+
server,
|
|
1303
|
+
rule,
|
|
1304
|
+
group: {
|
|
1305
|
+
create: { name, description, vpc_id: server.vpcId },
|
|
1306
|
+
existing: existing ? { id: existing.id, name: existing.name } : null
|
|
1307
|
+
},
|
|
1308
|
+
deploy: { skipped: '本轮红线:只建组加规则,不绑定实例' },
|
|
1309
|
+
commands: [
|
|
1310
|
+
{ step: existing ? 'skip_create' : 'create_group', argv: existing ? null : [adapter.bin, ...createArgs] },
|
|
1311
|
+
{ step: 'add_rule', argv: [adapter.bin, ...(addArgs || adapter.addRuleArgs(ctx, '<新安全组ID-创建后回填>', rule))] }
|
|
1312
|
+
]
|
|
1313
|
+
};
|
|
1314
|
+
|
|
1315
|
+
if (opts.dryRun || !opts.yes) {
|
|
1316
|
+
if (io.json) io.data({ mode: 'dry-run', plan });
|
|
1317
|
+
else io.data({ text: `计划:${proto}/${port} ← ${source};新建安全组 ${name}(VPC ${server.vpcId});不绑定实例` });
|
|
1318
|
+
return EXIT.OK;
|
|
1319
|
+
}
|
|
1320
|
+
|
|
1321
|
+
const done = [];
|
|
1322
|
+
let gid = existing ? existing.id : null;
|
|
1323
|
+
try {
|
|
1324
|
+
if (!gid) {
|
|
1325
|
+
const r = await firewall.run(adapter.bin, createArgs, ctx);
|
|
1326
|
+
gid = adapter.groupIdFrom(r.stdout);
|
|
1327
|
+
if (!gid) throw new CliError(EXIT.VENDOR, '安全组已创建但取不到 groupid,请到控制台确认', { name });
|
|
1328
|
+
done.push({ step: 'create_group', groupid: gid, name });
|
|
1329
|
+
} else {
|
|
1330
|
+
done.push({ step: 'create_group', skipped: 'exists', groupid: gid });
|
|
1331
|
+
}
|
|
1332
|
+
await firewall.run(adapter.bin, adapter.addRuleArgs(ctx, gid, rule), ctx);
|
|
1333
|
+
done.push({ step: 'add_rule', groupid: gid, port, source });
|
|
1334
|
+
} catch (e) {
|
|
1335
|
+
throw e instanceof CliError ? e : openPortError(e);
|
|
1336
|
+
}
|
|
1337
|
+
io.data({ ok: true, plan, done });
|
|
1338
|
+
return EXIT.OK;
|
|
1339
|
+
}
|
|
1340
|
+
|
|
1341
|
+
async function cmdOpenPort(io, opts) {
|
|
1342
|
+
const provider = val(opts, 'provider') || 'west';
|
|
1343
|
+
if (provider !== 'west') {
|
|
1344
|
+
const adapter = firewall.get(provider);
|
|
1345
|
+
if (!adapter) {
|
|
1346
|
+
throw new CliError(EXIT.USAGE, `--provider 支持 west / ${firewall.ids().join(' / ')}`);
|
|
1347
|
+
}
|
|
1348
|
+
return cmdOpenPortVendor(io, opts, adapter, provider);
|
|
1349
|
+
}
|
|
1350
|
+
const ip = val(opts, 'ip');
|
|
1351
|
+
if (!ip) {
|
|
1352
|
+
throw new CliError(EXIT.USAGE,
|
|
1353
|
+
'用法:srvprice host open-port --ip <服务器公网IP> --port <n> --source <允许来源IP> [--proto tcp] [--group <id>] [--deploy --yes]');
|
|
1354
|
+
}
|
|
1355
|
+
const port = Number(val(opts, 'port'));
|
|
1356
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) {
|
|
1357
|
+
throw new CliError(EXIT.USAGE, '--port 需要 1-65535');
|
|
1358
|
+
}
|
|
1359
|
+
const proto = String(val(opts, 'proto') || 'tcp').toLowerCase();
|
|
1360
|
+
if (!['tcp', 'udp', 'icmp'].includes(proto)) {
|
|
1361
|
+
throw new CliError(EXIT.USAGE, '--proto 只支持 tcp/udp/icmp');
|
|
1362
|
+
}
|
|
1363
|
+
const source = val(opts, 'source');
|
|
1364
|
+
if (!source) {
|
|
1365
|
+
throw new CliError(EXIT.USAGE, '必须给 --source 限来源 IP;确要放开所有来源请显式 --source 0.0.0.0 --yes');
|
|
1366
|
+
}
|
|
1367
|
+
if (source === '0.0.0.0' && !opts.yes) {
|
|
1368
|
+
throw new CliError(EXIT.UNCONFIRMED, '放开所有来源需要 --yes');
|
|
1369
|
+
}
|
|
1370
|
+
const priority = Number(val(opts, 'priority') || 10);
|
|
1371
|
+
if (!Number.isInteger(priority) || priority < 1 || priority > 1024) {
|
|
1372
|
+
throw new CliError(EXIT.USAGE, '--priority 须在 1-1024');
|
|
1373
|
+
}
|
|
1374
|
+
|
|
1375
|
+
const creds = westlib.creds();
|
|
1376
|
+
if (!creds.user || !creds.pass) {
|
|
1377
|
+
throw new CliError(EXIT.CRED,
|
|
1378
|
+
'缺西部数码凭据:请用 vault 注入 WEST_USERNAME / WEST_API_PASSWORD 后运行(vault-cli run ...)',
|
|
1379
|
+
{ reason: 'auth_failed', provider: 'west' });
|
|
1380
|
+
}
|
|
1381
|
+
|
|
1382
|
+
// 只允许对自己账号下的服务器动安全组
|
|
1383
|
+
const servers = asList(await westlib.listServers({ limit: 200 }));
|
|
1384
|
+
const server = servers.find((s) => String(s.allocateip || s.ip || '') === ip);
|
|
1385
|
+
if (!server) {
|
|
1386
|
+
throw new CliError(EXIT.NOT_FOUND,
|
|
1387
|
+
`没在西部数码账号下找到 IP 为 ${ip} 的服务器(不替你给别处开端口)`, { ip });
|
|
1388
|
+
}
|
|
1389
|
+
|
|
1390
|
+
const groups = asList(await westlib.listFirewallGroups());
|
|
1391
|
+
const wantedGroup = val(opts, 'group');
|
|
1392
|
+
let group = null;
|
|
1393
|
+
if (wantedGroup) {
|
|
1394
|
+
group = groups.find((g) => String(g.sysid || g.groupid || g.id) === String(wantedGroup));
|
|
1395
|
+
if (!group) throw new CliError(EXIT.NOT_FOUND, `安全组不存在:${wantedGroup}`, { group: wantedGroup });
|
|
1396
|
+
} else {
|
|
1397
|
+
group = groups.find((g) => JSON.stringify(g).includes(ip)) ||
|
|
1398
|
+
groups.find((g) => String(g.group_name || '').includes(ip.replace(/\./g, '-'))) || null;
|
|
1399
|
+
}
|
|
1400
|
+
const gid = group ? String(group.sysid || group.groupid || group.id || '') : null;
|
|
1401
|
+
|
|
1402
|
+
let duplicate = null;
|
|
1403
|
+
if (gid) {
|
|
1404
|
+
const rules = asList(await westlib.groupRules({ groupid: gid }));
|
|
1405
|
+
duplicate = rules.find((r) =>
|
|
1406
|
+
Number(r.dstport) === port &&
|
|
1407
|
+
String(r.proto || '').toLowerCase() === proto &&
|
|
1408
|
+
(String(r.srcip || '') === source ||
|
|
1409
|
+
(source === '0.0.0.0' && String(r.srcip_type) === '0'))
|
|
1410
|
+
) || null;
|
|
1411
|
+
}
|
|
1412
|
+
|
|
1413
|
+
const plan = {
|
|
1414
|
+
provider: 'west',
|
|
1415
|
+
server: {
|
|
1416
|
+
id: server.id !== undefined ? String(server.id) : null,
|
|
1417
|
+
ip,
|
|
1418
|
+
os: server.os || null,
|
|
1419
|
+
room: server.serverroom || null
|
|
1420
|
+
},
|
|
1421
|
+
rule: { proto, port, source, priority, action: 'pass' },
|
|
1422
|
+
group: group
|
|
1423
|
+
? { groupid: gid, name: group.group_name || group.name || null, memo: group.group_memo || group.memo || null }
|
|
1424
|
+
: {
|
|
1425
|
+
create: {
|
|
1426
|
+
name: val(opts, 'name') || `srvprice-${ip.replace(/\./g, '-')}-${port}`,
|
|
1427
|
+
memo: val(opts, 'memo') || `srvprice open-port ${port} ${core.todayIso()}`
|
|
1428
|
+
}
|
|
1429
|
+
},
|
|
1430
|
+
duplicate: duplicate ? { sysid: duplicate.sysid || null } : null,
|
|
1431
|
+
deploy: opts.deploy
|
|
1432
|
+
? { sip: ip, note: '部署后安全组接管该机出入站' }
|
|
1433
|
+
: { skipped: '未加 --deploy:只建规则,不生效' }
|
|
1434
|
+
};
|
|
1435
|
+
|
|
1436
|
+
if (opts.dryRun || !opts.yes) {
|
|
1437
|
+
if (io.json) {
|
|
1438
|
+
io.data({
|
|
1439
|
+
mode: 'dry-run',
|
|
1440
|
+
plan,
|
|
1441
|
+
warning: '西部数码安全组首次部署会接管出入站:先确认 22/25 等现网端口已在规则里放通;本命令默认不部署。'
|
|
1442
|
+
});
|
|
1443
|
+
} else {
|
|
1444
|
+
io.data({
|
|
1445
|
+
text: `计划:${proto} ${port} ← ${source}` +
|
|
1446
|
+
`(${plan.group.groupid ? '安全组 ' + plan.group.groupid : '新建安全组'});` +
|
|
1447
|
+
`${plan.deploy.skipped || '将部署到 ' + ip}`
|
|
1448
|
+
});
|
|
1449
|
+
}
|
|
1450
|
+
return EXIT.OK;
|
|
1451
|
+
}
|
|
1452
|
+
|
|
1453
|
+
const done = [];
|
|
1454
|
+
let finalGid = gid;
|
|
1455
|
+
if (!finalGid) {
|
|
1456
|
+
const c = await westlib.addFirewallGroup({
|
|
1457
|
+
name: plan.group.create.name || undefined,
|
|
1458
|
+
memo: plan.group.create.memo
|
|
1459
|
+
});
|
|
1460
|
+
finalGid = String((c && (c.sysid || c.groupid || c.id)) ||
|
|
1461
|
+
(c && c.data && (c.data.sysid || c.data.groupid || c.data.id)) || '');
|
|
1462
|
+
if (!finalGid) {
|
|
1463
|
+
const again = asList(await westlib.listFirewallGroups());
|
|
1464
|
+
const g = again.find((x) =>
|
|
1465
|
+
String(x.group_name || x.name || '') === String(plan.group.create.name || '') ||
|
|
1466
|
+
String(x.group_memo || x.memo || '') === String(plan.group.create.memo || ''));
|
|
1467
|
+
finalGid = g ? String(g.sysid || g.groupid || g.id) : '';
|
|
1468
|
+
}
|
|
1469
|
+
if (!finalGid) {
|
|
1470
|
+
throw new CliError(EXIT.VENDOR, '安全组已创建但取不到 groupid,请到控制台确认', {
|
|
1471
|
+
memo: plan.group.create.memo
|
|
1472
|
+
});
|
|
1473
|
+
}
|
|
1474
|
+
done.push({ step: 'create_group', groupid: finalGid });
|
|
1475
|
+
}
|
|
1476
|
+
|
|
1477
|
+
if (!duplicate) {
|
|
1478
|
+
await westlib.addGroupRule({
|
|
1479
|
+
groupid: finalGid, proto, port, srcip: source,
|
|
1480
|
+
srcip_type: source === '0.0.0.0' ? 0 : 1,
|
|
1481
|
+
allow_all: source === '0.0.0.0', priority, action: 'pass'
|
|
1482
|
+
});
|
|
1483
|
+
done.push({ step: 'add_rule', groupid: finalGid, port, source });
|
|
1484
|
+
} else {
|
|
1485
|
+
done.push({ step: 'add_rule', skipped: 'duplicate', sysid: duplicate.sysid || null });
|
|
1486
|
+
}
|
|
1487
|
+
|
|
1488
|
+
if (opts.deploy) {
|
|
1489
|
+
await westlib.deployGroup({ groupid: finalGid, sip: ip, enable: true });
|
|
1490
|
+
done.push({ step: 'deploy', groupid: finalGid, sip: ip });
|
|
1491
|
+
}
|
|
1492
|
+
|
|
1493
|
+
io.data({ ok: true, plan, done });
|
|
1494
|
+
return EXIT.OK;
|
|
1495
|
+
}
|
|
1496
|
+
|
|
1497
|
+
async function cmdHost(io, opts, profilePick, sub) {
|
|
1498
|
+
need(sub, ['list', 'status', 'start', 'stop', 'reboot', 'wait', 'snapshots', 'open-port'], 'host');
|
|
1499
|
+
const { values: profile } = profilePick();
|
|
1500
|
+
|
|
1501
|
+
if (sub === 'open-port') return cmdOpenPort(io, opts);
|
|
1502
|
+
|
|
1503
|
+
if (sub === 'list') {
|
|
1504
|
+
const { hosts, errors } = await hostlib.listAcross(opts, profile, io);
|
|
1505
|
+
const statusFilter = val(opts, 'status');
|
|
1506
|
+
const filtered = statusFilter ? hosts.filter((h) => h.status === statusFilter) : hosts;
|
|
1507
|
+
filtered.sort((a, b) => a.id.localeCompare(b.id));
|
|
1508
|
+
if (io.json) {
|
|
1509
|
+
io.data({ count: filtered.length, items: filtered, errors, note: '每行 ID 形如 <provider>:<instance-id>,直接用于 host status/start/stop。' });
|
|
1510
|
+
return errors.length && filtered.length === 0 ? EXIT.CRED : EXIT.OK;
|
|
1511
|
+
}
|
|
1512
|
+
io.data({
|
|
1513
|
+
rows: filtered.map(hostRow),
|
|
1514
|
+
columns: HOST_COLUMNS,
|
|
1515
|
+
footer: filtered.length ? `共 ${filtered.length} 台。未接入 / 未登录的厂商见 stderr。` : '没有可列出的主机。'
|
|
1516
|
+
});
|
|
1517
|
+
return errors.length && filtered.length === 0 ? EXIT.CRED : EXIT.OK;
|
|
1518
|
+
}
|
|
1519
|
+
|
|
1520
|
+
if (sub === 'status') {
|
|
1521
|
+
const id = requireId(opts);
|
|
1522
|
+
const { adapter, ctx, host } = await hostlib.findHost(id, opts, profile);
|
|
1523
|
+
// ★ 有自己的状态接口的厂商(西部数码):列表里没有状态,这里补一次真实状态
|
|
1524
|
+
let h = host;
|
|
1525
|
+
if (adapter && adapter.getStatus) {
|
|
1526
|
+
try {
|
|
1527
|
+
h = await adapter.getStatus(ctx, host);
|
|
1528
|
+
} catch (e) {
|
|
1529
|
+
h = Object.assign({}, host, { status_info: '状态查询失败:' + e.message });
|
|
1530
|
+
}
|
|
1531
|
+
}
|
|
1532
|
+
io.data({ host: h, checked_at: core.nowIso() });
|
|
1533
|
+
return EXIT.OK;
|
|
1534
|
+
}
|
|
1535
|
+
|
|
1536
|
+
// 云快照列表(目前仅西部数码;只读)
|
|
1537
|
+
if (sub === 'snapshots') {
|
|
1538
|
+
const id = requireId(opts);
|
|
1539
|
+
const { adapter, ctx, host } = await hostlib.findHost(id, opts, profile);
|
|
1540
|
+
if (!adapter || !adapter.snapshots) {
|
|
1541
|
+
throw new CliError(EXIT.USAGE,
|
|
1542
|
+
`${host.provider} 适配器暂不支持 snapshots(当前支持:west)`);
|
|
1543
|
+
}
|
|
1544
|
+
const snap = await adapter.snapshots(ctx, host);
|
|
1545
|
+
io.data({ host_id: host.id, provider: host.provider, snapshots: snap, checked_at: core.nowIso() });
|
|
1546
|
+
return EXIT.OK;
|
|
1547
|
+
}
|
|
1548
|
+
|
|
1549
|
+
if (sub === 'wait') {
|
|
1550
|
+
const id = requireId(opts);
|
|
1551
|
+
const until = val(opts, 'until');
|
|
1552
|
+
if (!until || !['running', 'stopped'].includes(until)) {
|
|
1553
|
+
throw new CliError(EXIT.USAGE, '用法:srvprice host wait --id <id> --until running|stopped');
|
|
1554
|
+
}
|
|
1555
|
+
const { adapter, ctx, host } = await hostlib.findHost(id, opts, profile);
|
|
1556
|
+
if (host.status === until) { io.data({ host, waited: false }); return EXIT.OK; }
|
|
1557
|
+
// 跨地域列出的实例:轮询也用实例所在地域,避免每个地域都查一遍
|
|
1558
|
+
const actx = hostlib.actionCtx(ctx, host);
|
|
1559
|
+
const final = await hostlib.waitFor(adapter, actx, host.instance_id, until, io, opts);
|
|
1560
|
+
io.data({ host: final, waited: true });
|
|
1561
|
+
return EXIT.OK;
|
|
1562
|
+
}
|
|
1563
|
+
|
|
1564
|
+
// 写操作:start / stop / reboot
|
|
1565
|
+
const id = requireId(opts);
|
|
1566
|
+
// ★ 只读模式:profile.read_only 或 SRVPRICE_READONLY=1 时,写操作无论 --yes 一律拒绝。
|
|
1567
|
+
// 配只读 AK/SK 时用它兜底,避免「忘了」变成误操作;凭据本身也会在厂商侧拒绝。
|
|
1568
|
+
const readOnly = profile.read_only === true || process.env.SRVPRICE_READONLY === '1';
|
|
1569
|
+
if (readOnly) {
|
|
1570
|
+
throw new CliError(EXIT.USAGE,
|
|
1571
|
+
`只读模式已开启,拒绝执行 ${sub}:${id}。验证用 host list / status 即可;` +
|
|
1572
|
+
'要开关机请先关掉只读(srvprice config set --key read_only --value false,或去掉 SRVPRICE_READONLY)',
|
|
1573
|
+
{ action: sub, host_id: id, reason: 'read_only' });
|
|
1574
|
+
}
|
|
1575
|
+
const { adapter, ctx: baseCtx, host } = await hostlib.findHost(id, opts, profile);
|
|
1576
|
+
// ★ 跨地域列出的实例:没显式给 --region 时,用实例所在地域(AWS 的 AZ、腾讯的可用区反推)
|
|
1577
|
+
const ctx = hostlib.actionCtx(baseCtx, host);
|
|
1578
|
+
const target = hostlib.TARGET_STATUS[sub];
|
|
1579
|
+
|
|
1580
|
+
if (opts.dryRun) {
|
|
1581
|
+
const plan = {
|
|
1582
|
+
dry_run: true,
|
|
1583
|
+
action: sub,
|
|
1584
|
+
host,
|
|
1585
|
+
target_status: target,
|
|
1586
|
+
vendor_command: (() => {
|
|
1587
|
+
const c = hostlib.actionCommand(host.provider, sub, host.instance_id, ctx);
|
|
1588
|
+
return [c.bin, ...c.args].join(' ');
|
|
1589
|
+
})(),
|
|
1590
|
+
note: '--dry-run 已校验凭据以外的一切;加 --yes 或交互确认后去掉 --dry-run 执行。'
|
|
1591
|
+
};
|
|
1592
|
+
io.data(plan);
|
|
1593
|
+
return EXIT.OK;
|
|
1594
|
+
}
|
|
1595
|
+
|
|
1596
|
+
const summary = `${host.provider} / ${host.name || host.instance_id}(${host.public_ipv4 || '无公网 IP'},当前 ${host.status})→ 目标 ${target}`;
|
|
1597
|
+
if (!opts.yes) {
|
|
1598
|
+
if (!process.stdin.isTTY) {
|
|
1599
|
+
throw new CliError(EXIT.UNCONFIRMED,
|
|
1600
|
+
`写操作未确认而阻断:${sub} ${host.id}。非交互环境必须显式加 --yes,或先用 --dry-run 预览。`,
|
|
1601
|
+
{ action: sub, host_id: host.id, target_status: target });
|
|
1602
|
+
}
|
|
1603
|
+
io.info(`即将执行:${summary}`);
|
|
1604
|
+
const ok = await core.confirmPrompt(`确认 ${sub}?`);
|
|
1605
|
+
if (!ok) {
|
|
1606
|
+
throw new CliError(EXIT.UNCONFIRMED, '用户取消,未执行', { action: sub, host_id: host.id });
|
|
1607
|
+
}
|
|
1608
|
+
}
|
|
1609
|
+
|
|
1610
|
+
const res = await hostlib.runAction(host.provider, sub, host.instance_id, ctx);
|
|
1611
|
+
io.info(`已提交:${res.command}`);
|
|
1612
|
+
|
|
1613
|
+
// 执行后回读状态,不凭「已受理」就报成功
|
|
1614
|
+
let after;
|
|
1615
|
+
try {
|
|
1616
|
+
const hosts = await adapter.list(ctx);
|
|
1617
|
+
after = hosts.find((h) => h.instance_id === host.instance_id) || null;
|
|
1618
|
+
} catch (e) {
|
|
1619
|
+
after = null;
|
|
1620
|
+
io.warn(`执行后回读状态失败:${e.message}`);
|
|
1621
|
+
}
|
|
1622
|
+
|
|
1623
|
+
if (opts.wait && target) {
|
|
1624
|
+
const final = await hostlib.waitFor(adapter, ctx, host.instance_id, target, io, opts);
|
|
1625
|
+
io.data({ action: sub, host: final, previous_status: host.status, vendor_command: res.command });
|
|
1626
|
+
return EXIT.OK;
|
|
1627
|
+
}
|
|
1628
|
+
|
|
1629
|
+
io.data({
|
|
1630
|
+
action: sub,
|
|
1631
|
+
submitted: true,
|
|
1632
|
+
host_id: host.id,
|
|
1633
|
+
previous_status: host.status,
|
|
1634
|
+
status_after: after ? after.status : '未知(回读失败)',
|
|
1635
|
+
vendor_command: res.command,
|
|
1636
|
+
note: '厂商通常异步处理;需要确定结果请加 --wait 或运行 srvprice host wait。'
|
|
1637
|
+
});
|
|
1638
|
+
return EXIT.OK;
|
|
1639
|
+
}
|
|
1640
|
+
|
|
1641
|
+
function requireId(opts) {
|
|
1642
|
+
const id = Array.isArray(opts.id) ? opts.id[0] : val(opts, 'id');
|
|
1643
|
+
if (!id) throw new CliError(EXIT.USAGE, '用法:需要 --id <provider>:<instance-id>(先运行 srvprice host list)');
|
|
1644
|
+
return id;
|
|
1645
|
+
}
|
|
1646
|
+
|
|
1647
|
+
// ---------------------------------------------------------------------------
|
|
1648
|
+
// vendor
|
|
1649
|
+
// ---------------------------------------------------------------------------
|
|
1650
|
+
|
|
1651
|
+
const VENDOR_ENV = {
|
|
1652
|
+
aliyun: ['SRVPRICE_ALIYUN_KEY', 'SRVPRICE_ALIYUN_SECRET'],
|
|
1653
|
+
aws: ['SRVPRICE_AWS_ACCESS_KEY_ID', 'SRVPRICE_AWS_SECRET_ACCESS_KEY'],
|
|
1654
|
+
tencent: ['SRVPRICE_TENCENT_SECRET_ID', 'SRVPRICE_TENCENT_SECRET_KEY'],
|
|
1655
|
+
ucloud: ['SRVPRICE_UCLOUD_PUBLIC_KEY', 'SRVPRICE_UCLOUD_PRIVATE_KEY'],
|
|
1656
|
+
jdcloud: ['SRVPRICE_JDCLOUD_ACCESS_KEY', 'SRVPRICE_JDCLOUD_SECRET_KEY'],
|
|
1657
|
+
volcengine: ['SRVPRICE_VOLCENGINE_ACCESS_KEY', 'SRVPRICE_VOLCENGINE_SECRET_KEY'],
|
|
1658
|
+
baidu: ['SRVPRICE_BAIDU_ACCESS_KEY_ID', 'SRVPRICE_BAIDU_SECRET_ACCESS_KEY'],
|
|
1659
|
+
west: ['SRVPRICE_WEST_USER', 'SRVPRICE_WEST_API_PASSWORD'],
|
|
1660
|
+
ctyun: ['SRVPRICE_CTYUN_AK', 'SRVPRICE_CTYUN_SK'],
|
|
1661
|
+
doctl: ['SRVPRICE_DOCTL_TOKEN'],
|
|
1662
|
+
hcloud: ['SRVPRICE_HCLOUD_TOKEN'],
|
|
1663
|
+
vultr: ['SRVPRICE_VULTR_API_KEY'],
|
|
1664
|
+
linode: ['SRVPRICE_LINODE_TOKEN']
|
|
1665
|
+
};
|
|
1666
|
+
|
|
1667
|
+
async function cmdVendor(io, opts, config, sub) {
|
|
1668
|
+
need(sub, ['list', 'add', 'status', 'remove'], 'vendor');
|
|
1669
|
+
const creds = core.loadCreds();
|
|
1670
|
+
|
|
1671
|
+
if (sub === 'list' || sub === 'status') {
|
|
1672
|
+
const only = val(opts, 'name');
|
|
1673
|
+
const ids = only ? [only] : hostlib.VENDOR_IDS;
|
|
1674
|
+
for (const id of ids) hostlib.getAdapter(id);
|
|
1675
|
+
const probes = [];
|
|
1676
|
+
for (const id of ids) probes.push(await hostlib.probe(id, opts.timeout ? Number(opts.timeout) * 1000 : 15000));
|
|
1677
|
+
|
|
1678
|
+
const items = [];
|
|
1679
|
+
for (const p of probes) {
|
|
1680
|
+
const credProbe = p.installed ? await hostlib.probeCreds(p.id, 15000) : { checked: false, configured: null, detail: '' };
|
|
1681
|
+
const stored = creds.vendors[p.id];
|
|
1682
|
+
const envKeys = VENDOR_ENV[p.id] || [];
|
|
1683
|
+
items.push({
|
|
1684
|
+
id: p.id,
|
|
1685
|
+
label: p.label,
|
|
1686
|
+
bin: p.bin,
|
|
1687
|
+
installed: p.installed,
|
|
1688
|
+
version: p.version,
|
|
1689
|
+
cli_configured: credProbe.configured,
|
|
1690
|
+
cli_cred_detail: credProbe.detail || null,
|
|
1691
|
+
credential: {
|
|
1692
|
+
stored: !!stored,
|
|
1693
|
+
masked: stored ? core.mask(stored.key || stored.token || null) : null,
|
|
1694
|
+
env_present: envKeys.some((k) => !!process.env[k]),
|
|
1695
|
+
added_at: stored ? stored.added_at : null
|
|
1696
|
+
},
|
|
1697
|
+
spec_verified: hostlib.getAdapter(p.id).spec_verified || 'verified',
|
|
1698
|
+
mode: 'wrap-vendor-cli',
|
|
1699
|
+
note: '主机操作走厂商 CLI 自己的登录态;本机凭据文件用于将来直调 API 与授权记录。'
|
|
1700
|
+
});
|
|
1701
|
+
}
|
|
1702
|
+
|
|
1703
|
+
if (io.json) { io.data({ count: items.length, items }); return EXIT.OK; }
|
|
1704
|
+
io.data({
|
|
1705
|
+
rows: items.map((i) => ({
|
|
1706
|
+
id: i.id,
|
|
1707
|
+
label: i.label,
|
|
1708
|
+
installed: i.installed ? '已装' : '未装',
|
|
1709
|
+
version: i.version || '—',
|
|
1710
|
+
cred: i.credential.stored ? i.credential.masked : (i.credential.env_present ? 'env' : '无'),
|
|
1711
|
+
spec: i.spec_verified === 'verified' ? '' : (i.spec_verified === 'read_only' ? '只读(写命令未核实)' : '输出格式待核')
|
|
1712
|
+
})),
|
|
1713
|
+
columns: [
|
|
1714
|
+
{ key: 'id', label: '厂商' },
|
|
1715
|
+
{ key: 'label', label: '名称' },
|
|
1716
|
+
{ key: 'installed', label: 'CLI' },
|
|
1717
|
+
{ key: 'version', label: '版本' },
|
|
1718
|
+
{ key: 'cred', label: '凭据' },
|
|
1719
|
+
{ key: 'spec', label: '备注' }
|
|
1720
|
+
],
|
|
1721
|
+
footer: '未装的厂商:先按其官方文档安装 CLI 并登录,再运行 srvprice host list。'
|
|
1722
|
+
});
|
|
1723
|
+
return EXIT.OK;
|
|
1724
|
+
}
|
|
1725
|
+
|
|
1726
|
+
if (sub === 'add') {
|
|
1727
|
+
const name = val(opts, 'name');
|
|
1728
|
+
if (!name) throw new CliError(EXIT.USAGE, `用法:srvprice vendor add --name <${hostlib.VENDOR_IDS.join('|')}>`);
|
|
1729
|
+
hostlib.getAdapter(name);
|
|
1730
|
+
|
|
1731
|
+
if (opts.key !== undefined) {
|
|
1732
|
+
throw new CliError(EXIT.USAGE,
|
|
1733
|
+
'密钥不接受命令行参数(会进 shell 历史与进程列表)。请用交互输入,或设环境变量后重跑。');
|
|
1734
|
+
}
|
|
1735
|
+
|
|
1736
|
+
const envKeys = VENDOR_ENV[name] || [];
|
|
1737
|
+
const fromEnv = {};
|
|
1738
|
+
for (const k of envKeys) if (process.env[k]) fromEnv[k] = process.env[k];
|
|
1739
|
+
|
|
1740
|
+
let record;
|
|
1741
|
+
if (Object.keys(fromEnv).length) {
|
|
1742
|
+
const firstKey = envKeys[0];
|
|
1743
|
+
record = {
|
|
1744
|
+
key: fromEnv[firstKey],
|
|
1745
|
+
secret: envKeys[1] ? fromEnv[envKeys[1]] || null : null,
|
|
1746
|
+
added_at: core.nowIso(),
|
|
1747
|
+
source: 'env'
|
|
1748
|
+
};
|
|
1749
|
+
io.info(`从环境变量读取 ${name} 凭据`);
|
|
1750
|
+
} else if (process.stdin.isTTY) {
|
|
1751
|
+
const v1 = await core.readSecretHidden(`${name} 凭据(输入不回显): `);
|
|
1752
|
+
if (!v1) throw new CliError(EXIT.USAGE, '未输入凭据,已取消');
|
|
1753
|
+
let v2 = null;
|
|
1754
|
+
if (envKeys.length > 1) {
|
|
1755
|
+
v2 = await core.readSecretHidden(`${name} 第二段凭据(如 secret,输入不回显;无则回车): `);
|
|
1756
|
+
v2 = v2 || null;
|
|
1757
|
+
}
|
|
1758
|
+
record = { key: v1, secret: v2, added_at: core.nowIso(), source: 'prompt' };
|
|
1759
|
+
} else {
|
|
1760
|
+
throw new CliError(EXIT.USAGE,
|
|
1761
|
+
`非交互环境请通过环境变量注入:${envKeys.join(' / ')}(不落盘、不进 shell 历史)`);
|
|
1762
|
+
}
|
|
1763
|
+
|
|
1764
|
+
creds.vendors[name] = record;
|
|
1765
|
+
core.saveCreds(creds);
|
|
1766
|
+
io.data({
|
|
1767
|
+
vendor: name,
|
|
1768
|
+
stored: true,
|
|
1769
|
+
masked: core.mask(record.key),
|
|
1770
|
+
path: core.CREDS_PATH(),
|
|
1771
|
+
mode: core.fileMode(core.CREDS_PATH()),
|
|
1772
|
+
note: '凭据只存本机、不上传;主机操作仍走厂商 CLI 自己的登录态。'
|
|
1773
|
+
});
|
|
1774
|
+
return EXIT.OK;
|
|
1775
|
+
}
|
|
1776
|
+
|
|
1777
|
+
// remove
|
|
1778
|
+
const name = val(opts, 'name');
|
|
1779
|
+
if (!name) throw new CliError(EXIT.USAGE, '用法:srvprice vendor remove --name <vendor>');
|
|
1780
|
+
hostlib.getAdapter(name);
|
|
1781
|
+
if (!creds.vendors[name]) throw new CliError(EXIT.NOT_FOUND, `没有 ${name} 的本机凭据`);
|
|
1782
|
+
|
|
1783
|
+
if (!opts.yes) {
|
|
1784
|
+
if (!process.stdin.isTTY) {
|
|
1785
|
+
throw new CliError(EXIT.UNCONFIRMED, '删除凭据需要确认:非交互环境请显式加 --yes');
|
|
1786
|
+
}
|
|
1787
|
+
const ok = await core.confirmPrompt(`删除 ${name} 的本机凭据?`);
|
|
1788
|
+
if (!ok) throw new CliError(EXIT.UNCONFIRMED, '用户取消,未删除');
|
|
1789
|
+
}
|
|
1790
|
+
delete creds.vendors[name];
|
|
1791
|
+
core.saveCreds(creds);
|
|
1792
|
+
io.data({ vendor: name, removed: true });
|
|
1793
|
+
return EXIT.OK;
|
|
1794
|
+
}
|
|
1795
|
+
|
|
1796
|
+
// ---------------------------------------------------------------------------
|
|
1797
|
+
// introspect:机器可读命令结构
|
|
1798
|
+
// ---------------------------------------------------------------------------
|
|
1799
|
+
|
|
1800
|
+
function introspect() {
|
|
1801
|
+
return {
|
|
1802
|
+
name: 'srvprice',
|
|
1803
|
+
version: core.VERSION,
|
|
1804
|
+
binary_aliases: ['srvprice', 'sp'],
|
|
1805
|
+
agent_contract: {
|
|
1806
|
+
stdout: 'only business result (JSON when --output json or stdout is not a TTY)',
|
|
1807
|
+
stderr: 'diagnostics; JSONL in json mode',
|
|
1808
|
+
default_output: 'auto: TTY→text, pipe→json',
|
|
1809
|
+
default_interactive: false,
|
|
1810
|
+
price_freshness: 'every price/deal carries verified_at and source_url; stale data warns on stderr',
|
|
1811
|
+
write_ops: 'host start/stop/reboot require confirmation; non-TTY without --yes exits 7; --dry-run prints vendor command only'
|
|
1812
|
+
},
|
|
1813
|
+
exit_codes: EXIT,
|
|
1814
|
+
vendored_clis: hostlib.VENDOR_IDS,
|
|
1815
|
+
commands: {
|
|
1816
|
+
plan: { subcommands: ['list', 'get', 'compare'], options: ['--provider', '--cpu', '--mem', '--region', '--budget-max', '--new-user-only', '--page', '--page-size'] },
|
|
1817
|
+
recommend: { subcommands: [null, 'wizard'], options: ['--use-case', '--budget', '--region', '--visitors', '--explain'] },
|
|
1818
|
+
deal: { subcommands: ['list', 'get'], options: ['--provider', '--new-user-only', '--ends-before', '--include-expired'] },
|
|
1819
|
+
provider: { subcommands: ['list', 'get'], options: ['--name'] },
|
|
1820
|
+
promo: {
|
|
1821
|
+
subcommands: ['list', 'get', 'actions', 'sync', 'link'],
|
|
1822
|
+
options: ['--name', '--line', '--status', '--local-only', '--stale-days', '--url', '--key', '--bundled', '--yes'],
|
|
1823
|
+
safety: 'never applies to or signs programs; promo link only edits provider URLs (https + vendor domain allowlist); --bundled writes repo data with a .bak backup'
|
|
1824
|
+
},
|
|
1825
|
+
buy: { subcommands: ['url', 'open'], options: ['--plan-id', '--no-open'], safety: 'never places orders; prints/opens official channel URLs only' },
|
|
1826
|
+
setup: { subcommands: ['list', 'show'], options: ['--provider', '--os'], safety: 'text guidance only; never executes remotely' },
|
|
1827
|
+
config: { subcommands: ['show', 'list', 'use', 'set', 'reset'], options: ['--name', '--key', '--value', '--profile'] },
|
|
1828
|
+
host: {
|
|
1829
|
+
subcommands: ['list', 'status', 'start', 'stop', 'reboot', 'wait', 'snapshots', 'open-port'],
|
|
1830
|
+
options: ['--id', '--provider', '--region', '--status', '--wait', '--yes', '--dry-run', '--until', '--ip', '--port', '--proto', '--source', '--group', '--priority', '--deploy', '--memo', '--name'],
|
|
1831
|
+
safety: 'open-port defaults to a dry-run plan; writes require --yes; --deploy is opt-in because a first-time security group takes over inbound/outbound'
|
|
1832
|
+
},
|
|
1833
|
+
vendor: { subcommands: ['list', 'add', 'status', 'remove'], options: ['--name'] }
|
|
1834
|
+
}
|
|
1835
|
+
};
|
|
1836
|
+
}
|
|
1837
|
+
|
|
1838
|
+
// ---------------------------------------------------------------------------
|
|
1839
|
+
// 启动
|
|
1840
|
+
// ---------------------------------------------------------------------------
|
|
1841
|
+
|
|
1842
|
+
main(process.argv.slice(2)).then((code) => {
|
|
1843
|
+
process.exitCode = code;
|
|
1844
|
+
}).catch((e) => {
|
|
1845
|
+
if (e instanceof CliError) {
|
|
1846
|
+
const io = safeWarn();
|
|
1847
|
+
io(e.message, { reason: e.reason, exit_code: e.exitCode });
|
|
1848
|
+
process.exitCode = e.exitCode;
|
|
1849
|
+
} else {
|
|
1850
|
+
process.stderr.write(`错误:${e && e.message ? e.message : e}\n`);
|
|
1851
|
+
if (process.env.SRVPRICE_DEBUG) process.stderr.write(`${e && e.stack ? e.stack : ''}\n`);
|
|
1852
|
+
process.exitCode = EXIT.GENERAL;
|
|
1853
|
+
}
|
|
1854
|
+
});
|
|
1855
|
+
|
|
1856
|
+
function safeWarn() {
|
|
1857
|
+
// 出错时按当前 argv 判断输出模式,避免重复解析失败
|
|
1858
|
+
const jsonMode = process.argv.includes('--json') ||
|
|
1859
|
+
(process.argv.includes('--output') && process.argv[process.argv.indexOf('--output') + 1] === 'json') ||
|
|
1860
|
+
!process.stdout.isTTY;
|
|
1861
|
+
return (message, extra) => {
|
|
1862
|
+
if (jsonMode) process.stderr.write(JSON.stringify(Object.assign({ level: 'error', message }, extra || {})) + '\n');
|
|
1863
|
+
else process.stderr.write(`错误:${message}\n`);
|
|
1864
|
+
};
|
|
1865
|
+
}
|