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/data/setup.json
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
{
|
|
2
|
+
"schema": 1,
|
|
3
|
+
"snapshot_date": "2026-10-30",
|
|
4
|
+
"note": "购后维护指引。只给步骤文本,不 SSH、不改用户服务器。通用步骤不绑定厂商原文,逐条标注 confidence=generic;绑定厂商处写 provider。命令示例由用户自己在服务器上执行。",
|
|
5
|
+
"topics": [
|
|
6
|
+
{
|
|
7
|
+
"id": "open-port",
|
|
8
|
+
"title": "开放端口",
|
|
9
|
+
"summary": "云服务器的端口有两条拦路:厂商安全组 / 防火墙(控制台)和系统内防火墙(ufw / firewalld)。两条都要放行。",
|
|
10
|
+
"applies_to": ["aliyun", "ucloud", "westcn", "tencent", "ctyun", "jdcloud", "baidu"],
|
|
11
|
+
"os": ["linux"],
|
|
12
|
+
"steps": [
|
|
13
|
+
{ "n": 1, "text": "先确认实例绑定的安全组 / 防火墙规则:入方向放行目标端口,来源按需收紧到固定 IP,不要图省事写 0.0.0.0/0。" },
|
|
14
|
+
{ "n": 2, "text": "Web 服务只开放 80 / 443;管理端口(22 / 面板端口)建议限制来源 IP。" },
|
|
15
|
+
{ "n": 3, "text": "系统内防火墙(以 ufw 为例):sudo ufw allow 443/tcp && sudo ufw reload;firewalld:sudo firewall-cmd --add-port=443/tcp --permanent && sudo firewall-cmd --reload。" },
|
|
16
|
+
{ "n": 4, "text": "验证:从外部执行 nc -vz <IP> 443,或在线端口检测;本机自测通过不代表外部可达。" }
|
|
17
|
+
],
|
|
18
|
+
"verify": "从另一台机器(非本机)发起连接,或使用第三方端口检测服务。",
|
|
19
|
+
"source_url": null,
|
|
20
|
+
"verified_at": "2026-10-30",
|
|
21
|
+
"confidence": "generic"
|
|
22
|
+
},
|
|
23
|
+
{
|
|
24
|
+
"id": "ssh-key",
|
|
25
|
+
"title": "SSH 密钥登录",
|
|
26
|
+
"summary": "用密钥替代密码登录。私钥只留在本机,公钥放到服务器 ~/.ssh/authorized_keys。",
|
|
27
|
+
"applies_to": ["aliyun", "ucloud", "westcn", "tencent", "ctyun", "jdcloud", "baidu", "digitalocean", "vultr"],
|
|
28
|
+
"os": ["linux"],
|
|
29
|
+
"steps": [
|
|
30
|
+
{ "n": 1, "text": "本机生成密钥:ssh-keygen -t ed25519 -C \"you@host\",一路回车(如需口令短语可设置)。" },
|
|
31
|
+
{ "n": 2, "text": "复制公钥:ssh-copy-id -i ~/.ssh/id_ed25519.pub user@<IP>;或手工把 id_ed25519.pub 内容追加到服务器 ~/.ssh/authorized_keys。" },
|
|
32
|
+
{ "n": 3, "text": "验证免密登录成功后,再在服务器 /etc/ssh/sshd_config 设 PasswordAuthentication no,然后 systemctl reload sshd。" },
|
|
33
|
+
{ "n": 4, "text": "确认无误前不要关闭当前会话——配错了只能走控制台 VNC 救援。" },
|
|
34
|
+
{ "n": 5, "text": "多数厂商创建实例时支持直接注入公钥;已注入的实例无需再手工复制。" }
|
|
35
|
+
],
|
|
36
|
+
"verify": "新开一个终端 ssh -o PasswordAuthentication=no user@<IP> 能直接进入。",
|
|
37
|
+
"source_url": null,
|
|
38
|
+
"verified_at": "2026-10-30",
|
|
39
|
+
"confidence": "generic"
|
|
40
|
+
},
|
|
41
|
+
{
|
|
42
|
+
"id": "swap",
|
|
43
|
+
"title": "配置 swap(小内存机型)",
|
|
44
|
+
"summary": "1G / 2G 内存机型在跑数据库或构建时容易 OOM,加一块 swap 作缓冲。",
|
|
45
|
+
"applies_to": ["*"],
|
|
46
|
+
"os": ["linux"],
|
|
47
|
+
"steps": [
|
|
48
|
+
{ "n": 1, "text": "创建 swap 文件(以 2G 为例):sudo fallocate -l 2G /swapfile(不支持 fallocate 时用 dd if=/dev/zero of=/swapfile bs=1M count=2048)。" },
|
|
49
|
+
{ "n": 2, "text": "权限收紧:sudo chmod 600 /swapfile。" },
|
|
50
|
+
{ "n": 3, "text": "格式化并启用:sudo mkswap /swapfile && sudo swapon /swapfile。" },
|
|
51
|
+
{ "n": 4, "text": "持久化:把 /swapfile none swap sw 0 0 追加到 /etc/fstab。" },
|
|
52
|
+
{ "n": 5, "text": "调低换出倾向:sudo sysctl vm.swappiness=10,并写入 /etc/sysctl.conf。" }
|
|
53
|
+
],
|
|
54
|
+
"verify": "free -h 中 Swap 行显示已用容量。",
|
|
55
|
+
"source_url": null,
|
|
56
|
+
"verified_at": "2026-10-30",
|
|
57
|
+
"confidence": "generic"
|
|
58
|
+
},
|
|
59
|
+
{
|
|
60
|
+
"id": "docker-install",
|
|
61
|
+
"title": "安装 Docker",
|
|
62
|
+
"summary": "用官方仓库装 Docker Engine,不要用发行版自带的旧版本包。",
|
|
63
|
+
"applies_to": ["*"],
|
|
64
|
+
"os": ["ubuntu", "debian", "centos"],
|
|
65
|
+
"steps": [
|
|
66
|
+
{ "n": 1, "text": "卸载旧包(如装过):sudo apt remove docker docker-engine docker.io containerd runc。" },
|
|
67
|
+
{ "n": 2, "text": "按官方文档添加 Docker 仓库(Ubuntu / Debian 用 apt,CentOS 用 dnf),再 sudo apt install docker-ce docker-ce-cli containerd.io。" },
|
|
68
|
+
{ "n": 3, "text": "国内机器拉镜像慢时配置镜像加速器(写 /etc/docker/daemon.json 的 registry-mirrors),改完 sudo systemctl restart docker。" },
|
|
69
|
+
{ "n": 4, "text": "非 root 使用:sudo usermod -aG docker $USER,重新登录生效。" }
|
|
70
|
+
],
|
|
71
|
+
"verify": "sudo docker run --rm hello-world 输出 Hello from Docker!",
|
|
72
|
+
"source_url": "https://docs.docker.com/engine/install/",
|
|
73
|
+
"verified_at": "2026-10-30",
|
|
74
|
+
"confidence": "generic"
|
|
75
|
+
},
|
|
76
|
+
{
|
|
77
|
+
"id": "icp-filing",
|
|
78
|
+
"title": "ICP 备案判断",
|
|
79
|
+
"summary": "大陆地域建站必须备案;港澳台 / 海外地域不需要工信部 ICP 备案,但个别厂商 FAQ 另有公安联网备案要求。",
|
|
80
|
+
"applies_to": ["aliyun", "ucloud", "westcn", "tencent", "ctyun", "jdcloud", "baidu"],
|
|
81
|
+
"os": ["*"],
|
|
82
|
+
"steps": [
|
|
83
|
+
{ "n": 1, "text": "只买服务器、不解析域名、不开 Web 服务:不触发 ICP 备案。" },
|
|
84
|
+
{ "n": 2, "text": "域名指向大陆节点提供网站服务:必须先备案,未备案域名会被监测封堵。" },
|
|
85
|
+
{ "n": 3, "text": "腾讯云备案要求购买大陆包年包月机 ≥3 个月、备案时剩余有效期 ≥1 个月。" },
|
|
86
|
+
{ "n": 4, "text": "海外 / 港澳台机型:腾讯云明确「无需备案、也不能用于备案」;阿里云香港官方 FAQ 称仍需公安联网备案;天翼云、百度未找到香港免备案声明——不要替用户断言免备案。" }
|
|
87
|
+
],
|
|
88
|
+
"verify": "在目标厂商备案控制台确认当前域名与实例的地域、有效期是否满足要求。",
|
|
89
|
+
"source_url": "https://www.srvprice.com/servers/",
|
|
90
|
+
"verified_at": "2026-10-30",
|
|
91
|
+
"confidence": "page"
|
|
92
|
+
}
|
|
93
|
+
]
|
|
94
|
+
}
|
package/lib/core.js
ADDED
|
@@ -0,0 +1,522 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// srvprice CLI 公共层:参数解析 / 输出契约 / 退出码 / 配置与凭据 / 数据装载。
|
|
4
|
+
// 零外部依赖,Node >= 18.17。
|
|
5
|
+
|
|
6
|
+
const fs = require('fs');
|
|
7
|
+
const os = require('os');
|
|
8
|
+
const path = require('path');
|
|
9
|
+
|
|
10
|
+
const VERSION = require('../package.json').version;
|
|
11
|
+
|
|
12
|
+
// 退出码表(v1 定死,见调研第 05 节)
|
|
13
|
+
const EXIT = {
|
|
14
|
+
OK: 0,
|
|
15
|
+
GENERAL: 1, // 通用失败
|
|
16
|
+
USAGE: 2, // 参数 / 用法错误
|
|
17
|
+
STALE: 3, // 数据过期或不可用(可重试)
|
|
18
|
+
NOT_FOUND: 4, // 未找到
|
|
19
|
+
CRED: 5, // 凭据缺失或失效(指明哪家厂商)
|
|
20
|
+
VENDOR: 6, // 厂商侧拒绝 / 厂商错误
|
|
21
|
+
UNCONFIRMED: 7, // 写操作未确认而阻断
|
|
22
|
+
INTERRUPT: 130 // 中断
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
class CliError extends Error {
|
|
26
|
+
constructor(code, message, extra) {
|
|
27
|
+
super(message);
|
|
28
|
+
this.name = 'CliError';
|
|
29
|
+
this.exitCode = code;
|
|
30
|
+
Object.assign(this, extra || {});
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const EXIT_HELP = `退出码:0 成功 / 1 通用失败 / 2 参数错误 / 3 数据过期或不可用 / 4 未找到 /
|
|
35
|
+
5 凭据缺失或失效 / 6 厂商侧错误 / 7 写操作未确认而阻断 / 130 中断`;
|
|
36
|
+
|
|
37
|
+
// ---------------------------------------------------------------------------
|
|
38
|
+
// 参数解析
|
|
39
|
+
// ---------------------------------------------------------------------------
|
|
40
|
+
|
|
41
|
+
const BOOL_FLAGS = new Set([
|
|
42
|
+
'yes', 'dry-run', 'refresh', 'explain', 'no-open', 'new-user-only', 'include-expired',
|
|
43
|
+
'wait', 'no-color', 'help', 'version', 'introspect', 'verbose', 'quiet', 'json',
|
|
44
|
+
'force', 'all-providers', 'no-header', 'local-only', 'bundled', 'deploy'
|
|
45
|
+
]);
|
|
46
|
+
|
|
47
|
+
const SHORT_FLAGS = { '-o': 'output', '-h': 'help', '-v': 'version', '-y': 'yes', '-q': 'quiet' };
|
|
48
|
+
|
|
49
|
+
function camel(s) {
|
|
50
|
+
return s.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function parseArgs(argv) {
|
|
54
|
+
const words = [];
|
|
55
|
+
const opts = {};
|
|
56
|
+
let i = 0;
|
|
57
|
+
while (i < argv.length) {
|
|
58
|
+
let a = argv[i];
|
|
59
|
+
if (a === '--') { words.push(...argv.slice(i + 1)); break; }
|
|
60
|
+
if (SHORT_FLAGS[a]) { a = '--' + SHORT_FLAGS[a]; }
|
|
61
|
+
if (a.startsWith('--')) {
|
|
62
|
+
let name = a.slice(2);
|
|
63
|
+
let value;
|
|
64
|
+
const eq = name.indexOf('=');
|
|
65
|
+
if (eq >= 0) { value = name.slice(eq + 1); name = name.slice(0, eq); }
|
|
66
|
+
const key = camel(name);
|
|
67
|
+
if (BOOL_FLAGS.has(name)) {
|
|
68
|
+
opts[key] = value === undefined ? true : value !== 'false';
|
|
69
|
+
i += 1;
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
if (value === undefined) {
|
|
73
|
+
const next = argv[i + 1];
|
|
74
|
+
if (next !== undefined && !next.startsWith('-')) { value = next; i += 2; } else { value = true; i += 1; }
|
|
75
|
+
} else {
|
|
76
|
+
i += 1;
|
|
77
|
+
}
|
|
78
|
+
// 重复的 --id / --provider 收集为数组
|
|
79
|
+
if (key === 'id' || key === 'provider') {
|
|
80
|
+
if (opts[key] === undefined) opts[key] = [];
|
|
81
|
+
else if (!Array.isArray(opts[key])) opts[key] = [opts[key]];
|
|
82
|
+
opts[key].push(value);
|
|
83
|
+
} else {
|
|
84
|
+
opts[key] = value;
|
|
85
|
+
}
|
|
86
|
+
continue;
|
|
87
|
+
}
|
|
88
|
+
words.push(a);
|
|
89
|
+
i += 1;
|
|
90
|
+
}
|
|
91
|
+
return { words, opts };
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function asArray(v) {
|
|
95
|
+
if (v === undefined || v === null) return [];
|
|
96
|
+
return Array.isArray(v) ? v : [v];
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// ---------------------------------------------------------------------------
|
|
100
|
+
// 输出契约:--output auto|json|text
|
|
101
|
+
// ---------------------------------------------------------------------------
|
|
102
|
+
|
|
103
|
+
function outMode(opts, config) {
|
|
104
|
+
const want = opts.output && opts.output !== true ? String(opts.output).toLowerCase() : null;
|
|
105
|
+
if (want && want !== 'auto') {
|
|
106
|
+
if (want !== 'json' && want !== 'text') {
|
|
107
|
+
throw new CliError(EXIT.USAGE, `--output 只接受 json / text / auto(收到 ${want})`);
|
|
108
|
+
}
|
|
109
|
+
return want;
|
|
110
|
+
}
|
|
111
|
+
if (want === 'auto') return process.stdout.isTTY ? 'text' : 'json';
|
|
112
|
+
const configured = config.output || 'auto';
|
|
113
|
+
if (configured !== 'auto') return configured;
|
|
114
|
+
// 默认:管道/重定向走 json,终端走 text——agent 拿到的永远是结构化输出
|
|
115
|
+
return process.stdout.isTTY ? 'text' : 'json';
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function makeIO(opts, config) {
|
|
119
|
+
const mode = outMode(opts, config);
|
|
120
|
+
const json = mode === 'json';
|
|
121
|
+
const color = !opts.noColor && process.stdout.isTTY && !!process.env.TERM && !process.env.NO_COLOR;
|
|
122
|
+
|
|
123
|
+
return {
|
|
124
|
+
mode,
|
|
125
|
+
json,
|
|
126
|
+
color,
|
|
127
|
+
// stdout 只放业务结果
|
|
128
|
+
data(payload) {
|
|
129
|
+
if (json) process.stdout.write(JSON.stringify(payload, null, 2) + '\n');
|
|
130
|
+
else process.stdout.write(renderText(payload) + '\n');
|
|
131
|
+
},
|
|
132
|
+
raw(text) {
|
|
133
|
+
process.stdout.write(text + '\n');
|
|
134
|
+
},
|
|
135
|
+
// stderr:诊断 / 警告 / 进度,JSON 模式走 JSONL
|
|
136
|
+
warn(message, extra) {
|
|
137
|
+
if (json) {
|
|
138
|
+
process.stderr.write(JSON.stringify(Object.assign({ level: 'warn', message }, extra || {})) + '\n');
|
|
139
|
+
} else if (!opts.quiet) {
|
|
140
|
+
process.stderr.write(`warning: ${message}\n`);
|
|
141
|
+
}
|
|
142
|
+
},
|
|
143
|
+
info(message, extra) {
|
|
144
|
+
if (json) {
|
|
145
|
+
process.stderr.write(JSON.stringify(Object.assign({ level: 'info', message }, extra || {})) + '\n');
|
|
146
|
+
} else if (!opts.quiet) {
|
|
147
|
+
process.stderr.write(`${message}\n`);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// text 模式下把统一对象渲染成可读表格。列表型 payload 约定 { rows, columns }。
|
|
154
|
+
function renderText(payload) {
|
|
155
|
+
if (payload && Array.isArray(payload.rows) && Array.isArray(payload.columns)) {
|
|
156
|
+
return renderTable(payload.rows, payload.columns, payload.footer);
|
|
157
|
+
}
|
|
158
|
+
if (typeof payload === 'string') return payload;
|
|
159
|
+
if (payload && typeof payload === 'object' && typeof payload.text === 'string') return payload.text;
|
|
160
|
+
return JSON.stringify(payload, null, 2);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function displayWidth(s) {
|
|
164
|
+
let w = 0;
|
|
165
|
+
for (const ch of String(s)) {
|
|
166
|
+
const cp = ch.codePointAt(0);
|
|
167
|
+
// CJK 及全角符号按 2 列
|
|
168
|
+
w += (cp >= 0x1100 && (
|
|
169
|
+
cp <= 0x115f || cp === 0x2329 || cp === 0x232a ||
|
|
170
|
+
(cp >= 0x2e80 && cp <= 0xa4cf && cp !== 0x303f) ||
|
|
171
|
+
(cp >= 0xac00 && cp <= 0xd7a3) ||
|
|
172
|
+
(cp >= 0xf900 && cp <= 0xfaff) ||
|
|
173
|
+
(cp >= 0xfe30 && cp <= 0xfe6f) ||
|
|
174
|
+
(cp >= 0xff00 && cp <= 0xff60) ||
|
|
175
|
+
(cp >= 0xffe0 && cp <= 0xffe6) ||
|
|
176
|
+
(cp >= 0x1f300 && cp <= 0x1f64f) ||
|
|
177
|
+
(cp >= 0x20000 && cp <= 0x3fffd))) ? 2 : 1;
|
|
178
|
+
}
|
|
179
|
+
return w;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function pad(s, width) {
|
|
183
|
+
const d = width - displayWidth(s);
|
|
184
|
+
return d > 0 ? s + ' '.repeat(d) : s;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function renderTable(rows, columns, footer) {
|
|
188
|
+
if (!rows.length) return '(无结果)';
|
|
189
|
+
const widths = columns.map((c) => Math.max(
|
|
190
|
+
displayWidth(c.label),
|
|
191
|
+
...rows.map((r) => displayWidth(cellText(r, c)))
|
|
192
|
+
));
|
|
193
|
+
const lines = [];
|
|
194
|
+
lines.push(columns.map((c, i) => pad(c.label, widths[i])).join(' ').replace(/\s+$/, ''));
|
|
195
|
+
lines.push(columns.map((c, i) => '-'.repeat(widths[i])).join(' '));
|
|
196
|
+
for (const r of rows) {
|
|
197
|
+
lines.push(columns.map((c, i) => pad(cellText(r, c), widths[i])).join(' ').replace(/\s+$/, ''));
|
|
198
|
+
}
|
|
199
|
+
if (footer) lines.push('', footer);
|
|
200
|
+
return lines.join('\n');
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function cellText(row, col) {
|
|
204
|
+
const v = col.get ? col.get(row) : row[col.key];
|
|
205
|
+
if (v === undefined || v === null || v === '') return col.null || '—';
|
|
206
|
+
return String(v);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// ---------------------------------------------------------------------------
|
|
210
|
+
// 配置(选购偏好)与凭据(厂商密钥)——两个文件,语义严格分开
|
|
211
|
+
// ---------------------------------------------------------------------------
|
|
212
|
+
|
|
213
|
+
function homeDir() {
|
|
214
|
+
return process.env.SRVPRICE_HOME || path.join(os.homedir(), '.srvprice');
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
const CONFIG_PATH = () => path.join(homeDir(), 'config.json');
|
|
218
|
+
const CREDS_PATH = () => path.join(homeDir(), 'credentials.json');
|
|
219
|
+
const CACHE_DIR = () => path.join(homeDir(), 'cache');
|
|
220
|
+
|
|
221
|
+
const DEFAULT_PROFILE = {
|
|
222
|
+
currency: 'CNY',
|
|
223
|
+
default_region: null,
|
|
224
|
+
providers: [],
|
|
225
|
+
default_term: '1y',
|
|
226
|
+
new_user_only: false,
|
|
227
|
+
read_only: false, // true = 任何厂商写操作一律拒绝(配只读 key 时用,凭据 + 策略双保险)
|
|
228
|
+
output: 'auto',
|
|
229
|
+
language: 'zh',
|
|
230
|
+
stale_hours: 24
|
|
231
|
+
};
|
|
232
|
+
|
|
233
|
+
function ensureDir(dir, mode) {
|
|
234
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
235
|
+
if (mode) { try { fs.chmodSync(dir, mode); } catch (_) { /* Windows 上无实际效果 */ } }
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
function readJsonSafe(file) {
|
|
239
|
+
try {
|
|
240
|
+
return JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
241
|
+
} catch (e) {
|
|
242
|
+
if (e.code === 'ENOENT') return null;
|
|
243
|
+
throw new CliError(EXIT.GENERAL, `配置文件读取失败:${file}(${e.message})`);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
function writeJson0600(file, obj) {
|
|
248
|
+
ensureDir(path.dirname(file));
|
|
249
|
+
fs.writeFileSync(file, JSON.stringify(obj, null, 2) + '\n', { mode: 0o600 });
|
|
250
|
+
try { fs.chmodSync(file, 0o600); } catch (_) { /* Windows */ }
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
function loadConfig() {
|
|
254
|
+
const raw = readJsonSafe(CONFIG_PATH()) || {};
|
|
255
|
+
const profiles = Object.assign({ default: Object.assign({}, DEFAULT_PROFILE) }, raw.profiles || {});
|
|
256
|
+
if (!profiles.default) profiles.default = Object.assign({}, DEFAULT_PROFILE);
|
|
257
|
+
for (const k of Object.keys(profiles)) {
|
|
258
|
+
profiles[k] = Object.assign({}, DEFAULT_PROFILE, profiles[k]);
|
|
259
|
+
}
|
|
260
|
+
return {
|
|
261
|
+
version: raw.version || 1,
|
|
262
|
+
active_profile: raw.active_profile || 'default',
|
|
263
|
+
profiles
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
function saveConfig(cfg) {
|
|
268
|
+
writeJson0600(CONFIG_PATH(), cfg);
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
// 优先级:--profile > SRVPRICE_PROFILE > 激活配置 > default
|
|
272
|
+
function resolveProfile(config, opts) {
|
|
273
|
+
const name = (opts.profile && opts.profile !== true ? String(opts.profile) : null)
|
|
274
|
+
|| process.env.SRVPRICE_PROFILE
|
|
275
|
+
|| config.active_profile
|
|
276
|
+
|| 'default';
|
|
277
|
+
const source = (opts.profile && opts.profile !== true) ? 'flag'
|
|
278
|
+
: (process.env.SRVPRICE_PROFILE ? 'env' : (name === config.active_profile ? 'active' : 'default'));
|
|
279
|
+
const values = config.profiles[name];
|
|
280
|
+
if (!values) {
|
|
281
|
+
throw new CliError(EXIT.NOT_FOUND, `选购 profile 不存在:${name}(用 srvprice config list 查看)`);
|
|
282
|
+
}
|
|
283
|
+
return { name, source, values };
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
function loadCreds() {
|
|
287
|
+
const raw = readJsonSafe(CREDS_PATH()) || {};
|
|
288
|
+
return { version: raw.version || 1, vendors: raw.vendors || {} };
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
function saveCreds(creds) {
|
|
292
|
+
writeJson0600(CREDS_PATH(), creds);
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
function fileMode(file) {
|
|
296
|
+
try { return (fs.statSync(file).mode & 0o777).toString(8); } catch (_) { return null; }
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
function mask(secret) {
|
|
300
|
+
if (!secret) return null;
|
|
301
|
+
const s = String(secret);
|
|
302
|
+
if (s.length <= 8) return '*'.repeat(s.length);
|
|
303
|
+
return `${s.slice(0, 4)}…${s.slice(-4)}`;
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
// ---------------------------------------------------------------------------
|
|
307
|
+
// 数据装载(内置快照 + 本机缓存)
|
|
308
|
+
// ---------------------------------------------------------------------------
|
|
309
|
+
|
|
310
|
+
const DATA_DIR = path.join(__dirname, '..', 'data');
|
|
311
|
+
const DATA_FILES = { plans: 'plans.json', deals: 'deals.json', providers: 'providers.json', promos: 'promos.json', setup: 'setup.json' };
|
|
312
|
+
|
|
313
|
+
function dataOrigin(name) {
|
|
314
|
+
return process.env[`SRVPRICE_DATA_DIR`] || DATA_DIR;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
function cachePath(name) {
|
|
318
|
+
return path.join(CACHE_DIR(), DATA_FILES[name]);
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
// 推广码占位符:仓库里只存占位符,真实值运行时从环境变量注入(可由 vault-cli run 提供)
|
|
322
|
+
const URL_PLACEHOLDERS = {
|
|
323
|
+
YOUR_CPS_KEY: { env: 'SRVPRICE_TENCENT_CPS_KEY', label: '腾讯 CPS key' },
|
|
324
|
+
YOUR_REFERENCE_ID: { env: 'SRVPRICE_WEST_REFERENCE_ID', label: '西部数码代理/推荐 ID' }
|
|
325
|
+
};
|
|
326
|
+
const _warnedPlaceholders = new Set();
|
|
327
|
+
|
|
328
|
+
function resolvePlaceholders(value) {
|
|
329
|
+
if (typeof value === 'string') {
|
|
330
|
+
let s = value;
|
|
331
|
+
for (const [ph, meta] of Object.entries(URL_PLACEHOLDERS)) {
|
|
332
|
+
if (!s.includes(ph)) continue;
|
|
333
|
+
const injected = process.env[meta.env];
|
|
334
|
+
if (injected) {
|
|
335
|
+
s = s.split(ph).join(injected);
|
|
336
|
+
} else if (!_warnedPlaceholders.has(ph)) {
|
|
337
|
+
_warnedPlaceholders.add(ph);
|
|
338
|
+
process.stderr.write(JSON.stringify({
|
|
339
|
+
level: 'warn',
|
|
340
|
+
message: `${meta.label} 未注入(环境变量 ${meta.env}),链接中的 ${ph} 保持占位`
|
|
341
|
+
}) + '\n');
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
return s;
|
|
345
|
+
}
|
|
346
|
+
if (Array.isArray(value)) return value.map(resolvePlaceholders);
|
|
347
|
+
if (value && typeof value === 'object') {
|
|
348
|
+
const out = {};
|
|
349
|
+
for (const [k, v] of Object.entries(value)) out[k] = resolvePlaceholders(v);
|
|
350
|
+
return out;
|
|
351
|
+
}
|
|
352
|
+
return value;
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
function loadData(name) {
|
|
356
|
+
const file = DATA_FILES[name];
|
|
357
|
+
if (!file) throw new CliError(EXIT.GENERAL, `未知数据表:${name}`);
|
|
358
|
+
const cached = readJsonSafe(cachePath(name));
|
|
359
|
+
const origin = cached || readJsonSafe(path.join(dataOrigin(name), file));
|
|
360
|
+
if (!origin) throw new CliError(EXIT.STALE, `数据表缺失:${file}`);
|
|
361
|
+
return resolvePlaceholders(Object.assign({ _source: cached ? 'cache' : 'bundled' }, origin));
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
// 价格数据新鲜度检查:超过 stale_hours 在 stderr 警告,不阻断
|
|
365
|
+
function checkFreshness(io, records, staleHours, label) {
|
|
366
|
+
const dates = records.map((r) => r.verified_at).filter(Boolean).sort();
|
|
367
|
+
if (!dates.length) return { newest: null, age_hours: null, stale: true };
|
|
368
|
+
const newest = dates[dates.length - 1];
|
|
369
|
+
const ageMs = Date.now() - new Date(`${newest}T00:00:00Z`).getTime();
|
|
370
|
+
const ageHours = Math.round(ageMs / 3600000);
|
|
371
|
+
const stale = ageHours > staleHours;
|
|
372
|
+
if (stale) {
|
|
373
|
+
io.warn(
|
|
374
|
+
`${label}数据最新核验于 ${newest},已超过 ${staleHours} 小时;价格以厂商官网实时价为准,可用 --refresh 尝试更新`,
|
|
375
|
+
{ verified_at: newest, age_hours: ageHours, stale_hours: staleHours }
|
|
376
|
+
);
|
|
377
|
+
}
|
|
378
|
+
return { newest, age_hours: ageHours, stale };
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
const API_BASE = (process.env.SRVPRICE_API || 'https://www.srvprice.com').replace(/\/+$/, '');
|
|
382
|
+
|
|
383
|
+
// 数据同源:客户端不另起一套数据源,直接读站点的公开接口。
|
|
384
|
+
// plans → /api/server-snapshot(30 条周快照);deals/其他表暂无接口,保留内置快照。
|
|
385
|
+
async function refreshData(io, name) {
|
|
386
|
+
if (name !== 'plans') {
|
|
387
|
+
io.warn(`「${name}」暂无可刷新的公开接口,继续使用内置快照`);
|
|
388
|
+
return false;
|
|
389
|
+
}
|
|
390
|
+
const url = `${API_BASE}/api/server-snapshot`;
|
|
391
|
+
try {
|
|
392
|
+
const res = await fetch(url, { signal: AbortSignal.timeout(12000) });
|
|
393
|
+
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
|
394
|
+
const doc = await res.json();
|
|
395
|
+
if (!doc || !Array.isArray(doc.items) || !doc.items.length) {
|
|
396
|
+
throw new Error('快照返回结构不对');
|
|
397
|
+
}
|
|
398
|
+
const { snapshotToPlans } = require('./snapshot');
|
|
399
|
+
const out = snapshotToPlans(doc);
|
|
400
|
+
ensureDir(CACHE_DIR(), 0o700);
|
|
401
|
+
writeJson0600(path.join(CACHE_DIR(), DATA_FILES.plans), out);
|
|
402
|
+
io.info(`已从站点快照更新 ${out.plans.length} 条(数据日 ${out.snapshot_date || '未知'})`);
|
|
403
|
+
return true;
|
|
404
|
+
} catch (e) {
|
|
405
|
+
// 降级必须说清楚用的是哪天的快照,不能只报「继续使用内置快照」
|
|
406
|
+
let snap = null;
|
|
407
|
+
try { snap = loadData('plans').snapshot_date || null; } catch (_) { /* 数据也读不到时只报地址 */ }
|
|
408
|
+
io.warn(
|
|
409
|
+
`数据刷新失败(${url}):${e.message};继续使用内置/缓存快照` +
|
|
410
|
+
(snap ? `(数据日 ${snap},可能已过期,下单前请核对官网)` : ''),
|
|
411
|
+
{ stale_snapshot: snap, url }
|
|
412
|
+
);
|
|
413
|
+
return false;
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
// ---------------------------------------------------------------------------
|
|
418
|
+
// 工具
|
|
419
|
+
// ---------------------------------------------------------------------------
|
|
420
|
+
|
|
421
|
+
function nowIso() {
|
|
422
|
+
return new Date().toISOString();
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
function todayIso() {
|
|
426
|
+
return new Date().toISOString().slice(0, 10);
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
function paging(rows, opts) {
|
|
430
|
+
const page = Math.max(1, parseInt(opts.page || '1', 10) || 1);
|
|
431
|
+
const size = Math.max(1, parseInt(opts.pageSize || '20', 10) || 20);
|
|
432
|
+
const start = (page - 1) * size;
|
|
433
|
+
return {
|
|
434
|
+
page,
|
|
435
|
+
page_size: size,
|
|
436
|
+
total: rows.length,
|
|
437
|
+
has_more: start + size < rows.length,
|
|
438
|
+
items: rows.slice(start, start + size)
|
|
439
|
+
};
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
function confirmPrompt(question) {
|
|
443
|
+
// 只在 TTY 下调;非 TTY 一律视为未确认,由调用方转成退出码 7
|
|
444
|
+
if (!process.stdin.isTTY || !process.stdout.isTTY) return Promise.resolve(false);
|
|
445
|
+
const readline = require('readline');
|
|
446
|
+
const rl = readline.createInterface({ input: process.stdin, output: process.stderr });
|
|
447
|
+
return new Promise((resolve) => {
|
|
448
|
+
rl.question(`${question} [y/N] `, (answer) => {
|
|
449
|
+
rl.close();
|
|
450
|
+
resolve(/^y(es)?$/i.test(String(answer).trim()));
|
|
451
|
+
});
|
|
452
|
+
});
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
function readSecretHidden(promptText) {
|
|
456
|
+
if (!process.stdin.isTTY) return Promise.resolve(null);
|
|
457
|
+
return new Promise((resolve) => {
|
|
458
|
+
process.stderr.write(promptText);
|
|
459
|
+
const stdin = process.stdin;
|
|
460
|
+
const wasRaw = stdin.isRaw;
|
|
461
|
+
stdin.setRawMode(true);
|
|
462
|
+
stdin.resume();
|
|
463
|
+
stdin.setEncoding('utf8');
|
|
464
|
+
let buf = '';
|
|
465
|
+
const onData = (ch) => {
|
|
466
|
+
for (const c of ch) {
|
|
467
|
+
if (c === '\r' || c === '\n') {
|
|
468
|
+
stdin.setRawMode(wasRaw || false);
|
|
469
|
+
stdin.pause();
|
|
470
|
+
stdin.removeListener('data', onData);
|
|
471
|
+
process.stderr.write('\n');
|
|
472
|
+
resolve(buf);
|
|
473
|
+
return;
|
|
474
|
+
}
|
|
475
|
+
if (c === '\u0003') { // Ctrl-C
|
|
476
|
+
stdin.setRawMode(wasRaw || false);
|
|
477
|
+
process.stderr.write('\n');
|
|
478
|
+
process.exit(EXIT.INTERRUPT);
|
|
479
|
+
}
|
|
480
|
+
if (c === '\u007f' || c === '\b') { buf = buf.slice(0, -1); continue; }
|
|
481
|
+
buf += c;
|
|
482
|
+
}
|
|
483
|
+
};
|
|
484
|
+
stdin.on('data', onData);
|
|
485
|
+
});
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
module.exports = {
|
|
489
|
+
VERSION,
|
|
490
|
+
EXIT,
|
|
491
|
+
EXIT_HELP,
|
|
492
|
+
CliError,
|
|
493
|
+
parseArgs,
|
|
494
|
+
asArray,
|
|
495
|
+
makeIO,
|
|
496
|
+
outMode,
|
|
497
|
+
renderTable,
|
|
498
|
+
homeDir,
|
|
499
|
+
CONFIG_PATH,
|
|
500
|
+
CREDS_PATH,
|
|
501
|
+
CACHE_DIR,
|
|
502
|
+
DEFAULT_PROFILE,
|
|
503
|
+
loadConfig,
|
|
504
|
+
saveConfig,
|
|
505
|
+
resolveProfile,
|
|
506
|
+
loadCreds,
|
|
507
|
+
saveCreds,
|
|
508
|
+
fileMode,
|
|
509
|
+
mask,
|
|
510
|
+
loadData,
|
|
511
|
+
dataOrigin,
|
|
512
|
+
cachePath,
|
|
513
|
+
checkFreshness,
|
|
514
|
+
refreshData,
|
|
515
|
+
nowIso,
|
|
516
|
+
todayIso,
|
|
517
|
+
paging,
|
|
518
|
+
confirmPrompt,
|
|
519
|
+
readSecretHidden,
|
|
520
|
+
ensureDir,
|
|
521
|
+
writeJson0600
|
|
522
|
+
};
|