@dmall-inc/wd-cli 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/config.js ADDED
@@ -0,0 +1,269 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * 配置与凭据存储(借鉴 gh 的 config/hosts 双文件 + 12-factor 的 XDG 约定)。
5
+ *
6
+ * 目录:$WD_CLI_CONFIG_DIR > $XDG_CONFIG_HOME/wd-cli > ~/.config/wd-cli(Windows 用 %AppData%\wd-cli)
7
+ * config.json 普通配置:profile 的 baseUrl / authBaseUrl / clientId / 当前工作空间 …(0644 即可)
8
+ * hosts.json 凭据:登录令牌与直连令牌(0600)
9
+ *
10
+ * 分文件的理由与 gh 一致:普通配置经常要给人看、要进 dotfiles 仓库,凭据不该混在里面。
11
+ *
12
+ * 取值优先级(AWS CLI 的凭据链):命令行参数 > 环境变量 > 当前 profile。
13
+ */
14
+
15
+ const fs = require('node:fs');
16
+ const keyring = require('./keyring');
17
+ const os = require('node:os');
18
+ const path = require('node:path');
19
+
20
+ const CONFIG_FILE = 'config.json';
21
+ const HOSTS_FILE = 'hosts.json';
22
+ const DEFAULT_PROFILE = 'default';
23
+ const DEFAULT_TIMEOUT_MS = 30_000;
24
+
25
+ /** 可经 `wd-cli config set` 维护的键(白名单,避免写入拼错的键而静默不生效)。 */
26
+ const SETTABLE_KEYS = ['baseUrl', 'chatBaseUrl', 'authBaseUrl', 'clientId', 'timeoutMs'];
27
+
28
+ function configDir(env = process.env) {
29
+ if (env.WD_CLI_CONFIG_DIR) return env.WD_CLI_CONFIG_DIR;
30
+ if (process.platform === 'win32' && env.AppData) return path.join(env.AppData, 'wd-cli');
31
+ if (env.XDG_CONFIG_HOME) return path.join(env.XDG_CONFIG_HOME, 'wd-cli');
32
+ return path.join(os.homedir(), '.config', 'wd-cli');
33
+ }
34
+
35
+ function configPath(env) {
36
+ return path.join(configDir(env), CONFIG_FILE);
37
+ }
38
+
39
+ function hostsPath(env) {
40
+ return path.join(configDir(env), HOSTS_FILE);
41
+ }
42
+
43
+ function readJsonFile(file, fallback) {
44
+ try {
45
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
46
+ } catch {
47
+ return fallback;
48
+ }
49
+ }
50
+
51
+ function ensureDir(env) {
52
+ const dir = configDir(env);
53
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
54
+ try {
55
+ fs.chmodSync(dir, 0o700);
56
+ } catch {
57
+ // Windows 等不支持 POSIX 权限位的平台:忽略
58
+ }
59
+ return dir;
60
+ }
61
+
62
+ function writeJsonFile(file, data, mode, env) {
63
+ ensureDir(env);
64
+ fs.writeFileSync(file, `${JSON.stringify(data, null, 2)}\n`, { mode });
65
+ try {
66
+ fs.chmodSync(file, mode);
67
+ } catch {
68
+ // 同上
69
+ }
70
+ }
71
+
72
+ function loadConfig(env = process.env) {
73
+ const data = readJsonFile(configPath(env), {});
74
+ return {
75
+ currentProfile: typeof data.currentProfile === 'string' ? data.currentProfile : DEFAULT_PROFILE,
76
+ profiles: data.profiles && typeof data.profiles === 'object' ? data.profiles : {},
77
+ };
78
+ }
79
+
80
+ function saveConfig(config, env = process.env) {
81
+ writeJsonFile(configPath(env), config, 0o600, env);
82
+ }
83
+
84
+ /**
85
+ * 读取凭据。落在密钥链里的条目在 hosts.json 只留一个标记,这里补回真身;
86
+ * 密钥链取不到(换了机器、用户清过钥匙串)就当没登录,让用户重新登录,而不是抛错。
87
+ */
88
+ function loadHosts(env = process.env) {
89
+ const data = readJsonFile(hostsPath(env), {});
90
+ const hosts = data && typeof data === 'object' ? data : {};
91
+ for (const [profileName, entry] of Object.entries(hosts)) {
92
+ if (entry && entry.auth && entry.auth.__keyring) {
93
+ const secret = keyring.get(profileName);
94
+ const parsed = secret ? safeParse(secret) : null;
95
+ if (parsed) hosts[profileName] = { ...entry, auth: parsed };
96
+ else hosts[profileName] = { ...entry, auth: null };
97
+ }
98
+ }
99
+ return hosts;
100
+ }
101
+
102
+ function safeParse(text) {
103
+ try {
104
+ return JSON.parse(text);
105
+ } catch {
106
+ return null;
107
+ }
108
+ }
109
+
110
+ function saveHosts(hosts, env = process.env) {
111
+ // 凭据文件必须 0600:与 gh 的 hosts.yml 同等对待
112
+ writeJsonFile(hostsPath(env), hosts, 0o600, env);
113
+ }
114
+
115
+ /** 当前 profile 名:--profile > WD_CLI_PROFILE > config.currentProfile。 */
116
+ function resolveProfileName(flags = {}, env = process.env, config = null) {
117
+ if (flags.profile) return flags.profile;
118
+ if (env.WD_CLI_PROFILE) return env.WD_CLI_PROFILE;
119
+ return (config || loadConfig(env)).currentProfile || DEFAULT_PROFILE;
120
+ }
121
+
122
+ /**
123
+ * 汇总一次运行的有效配置。
124
+ *
125
+ * 凭据二选一:
126
+ * - token(直连模式):--token > WD_CLI_TOKEN > hosts[profile].token。与 GH_TOKEN 语义一致,存在即压过登录态。
127
+ * - auth(登录态):hosts[profile].auth(access/refresh/expiresAt)。
128
+ */
129
+ function resolveRuntime(flags = {}, env = process.env) {
130
+ const config = loadConfig(env);
131
+ const profileName = resolveProfileName(flags, env, config);
132
+ const profile = config.profiles[profileName] || {};
133
+ const hosts = loadHosts(env);
134
+ const hostEntry = hosts[profileName] || {};
135
+
136
+ const directToken = flags.token || env.WD_CLI_TOKEN || hostEntry.token || null;
137
+ const auth = directToken ? null : hostEntry.auth || null;
138
+
139
+ const workspaceRaw = flags.workspace || env.WD_CLI_WORKSPACE || profile.workspaceId || null;
140
+ const timeoutRaw = flags.timeoutMs || env.WD_CLI_TIMEOUT_MS || profile.timeoutMs || null;
141
+
142
+ return {
143
+ profileName,
144
+ profile,
145
+ config,
146
+ hosts,
147
+ baseUrl: trimSlash(flags.baseUrl || env.WD_CLI_BASE_URL || profile.baseUrl || ''),
148
+ chatBaseUrl: trimSlash(flags.chatBaseUrl || env.WD_CLI_CHAT_BASE_URL || profile.chatBaseUrl || ''),
149
+ authBaseUrl: trimSlash(profile.authBaseUrl || ''),
150
+ clientId: profile.clientId || '',
151
+ directToken,
152
+ auth,
153
+ workspaceId: workspaceRaw === null ? null : String(workspaceRaw),
154
+ workspaceName: profile.workspaceName || null,
155
+ timeoutMs: timeoutRaw ? Number(timeoutRaw) : DEFAULT_TIMEOUT_MS,
156
+ };
157
+ }
158
+
159
+ /** 主体类型:登录态 -> user;wat_ 前缀 -> workspace;其余令牌 -> agent;都没有 -> none。 */
160
+ function principalOf(runtime) {
161
+ if (runtime.directToken) {
162
+ return runtime.directToken.startsWith('wat_') ? 'workspace' : 'agent';
163
+ }
164
+ return runtime.auth ? 'user' : 'none';
165
+ }
166
+
167
+ /** 令牌脱敏:前缀 + 末 6 位,中间恒定省略。任何输出都只能用这个形态。 */
168
+ function maskToken(token) {
169
+ if (!token) return '';
170
+ const text = String(token);
171
+ const prefixMatch = text.match(/^(wat_|sat_|eyJ)/);
172
+ const prefix = prefixMatch ? prefixMatch[1] : text.slice(0, 3);
173
+ const tail = text.length > 6 ? text.slice(-6) : '';
174
+ return `${prefix}…${tail}`;
175
+ }
176
+
177
+ function updateProfile(profileName, patch, env = process.env) {
178
+ const config = loadConfig(env);
179
+ config.profiles[profileName] = { ...(config.profiles[profileName] || {}), ...patch };
180
+ for (const [key, value] of Object.entries(patch)) {
181
+ if (value === null || value === undefined) delete config.profiles[profileName][key];
182
+ }
183
+ config.currentProfile = config.currentProfile || DEFAULT_PROFILE;
184
+ saveConfig(config, env);
185
+ return config;
186
+ }
187
+
188
+ function setCurrentProfile(profileName, env = process.env) {
189
+ const config = loadConfig(env);
190
+ config.currentProfile = profileName;
191
+ if (!config.profiles[profileName]) config.profiles[profileName] = {};
192
+ saveConfig(config, env);
193
+ return config;
194
+ }
195
+
196
+ /**
197
+ * 序列化成纯 ASCII 的 JSON(非 ASCII 一律转 \uXXXX 转义)。
198
+ *
199
+ * macOS 的 `security` 一旦发现密码含非 ASCII 字节,读取时就改回十六进制转储而不是原文
200
+ * (中文名用户的登录态必踩)。这里从源头保证写进密钥链的永远是纯 ASCII,
201
+ * 读取侧 keyring.get 的 hex 兼容是第二道保险(存量条目仍要靠它)。
202
+ */
203
+ function stringifyAscii(value) {
204
+ return JSON.stringify(value).replace(/[\u0080-\uFFFF]/g, (ch) =>
205
+ `\\u${ch.charCodeAt(0).toString(16).padStart(4, '0')}`
206
+ );
207
+ }
208
+
209
+ /**
210
+ * 写入凭据。能用密钥链就把 auth 整体存进去,hosts.json 只留标记——
211
+ * 这样 dotfiles 备份、误发的日志里都不会带出令牌。
212
+ */
213
+ function updateHostEntry(profileName, patch, env = process.env) {
214
+ const hosts = loadHosts(env);
215
+ const next = { ...(hosts[profileName] || {}), ...patch };
216
+ for (const [key, value] of Object.entries(patch)) {
217
+ if (value === null || value === undefined) delete next[key];
218
+ }
219
+
220
+ const useKeyring = keyring.available(env);
221
+ if (Object.prototype.hasOwnProperty.call(patch, 'auth')) {
222
+ if (!patch.auth) {
223
+ // 删除同样要尊重 WD_CLI_INSECURE_STORAGE:该开关的语义是「完全不碰系统钥匙链」。
224
+ // 少了这个判断,测试 / CI 里的 logout 会去删开发机上真实的 wd-cli 凭据。
225
+ if (useKeyring) keyring.remove(profileName);
226
+ } else if (useKeyring && keyring.set(profileName, stringifyAscii(patch.auth))) {
227
+ next.auth = { __keyring: true };
228
+ }
229
+ }
230
+
231
+ hosts[profileName] = next;
232
+ // 落盘前把其它 profile 的密钥链条目还原成标记,避免读一次就把令牌写回明文文件
233
+ const onDisk = {};
234
+ for (const [name, entry] of Object.entries(hosts)) {
235
+ onDisk[name] =
236
+ name !== profileName && entry && entry.auth && !entry.auth.__keyring && keyring.available(env)
237
+ ? { ...entry, auth: { __keyring: true } }
238
+ : entry;
239
+ }
240
+ saveHosts(onDisk, env);
241
+ return hosts;
242
+ }
243
+
244
+ function trimSlash(value) {
245
+ return String(value || '').replace(/\/+$/, '');
246
+ }
247
+
248
+ module.exports = {
249
+ keyring,
250
+ DEFAULT_PROFILE,
251
+ DEFAULT_TIMEOUT_MS,
252
+ SETTABLE_KEYS,
253
+ configDir,
254
+ configPath,
255
+ hostsPath,
256
+ loadConfig,
257
+ saveConfig,
258
+ loadHosts,
259
+ saveHosts,
260
+ resolveProfileName,
261
+ resolveRuntime,
262
+ principalOf,
263
+ maskToken,
264
+ updateProfile,
265
+ setCurrentProfile,
266
+ updateHostEntry,
267
+ stringifyAscii,
268
+ trimSlash,
269
+ };
package/lib/data.js ADDED
@@ -0,0 +1,128 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * 请求体输入与交互确认。
5
+ *
6
+ * `--data` 三形态(对齐 gh 的 --input 与常见 CLI 习惯):
7
+ * --data '{"a":1}' 内联 JSON
8
+ * --data @file.json 从文件读
9
+ * --data - 从标准输入读
10
+ * 发送前一律校验是合法 JSON,非法即退出码 2——把错误挡在发请求之前,
11
+ * 而不是让服务端回一个 400 再来猜是哪儿写错了。
12
+ */
13
+
14
+ const fs = require('node:fs');
15
+ const readline = require('node:readline/promises');
16
+
17
+ const { CliError, EXIT, isTty } = require('./output');
18
+
19
+ function readStdin() {
20
+ try {
21
+ return fs.readFileSync(0, 'utf8');
22
+ } catch (error) {
23
+ throw new CliError(`读取标准输入失败:${error.message}`, EXIT.USAGE);
24
+ }
25
+ }
26
+
27
+ /** 取原始文本(不解析)。 */
28
+ function readDataText(raw, label = '--data') {
29
+ if (raw === undefined || raw === null) return null;
30
+ const text = String(raw);
31
+ if (text === '-') return readStdin();
32
+ if (text.startsWith('@')) {
33
+ const file = text.slice(1);
34
+ if (!fs.existsSync(file)) throw new CliError(`${label} 指定的文件不存在:${file}`, EXIT.USAGE);
35
+ return fs.readFileSync(file, 'utf8');
36
+ }
37
+ return text;
38
+ }
39
+
40
+ /** 取并解析为 JSON;非法 JSON 直接失败,不发请求。 */
41
+ function readJsonData(raw, label = '--data') {
42
+ const text = readDataText(raw, label);
43
+ if (text === null) return null;
44
+ try {
45
+ return JSON.parse(text);
46
+ } catch (error) {
47
+ throw new CliError(`${label} 不是合法 JSON:${error.message}`, EXIT.USAGE, {
48
+ hint: '可用 --data @file.json 或 --data - 从文件 / 标准输入传入',
49
+ });
50
+ }
51
+ }
52
+
53
+ /** 必填版:缺省即报错。 */
54
+ function requireJsonData(raw, label = '--data') {
55
+ const value = readJsonData(raw, label);
56
+ if (value === null) throw new CliError(`缺少 ${label}`, EXIT.USAGE);
57
+ return value;
58
+ }
59
+
60
+ /**
61
+ * 破坏性操作的二次确认(clig.dev)。非交互终端一律要求显式 --yes,
62
+ * 免得脚本里因为读不到输入而挂住或误删。
63
+ */
64
+ async function confirm(message, flags = {}) {
65
+ if (flags.yes) return true;
66
+ if (!isTty(process.stdin) || !isTty(process.stderr)) {
67
+ throw new CliError(`${message}(非交互环境)`, EXIT.USAGE, {
68
+ hint: '脚本 / CI 中请显式加 --yes 确认',
69
+ });
70
+ }
71
+ const rl = readline.createInterface({ input: process.stdin, output: process.stderr });
72
+ try {
73
+ const answer = (await rl.question(`${message} [y/N] `)).trim().toLowerCase();
74
+ return answer === 'y' || answer === 'yes';
75
+ } finally {
76
+ rl.close();
77
+ }
78
+ }
79
+
80
+ /** `-F key=value` 的类型推断(对齐 gh api -F):true/false/null/整数/小数按字面量,其余按字符串。 */
81
+ function inferTypedValue(text) {
82
+ const value = String(text);
83
+ if (value === 'true') return true;
84
+ if (value === 'false') return false;
85
+ if (value === 'null') return null;
86
+ if (/^-?\d+$/.test(value)) return Number(value);
87
+ if (/^-?\d+\.\d+$/.test(value)) return Number(value);
88
+ return value;
89
+ }
90
+
91
+ /** 解析可重复的 `key=value` 选项;typed 为真时对值做类型推断。 */
92
+ function parseKeyValues(items, { typed = false, label = '-f' } = {}) {
93
+ const out = {};
94
+ for (const item of items || []) {
95
+ const text = String(item);
96
+ const eq = text.indexOf('=');
97
+ if (eq <= 0) {
98
+ throw new CliError(`${label} 需要 key=value 形式,收到:${text}`, EXIT.USAGE);
99
+ }
100
+ const key = text.slice(0, eq);
101
+ const raw = text.slice(eq + 1);
102
+ out[key] = typed ? inferTypedValue(raw) : raw;
103
+ }
104
+ return out;
105
+ }
106
+
107
+ /** 解析 `-H "key: value"` 头。 */
108
+ function parseHeaders(items) {
109
+ const out = {};
110
+ for (const item of items || []) {
111
+ const text = String(item);
112
+ const idx = text.indexOf(':');
113
+ if (idx <= 0) throw new CliError(`-H 需要 "key: value" 形式,收到:${text}`, EXIT.USAGE);
114
+ out[text.slice(0, idx).trim()] = text.slice(idx + 1).trim();
115
+ }
116
+ return out;
117
+ }
118
+
119
+ module.exports = {
120
+ readStdin,
121
+ readDataText,
122
+ readJsonData,
123
+ requireJsonData,
124
+ confirm,
125
+ inferTypedValue,
126
+ parseKeyValues,
127
+ parseHeaders,
128
+ };