@wkgeo/cli 0.0.0-stage → 1.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/CHANGELOG.md +223 -0
- package/LICENSE +21 -0
- package/README.md +1042 -3
- package/SKILL.md +927 -0
- package/lib/ai/client.mjs +161 -0
- package/lib/ai/config.mjs +221 -0
- package/lib/ai/context.mjs +468 -0
- package/lib/ai/log.mjs +53 -0
- package/lib/api.mjs +339 -0
- package/lib/args.mjs +235 -0
- package/lib/cli.mjs +168 -0
- package/lib/cms.mjs +330 -0
- package/lib/commands/ai.mjs +392 -0
- package/lib/commands/apps.mjs +116 -0
- package/lib/commands/auth.mjs +1288 -0
- package/lib/commands/billing.mjs +666 -0
- package/lib/commands/cms.mjs +2533 -0
- package/lib/commands/config-auth.mjs +621 -0
- package/lib/commands/config.mjs +434 -0
- package/lib/commands/dnscred.mjs +428 -0
- package/lib/commands/domainops.mjs +546 -0
- package/lib/commands/domainorder.mjs +439 -0
- package/lib/commands/import.mjs +164 -0
- package/lib/commands/index.mjs +541 -0
- package/lib/commands/logs.mjs +141 -0
- package/lib/commands/orders.mjs +444 -0
- package/lib/commands/overview.mjs +394 -0
- package/lib/commands/plugins.mjs +678 -0
- package/lib/commands/site.mjs +435 -0
- package/lib/commands/siteops.mjs +1012 -0
- package/lib/commands/sites.mjs +905 -0
- package/lib/commands/skill.mjs +119 -0
- package/lib/commands/template.mjs +258 -0
- package/lib/config.mjs +351 -0
- package/lib/credentials.mjs +160 -0
- package/lib/device-store.mjs +132 -0
- package/lib/device.mjs +464 -0
- package/lib/errors.mjs +299 -0
- package/lib/format.mjs +339 -0
- package/lib/http.mjs +71 -0
- package/lib/index.mjs +44 -0
- package/lib/local-import.mjs +185 -0
- package/lib/login.mjs +1638 -0
- package/lib/oauth-urls.mjs +163 -0
- package/lib/page.mjs +393 -0
- package/lib/pkce.mjs +48 -0
- package/lib/proxy.mjs +454 -0
- package/lib/qr.mjs +31 -0
- package/lib/runtime.mjs +650 -0
- package/lib/site-state.mjs +137 -0
- package/lib/tar.mjs +207 -0
- package/lib/template-package.mjs +522 -0
- package/package.json +53 -4
- package/wkgeo.mjs +17 -0
package/lib/config.mjs
ADDED
|
@@ -0,0 +1,351 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CLI 配置:默认值 + 环境变量 + 命令行覆盖(优先级:命令行 > 环境变量 > 内置默认)
|
|
3
|
+
*
|
|
4
|
+
* 为什么单独一个文件:
|
|
5
|
+
* 1. CLI 里"这个值从哪来"最容易散落各处,散落之后就没法回答"线上到底打的是哪个环境"。
|
|
6
|
+
* 全部集中在这里,`wkgeo config` 才能一处打印出**实际生效**的值。
|
|
7
|
+
* 2. 测试要能注入环境(不污染 process.env),所以每个函数都带 env 参数。
|
|
8
|
+
*
|
|
9
|
+
* ⚠️ 踩过的坑:**绝不把任何密钥/令牌写进这里**。
|
|
10
|
+
* 我们是 OAuth 公共客户端(public client),只用 PKCE,没有 client_secret ——
|
|
11
|
+
* 源码里出现 client_secret 就等于把"机密客户端"的凭据公开了(而且会被 git 记住)。
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import os from 'node:os';
|
|
15
|
+
import path from 'node:path';
|
|
16
|
+
import { readFileSync } from 'node:fs';
|
|
17
|
+
|
|
18
|
+
import { UsageError } from './errors.mjs';
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* 线上 API 基址(业务接口 `/api/data`、OAuth 服务端 `/api/oauth/*` 都在这个域下)。
|
|
22
|
+
*
|
|
23
|
+
* ★ 2026-10-22(0.3.0):**已切阿里云 FC**,`api.wkgeo.com` 经 ESA 回源到 FC 函数。
|
|
24
|
+
* 旧腾讯 CloudBase 网关 `https://wkongai-….ap-shanghai.app.tcloudbase.com`
|
|
25
|
+
* **仅作历史兼容**(老版本 CLI 还指着它),新代码一律走这里;
|
|
26
|
+
* 若线上回滚,可用 `WKONGAI_BASE=https://wkongai-….tcloudbase.com` 临时覆盖,不用改代码。
|
|
27
|
+
*
|
|
28
|
+
* ⚠️ 切换前已按「门禁」逐路径比对过:`/api/data`、`/api/oauth/{metadata,userinfo,token,
|
|
29
|
+
* introspect,revoke,device_authorization}` 与未知路径的 404,新旧两边的状态码 / JSON 形状
|
|
30
|
+
* **完全一致**(详见 `.tmp-build/cli-aliyun-base-*.md`)。
|
|
31
|
+
*/
|
|
32
|
+
export const DEFAULT_BASE = 'https://api.wkgeo.com';
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* CMS 接口基址(**客户站后台那一套动作**:栏目 / 内容 / 素材 / 模板)。
|
|
36
|
+
*
|
|
37
|
+
* 为什么和 `DEFAULT_BASE` 分开:
|
|
38
|
+
* 平台面(站点 / 钱包 / 订单)在 CloudBase 网关 `/api/data`;
|
|
39
|
+
* CMS 面是**另一个云函数**,线上挂在自家域名下:`POST https://api.wkgeo.com/cms/<action>`。
|
|
40
|
+
* 两者域名、路径都不一样,硬合成一个 base 只会写出"改了一处另一处悄悄坏掉"的代码。
|
|
41
|
+
*
|
|
42
|
+
* ★ 2026-10-18 路径规范:域名已经含 `api`,路径里不再重复 —— 新写法是 `/cms/<action>`。
|
|
43
|
+
* 网关(ESA 重写规则)会把 `/cms/...` 换回 `/api/cms/...`,云函数不用改;
|
|
44
|
+
* 老写法 `https://api.wkgeo.com/api/cms` **继续兼容**,回退只改这一行。
|
|
45
|
+
*
|
|
46
|
+
* ⚠️ 这里只放**公开地址**。CMS 的鉴权是 Bearer 令牌(用户登录态),没有任何密钥进 CLI。
|
|
47
|
+
*
|
|
48
|
+
* ★ 2026-10-22(0.3.0):这个常量**本来就指向阿里云** `api.wkgeo.com`,本轮无需改动;
|
|
49
|
+
* 门禁实测旧的腾讯网关 `/cms/*` 是 404(CMS 从来没部署在腾讯那个域名下),
|
|
50
|
+
* 新基址 `/cms/*` 正常返回统一信封(未登录 `code:401`)。所以 CMS 面与平台面现在同域同源。
|
|
51
|
+
*/
|
|
52
|
+
export const DEFAULT_CMS_BASE = 'https://api.wkgeo.com/cms';
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* 前端页面基址(**2026-10-18 域名统一到路径**之后的 canonical 地址)。
|
|
56
|
+
*
|
|
57
|
+
* ★ 2026-10-02(三站拆分):三个业务页各有独立子域
|
|
58
|
+
* * 授权站 `https://oauth.wkgeo.com` —— 同意页 / 设备码页
|
|
59
|
+
* * 收银台 `https://pay.wkgeo.com` —— 支付页
|
|
60
|
+
* * 会员站 `https://user.wkgeo.com` —— 登录页 / 我的订单等
|
|
61
|
+
*
|
|
62
|
+
* ★★ 2026-10-18(域名统一到路径):授权站与会员站改挂主域前缀,**老子域继续可用**:
|
|
63
|
+
* * 授权站 `https://wkgeo.com/oauth/` (老:`https://oauth.wkgeo.com/`)
|
|
64
|
+
* * 会员站 `https://wkgeo.com/user/` (老:`https://user.wkgeo.com/`)
|
|
65
|
+
* * 收银台 `https://pay.wkgeo.com/` —— **支付独立,一行没动**
|
|
66
|
+
* 老板要求老地址并存,所以这三个常量是"**默认走新路径**",回滚只需一条环境变量:
|
|
67
|
+
* `WKONGAI_OAUTH_WEB_BASE=https://oauth.wkgeo.com`(见 README 的配置表)。
|
|
68
|
+
*
|
|
69
|
+
* ⚠️ 授权页地址不直接信任线上 metadata 的 `authorization_endpoint`:
|
|
70
|
+
* 1. 它由云函数 `oauth` 的 `ADMIN_WEB_BASE` 生成,**线上环境变量里还是老地址**,
|
|
71
|
+
* 服务端切完并重新部署之前一直返回 `https://oauth.wkgeo.com/...`;
|
|
72
|
+
* 2. 线上还曾经把它配成 http://localhost:8000(云函数默认值没配环境变量),
|
|
73
|
+
* 那种情况下打开的是**用户本机端口**,是最坏的一种失败。
|
|
74
|
+
* ⇒ 所以统一走 `oauth-urls.mjs` 的 `canonicalOauthUrl()`:
|
|
75
|
+
* **这里(配置基址)是 canonical,服务端只提供路径**。
|
|
76
|
+
*/
|
|
77
|
+
export const DEFAULT_OAUTH_WEB_BASE = 'https://wkgeo.com/oauth';
|
|
78
|
+
export const DEFAULT_PAY_WEB_BASE = 'https://pay.wkgeo.com';
|
|
79
|
+
export const DEFAULT_USER_WEB_BASE = 'https://wkgeo.com/user';
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* ⚠️ 兼容保留:老站(管理端)基址。
|
|
83
|
+
* 三站拆分后**没有任何代码再用它打开页面**,但 `WKONGAI_WEB_BASE` 这个总覆盖开关
|
|
84
|
+
* 与 `web_base` 这个输出字段必须留着 —— 删了会破坏既有自动化脚本。
|
|
85
|
+
*/
|
|
86
|
+
export const DEFAULT_WEB_BASE = 'https://www.wkongai.cn/admin';
|
|
87
|
+
|
|
88
|
+
/** 官方公共客户端的默认 client_id(--client-id / WKONGAI_CLIENT_ID 可覆盖) */
|
|
89
|
+
export const DEFAULT_CLIENT_ID = 'wkgeo-cli';
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* 默认申请的 scope。
|
|
93
|
+
* 这四项刚好覆盖"建站 + 下单 + 钱包支付 + 查余额":
|
|
94
|
+
* site:read 看自己的站 site:write 建站/删站
|
|
95
|
+
* billing:self 读钱包/下单/支付
|
|
96
|
+
* 刻意**不申请** billing:manage / user:write 这类"动钱/改权限"的能力 —— 能力越小越好,
|
|
97
|
+
* 而且那些动作在服务端本来就要二次验证(OAuth 令牌没有密码入口,永远过不了),申请了也是废的。
|
|
98
|
+
*/
|
|
99
|
+
export const DEFAULT_SCOPE =
|
|
100
|
+
/**
|
|
101
|
+
* 2026-10-18(老板批准方案 A):默认 scope 扩到"能真正管一个站"——
|
|
102
|
+
* * `site:read/write` —— 栏目、内容、站点信息、参数、字段、语言、插件、会员
|
|
103
|
+
* * `attachment:read/write` —— 素材上传/列表(**删除**另要 `attachment:delete`,破坏性动作不默认给)
|
|
104
|
+
* * `template:read/write` —— 模板文件读写(模板能插任意 HTML,服务端故意与 `site:write` 分开)
|
|
105
|
+
* 这几个 scope 平台侧的 `oauth_client.allowed_scopes` 里都已允许(迁移 `20261018110000`)。
|
|
106
|
+
*/
|
|
107
|
+
'site:read site:write attachment:read attachment:write template:read template:write billing:self';
|
|
108
|
+
|
|
109
|
+
/** 回调只监听回环;端口与服务端登记的 redirect_uri 一致(服务端对回环地址忽略端口比对) */
|
|
110
|
+
export const DEFAULT_CALLBACK_HOST = '127.0.0.1';
|
|
111
|
+
export const DEFAULT_CALLBACK_PORT = 53682;
|
|
112
|
+
export const DEFAULT_CALLBACK_PATH = '/callback';
|
|
113
|
+
|
|
114
|
+
/** 授权码本身 5 分钟过期,所以等待回调默认给 5 分钟就够(= 300 秒;`--timeout` 按**秒**传,见 parseDurationMs) */
|
|
115
|
+
export const DEFAULT_LOGIN_TIMEOUT_MS = 300000;
|
|
116
|
+
export const DEFAULT_HTTP_TIMEOUT_MS = 30000;
|
|
117
|
+
|
|
118
|
+
/** 本地凭据文件:`~/.wkongai/credentials.json`(0600) */
|
|
119
|
+
export function defaultCredentialsFile(env = process.env) {
|
|
120
|
+
if (env.WKONGAI_CREDENTIALS) return path.resolve(env.WKONGAI_CREDENTIALS);
|
|
121
|
+
const home = env.WKONGAI_HOME || os.homedir();
|
|
122
|
+
return path.join(home, '.wkongai', 'credentials.json');
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* 本地站点状态文件:**凭据文件同目录**的 `config.json`(默认 `~/.wkongai/config.json`)。
|
|
127
|
+
*
|
|
128
|
+
* 为什么不塞进凭据文件(见 `site-state.mjs` 的说明):那是"身份",这是"操作上下文",
|
|
129
|
+
* `logout` 不该把它一起删掉。跟着凭据目录走,是为了让 `--credentials` / `WKONGAI_CREDENTIALS`
|
|
130
|
+
* 的隔离语义保持一致(换一套身份 = 换一套站点选择),单测与多人共机都不会串。
|
|
131
|
+
*/
|
|
132
|
+
export function defaultSiteStateFile(env = process.env, credentialsFile = '') {
|
|
133
|
+
const creds = credentialsFile || defaultCredentialsFile(env);
|
|
134
|
+
return path.join(path.dirname(creds), 'config.json');
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** 去掉结尾斜杠:所有拼接都假设 base 不带尾斜杠,混着写会拼出 `//api/data` */
|
|
138
|
+
export function stripTrailingSlash(u) {
|
|
139
|
+
return String(u || '').replace(/\/+$/, '');
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* 给「页面 URL」补上尾斜杠 —— **本项目所有会被托管侧 302 的地址都必须经过它**(唯一构造入口)。
|
|
144
|
+
*
|
|
145
|
+
* ## 为什么必须有这个函数(真机实测过的坑)
|
|
146
|
+
* 前端是静态导出(`exportStatic`),产物是「每个路由一个目录」(`dist-oauth/authorize/index.html`)。
|
|
147
|
+
* 托管侧(OSS 静态托管 / 阿里云 ESA)对**不带尾斜杠**的目录路径会返回 **302**,
|
|
148
|
+
* 而这个 302 **不携带原始 query**:
|
|
149
|
+
* ```
|
|
150
|
+
* GET /admin/oauth/authorize?client_id=…&state=… → 302 /admin/oauth/authorize/ ← query 全丢 ❌
|
|
151
|
+
* GET /admin/oauth/authorize/?client_id=…&state=… → 200,参数完好 ✔
|
|
152
|
+
* ```
|
|
153
|
+
* (★ 2026-10-02:上面测的是老站路径;授权站去 `/oauth` 前缀后是 `/authorize`,
|
|
154
|
+
* 收银台去 `/pay` 前缀后是站根 `/`(站根是真实 `index.html`,不触发这个 302)。坑的形态没变。)
|
|
155
|
+
* 后果是授权页显示「授权请求不完整」,而且**前端救不回来**:302 发生在任何 JS 执行之前,
|
|
156
|
+
* 带参数的地址根本没到过浏览器。
|
|
157
|
+
*
|
|
158
|
+
* ## 行为(有单测钉住)
|
|
159
|
+
* * 尾斜杠必须加在 **`?` 之前**(`/oauth/device?user_code=x` → `/oauth/device/?user_code=x`,
|
|
160
|
+
* 授权站去前缀后是 `/device?user_code=x` → `/device/?user_code=x`),
|
|
161
|
+
* 加到 `?` 后面就变成另一个含义了;
|
|
162
|
+
* * 已经带尾斜杠**不重复拼**(不会出现 `//`);
|
|
163
|
+
* * 路径里的连续斜杠折叠(`/oauth//device` → `/oauth/device/`),
|
|
164
|
+
* 但**保留协议头的 `//`** —— 踩过的坑:一开始对整个字符串做 `replace(/\/{2,}/g,'/')`,
|
|
165
|
+
* 结果 `https://www.wkongai.cn/admin/oauth/device` 被折成 `https:/www.wkongai.cn/...`
|
|
166
|
+
* (看着"还能用"是因为 URL 解析器帮忙兜了,但这种字符串一旦拼进别的地方就会出问题);
|
|
167
|
+
* * query / hash 原样保留,一个字符都不动(那里可能有已经编码好的 `redirect=`)。
|
|
168
|
+
*/
|
|
169
|
+
export function withTrailingSlash(pathAndQuery) {
|
|
170
|
+
const raw = String(pathAndQuery == null ? '' : pathAndQuery);
|
|
171
|
+
// 先按 `#` 切开:hash 里可能有 `?`,不能被当成 query 起点
|
|
172
|
+
const hashAt = raw.indexOf('#');
|
|
173
|
+
const hash = hashAt >= 0 ? raw.slice(hashAt) : '';
|
|
174
|
+
const beforeHash = hashAt >= 0 ? raw.slice(0, hashAt) : raw;
|
|
175
|
+
|
|
176
|
+
const queryAt = beforeHash.indexOf('?');
|
|
177
|
+
const query = queryAt >= 0 ? beforeHash.slice(queryAt) : '';
|
|
178
|
+
const rawPath = queryAt >= 0 ? beforeHash.slice(0, queryAt) : beforeHash;
|
|
179
|
+
|
|
180
|
+
// 协议头(`https://`)里的 `//` 是语法的一部分,**不能**被当成"重复斜杠"折叠掉
|
|
181
|
+
const schemeMatch = /^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.exec(rawPath);
|
|
182
|
+
const scheme = schemeMatch ? schemeMatch[0] : '';
|
|
183
|
+
const collapsed = scheme + (scheme ? rawPath.slice(scheme.length) : rawPath).replace(/\/{2,}/g, '/');
|
|
184
|
+
const path = !collapsed || collapsed.endsWith('/') ? collapsed || '/' : `${collapsed}/`;
|
|
185
|
+
return `${path}${query}${hash}`;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** 时长后缀 → 毫秒倍率(只支持秒与毫秒两种,够用且不产生歧义) */
|
|
189
|
+
const DURATION_UNITS = { s: 1000, ms: 1 };
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* 解析「时长」参数。
|
|
193
|
+
*
|
|
194
|
+
* ## 为什么要有它(踩过的坑)
|
|
195
|
+
* `--timeout` 原来直接当**毫秒**用,于是 `--timeout 600` 变成 **600 毫秒** ——
|
|
196
|
+
* 用户按直觉写"600 秒",结果是 0.8 秒就超时失败,`--help` 里也没写单位,
|
|
197
|
+
* 属于"看起来成功其实用错"的那类坑。
|
|
198
|
+
*
|
|
199
|
+
* ## 约定
|
|
200
|
+
* * **默认单位是秒**:`600` = 600 秒(人类写超时几乎都按秒/分钟想);
|
|
201
|
+
* * 也接受显式后缀:`600s` / `500ms`(大小写都行);
|
|
202
|
+
* * 非法值**明确报错**(UsageError,退出码 2),而不是静默退回默认值 ——
|
|
203
|
+
* 静默兜底会让用户以为生效了,是最坑的一种"成功"。
|
|
204
|
+
*
|
|
205
|
+
* @param {string|number} raw 原始值(命令行字符串或环境变量)
|
|
206
|
+
* @param {object} [opts]
|
|
207
|
+
* @param {'s'|'ms'} [opts.defaultUnit] 不带后缀时的单位(默认 `'s'`)
|
|
208
|
+
* @param {string} [opts.flag] 出错信息里显示的参数名(如 `--timeout`)
|
|
209
|
+
* @returns {number} 毫秒
|
|
210
|
+
*/
|
|
211
|
+
export function parseDurationMs(raw, { defaultUnit = 's', flag = '--timeout' } = {}) {
|
|
212
|
+
const text = String(raw == null ? '' : raw).trim();
|
|
213
|
+
const bad = (why) =>
|
|
214
|
+
new UsageError(
|
|
215
|
+
`${why}\n用法:${flag} <时长>,默认单位是**秒**(例如 ${flag} 600 = 600 秒);` +
|
|
216
|
+
`也支持显式后缀 ${flag} 600s / ${flag} 500ms`,
|
|
217
|
+
);
|
|
218
|
+
|
|
219
|
+
const m = /^(\d+(?:\.\d+)?)\s*(ms|s)?$/i.exec(text);
|
|
220
|
+
if (!m) throw bad(`参数 ${flag} 需要时长,收到:${JSON.stringify(String(raw))}`);
|
|
221
|
+
const unit = (m[2] || defaultUnit).toLowerCase();
|
|
222
|
+
const ms = Number(m[1]) * DURATION_UNITS[unit];
|
|
223
|
+
if (!Number.isFinite(ms) || ms <= 0) throw bad(`参数 ${flag} 必须大于 0,收到:${JSON.stringify(String(raw))}`);
|
|
224
|
+
return Math.round(ms);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** scope 字符串 → 数组(空格或逗号分隔都吃;服务端两种都收) */
|
|
228
|
+
export function splitScope(scope) {
|
|
229
|
+
return String(scope || '')
|
|
230
|
+
.split(/[\s,]+/)
|
|
231
|
+
.map((s) => s.trim())
|
|
232
|
+
.filter(Boolean);
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
function toInt(v, fallback) {
|
|
236
|
+
const n = Number.parseInt(v, 10);
|
|
237
|
+
return Number.isFinite(n) ? n : fallback;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* 把「命令行 flags + 环境变量」合成一份最终配置。
|
|
242
|
+
* @param {object} flags 已解析的命令行标志(键为 camelCase)
|
|
243
|
+
* @param {object} env 环境变量(默认 process.env)
|
|
244
|
+
*/
|
|
245
|
+
export function resolveConfig(flags = {}, env = process.env) {
|
|
246
|
+
const pick = (flagVal, envKey, dflt) => {
|
|
247
|
+
if (flagVal !== undefined && flagVal !== null && flagVal !== '') return flagVal;
|
|
248
|
+
if (env[envKey] !== undefined && env[envKey] !== '') return env[envKey];
|
|
249
|
+
return dflt;
|
|
250
|
+
};
|
|
251
|
+
|
|
252
|
+
const scopeRaw = pick(flags.scope, 'WKONGAI_SCOPE', DEFAULT_SCOPE);
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* ★ 2026-10-02(三站拆分):三个业务子域的基址。
|
|
256
|
+
*
|
|
257
|
+
* 覆盖优先级(高 → 低):
|
|
258
|
+
* 1. `WKONGAI_WEB_BASE` / `--web-base` —— **总覆盖**:设了它就三站都用它
|
|
259
|
+
* (联调 / 回滚老站时一句环境变量搞定,不用改代码);
|
|
260
|
+
* 2. `WKONGAI_OAUTH_WEB_BASE` / `WKONGAI_PAY_WEB_BASE` / `WKONGAI_USER_WEB_BASE`
|
|
261
|
+
* —— 按站单独覆盖;
|
|
262
|
+
* 3. 各自的内置默认值(授权站 `/oauth`、收银台子域、会员站 `/user`)。
|
|
263
|
+
*/
|
|
264
|
+
const topOverride = stripTrailingSlash(pick(flags.webBase, 'WKONGAI_WEB_BASE', ''));
|
|
265
|
+
const getWebBase = (envKey, dflt) =>
|
|
266
|
+
topOverride || stripTrailingSlash(pick(undefined, envKey, dflt));
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* `--timeout` 的单位是**秒**(见 parseDurationMs 的说明),而环境变量
|
|
270
|
+
* `WKONGAI_LOGIN_TIMEOUT_MS` 名字里就写着 MS,**必须是毫秒** —— 两者不能共用一个默认单位,
|
|
271
|
+
* 否则 `WKONGAI_LOGIN_TIMEOUT_MS=300000` 会被当成 300000 秒(83 小时)。
|
|
272
|
+
*/
|
|
273
|
+
const loginTimeoutMs =
|
|
274
|
+
flags.timeout !== undefined && flags.timeout !== ''
|
|
275
|
+
? parseDurationMs(flags.timeout, { defaultUnit: 's', flag: '--timeout' })
|
|
276
|
+
: env.WKONGAI_LOGIN_TIMEOUT_MS !== undefined && env.WKONGAI_LOGIN_TIMEOUT_MS !== ''
|
|
277
|
+
? parseDurationMs(env.WKONGAI_LOGIN_TIMEOUT_MS, { defaultUnit: 'ms', flag: 'WKONGAI_LOGIN_TIMEOUT_MS' })
|
|
278
|
+
: DEFAULT_LOGIN_TIMEOUT_MS;
|
|
279
|
+
|
|
280
|
+
/**
|
|
281
|
+
* 凭据文件路径先算出来:站点状态文件放在**它同目录**(见 defaultSiteStateFile 的说明),
|
|
282
|
+
* 这样 `--credentials` 换一套身份时,选中的站点也跟着换,不会串站。
|
|
283
|
+
*/
|
|
284
|
+
const credentialsFile = flags.credentials
|
|
285
|
+
? path.resolve(String(flags.credentials))
|
|
286
|
+
: defaultCredentialsFile(env);
|
|
287
|
+
|
|
288
|
+
return {
|
|
289
|
+
base: stripTrailingSlash(pick(flags.base, 'WKONGAI_BASE', DEFAULT_BASE)),
|
|
290
|
+
/** ⚠️ 兼容字段:老站(管理端)基址。三站拆分后没有代码用它打开页面,但保留以免破坏自动化 */
|
|
291
|
+
webBase: topOverride || stripTrailingSlash(pick(undefined, 'WKONGAI_WEB_BASE', DEFAULT_WEB_BASE)),
|
|
292
|
+
/** 授权站基址(同意页 / 设备码页) */
|
|
293
|
+
oauthWebBase: getWebBase('WKONGAI_OAUTH_WEB_BASE', DEFAULT_OAUTH_WEB_BASE),
|
|
294
|
+
/** 收银台基址(支付页) */
|
|
295
|
+
payWebBase: getWebBase('WKONGAI_PAY_WEB_BASE', DEFAULT_PAY_WEB_BASE),
|
|
296
|
+
/** 会员站基址(登录页 / 我的订单等) */
|
|
297
|
+
userWebBase: getWebBase('WKONGAI_USER_WEB_BASE', DEFAULT_USER_WEB_BASE),
|
|
298
|
+
/** CMS 接口基址(栏目 / 内容 / 素材 / 模板;**和平台面是两个地址**) */
|
|
299
|
+
cmsBase: stripTrailingSlash(pick(flags.cmsBase, 'WKONGAI_CMS_BASE', DEFAULT_CMS_BASE)),
|
|
300
|
+
clientId: String(pick(flags.clientId, 'WKONGAI_CLIENT_ID', DEFAULT_CLIENT_ID)),
|
|
301
|
+
scope: splitScope(scopeRaw).join(' '),
|
|
302
|
+
credentialsFile,
|
|
303
|
+
/** 本地"当前站点"记录(`wkgeo site use` 写它;**不是**凭据) */
|
|
304
|
+
siteStateFile: defaultSiteStateFile(env, credentialsFile),
|
|
305
|
+
callbackHost: String(pick(flags.callbackHost, 'WKONGAI_CALLBACK_HOST', DEFAULT_CALLBACK_HOST)),
|
|
306
|
+
callbackPort: toInt(pick(flags.callbackPort, 'WKONGAI_CALLBACK_PORT', DEFAULT_CALLBACK_PORT), DEFAULT_CALLBACK_PORT),
|
|
307
|
+
callbackPath: String(pick(flags.callbackPath, 'WKONGAI_CALLBACK_PATH', DEFAULT_CALLBACK_PATH)),
|
|
308
|
+
loginTimeoutMs,
|
|
309
|
+
httpTimeoutMs: toInt(pick(flags.httpTimeout, 'WKONGAI_HTTP_TIMEOUT_MS', DEFAULT_HTTP_TIMEOUT_MS), DEFAULT_HTTP_TIMEOUT_MS),
|
|
310
|
+
json: flags.json === true,
|
|
311
|
+
color: flags.color !== false,
|
|
312
|
+
verbose: flags.verbose === true,
|
|
313
|
+
/**
|
|
314
|
+
* CLI 版本(**必须**与 `package.json` 一致)。
|
|
315
|
+
*
|
|
316
|
+
* 0.4.0 及以前这里写死 `'0.1.0'`,`wkgeo config` 报的版本和 `--version` 不一致 ——
|
|
317
|
+
* 现在统一从包元数据读,只有读不到(被裁剪的发行物)才退回 `0.0.0`。
|
|
318
|
+
*/
|
|
319
|
+
version: readPackageVersion(),
|
|
320
|
+
};
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/** 读 `cli/package.json` 的 version(`import.meta.url` 相对定位,安装到全局也能读对) */
|
|
324
|
+
function readPackageVersion() {
|
|
325
|
+
try {
|
|
326
|
+
const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
|
|
327
|
+
return String(pkg.version || '0.0.0');
|
|
328
|
+
} catch {
|
|
329
|
+
return '0.0.0';
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
/** 供 `wkgeo config` 展示:把"哪个来源生效"讲清楚(不含任何令牌) */
|
|
334
|
+
export function describeConfigSources(flags = {}, env = process.env) {
|
|
335
|
+
const src = (flagVal, envKey) => {
|
|
336
|
+
if (flagVal !== undefined && flagVal !== null && flagVal !== '') return '命令行';
|
|
337
|
+
if (env[envKey] !== undefined && env[envKey] !== '') return `环境变量 ${envKey}`;
|
|
338
|
+
return '内置默认';
|
|
339
|
+
};
|
|
340
|
+
return {
|
|
341
|
+
base: src(flags.base, 'WKONGAI_BASE'),
|
|
342
|
+
cms_base: src(flags.cmsBase, 'WKONGAI_CMS_BASE'),
|
|
343
|
+
client_id: src(flags.clientId, 'WKONGAI_CLIENT_ID'),
|
|
344
|
+
scope: src(flags.scope, 'WKONGAI_SCOPE'),
|
|
345
|
+
credentials_file: flags.credentials
|
|
346
|
+
? '命令行'
|
|
347
|
+
: env.WKONGAI_CREDENTIALS
|
|
348
|
+
? '环境变量 WKONGAI_CREDENTIALS'
|
|
349
|
+
: '内置默认 ~/.wkongai/credentials.json',
|
|
350
|
+
};
|
|
351
|
+
}
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 本地凭据文件:`~/.wkongai/credentials.json`(权限 0600,目录 0700)。
|
|
3
|
+
*
|
|
4
|
+
* 为什么是这个位置 / 这个形态:
|
|
5
|
+
* * 放用户主目录(不是当前目录):CLI 在任何目录下跑都能用;也不会被 git 误提交。
|
|
6
|
+
* * 0600:文件里是**30 天的 bearer 令牌**,等同密码。同机器其它用户不该读到。
|
|
7
|
+
* * 原子写(先写临时文件再 rename):避免"写一半被 Ctrl+C"留下损坏的 JSON,
|
|
8
|
+
* 下次启动读不动、只能重新登录(踩过一次)。
|
|
9
|
+
*
|
|
10
|
+
* ⚠️ Windows 说明:NTFS 的 `chmod` 基本是空操作(Node 会接受但只映射只读位)。
|
|
11
|
+
* 所以我们**仍然调用 chmod 0600**(POSIX 上有效),并在读到"权限过宽"时给出警告。
|
|
12
|
+
* Windows 上真正的保护来自用户目录 ACL(默认只有本人可读),这一点在 README 里写明了。
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import fs from 'node:fs';
|
|
16
|
+
import path from 'node:path';
|
|
17
|
+
import { CliError, EXIT } from './errors.mjs';
|
|
18
|
+
|
|
19
|
+
export const CREDENTIALS_VERSION = 1;
|
|
20
|
+
|
|
21
|
+
/** 读凭据:不存在返回 null;JSON 损坏 → 抛可照做的错误(不静默当未登录,否则用户不知道为什么) */
|
|
22
|
+
export function readCredentials(file) {
|
|
23
|
+
if (!file) return null;
|
|
24
|
+
let text;
|
|
25
|
+
try {
|
|
26
|
+
text = fs.readFileSync(file, 'utf8');
|
|
27
|
+
} catch (e) {
|
|
28
|
+
if (e && e.code === 'ENOENT') return null;
|
|
29
|
+
throw new CliError(`读取凭据文件失败:${e.message}`, {
|
|
30
|
+
kind: 'credentials',
|
|
31
|
+
hint: `文件位置:${file}`,
|
|
32
|
+
cause: e,
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
let parsed;
|
|
36
|
+
try {
|
|
37
|
+
parsed = JSON.parse(text);
|
|
38
|
+
} catch (e) {
|
|
39
|
+
throw new CliError(`凭据文件不是合法 JSON:${file}`, {
|
|
40
|
+
kind: 'credentials',
|
|
41
|
+
hint: '可以删掉它再运行 `wkgeo login`(或直接运行 `wkgeo login` 覆盖写入)',
|
|
42
|
+
cause: e,
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
if (!parsed || typeof parsed !== 'object' || !parsed.access_token) {
|
|
46
|
+
throw new CliError(`凭据文件缺少 access_token:${file}`, {
|
|
47
|
+
kind: 'credentials',
|
|
48
|
+
hint: '运行 `wkgeo logout` 清掉再 `wkgeo login`',
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
return parsed;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** 凭据文件权限是否过宽(POSIX 有意义;Windows 上恒判"无法判断") */
|
|
55
|
+
export function checkFileMode(file) {
|
|
56
|
+
if (process.platform === 'win32') return { supported: false };
|
|
57
|
+
try {
|
|
58
|
+
const st = fs.statSync(file);
|
|
59
|
+
const mode = st.mode & 0o777;
|
|
60
|
+
return { supported: true, mode, tooOpen: (mode & 0o077) !== 0, modeText: mode.toString(8).padStart(3, '0') };
|
|
61
|
+
} catch {
|
|
62
|
+
return { supported: false };
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* 原子写凭据(0600)。返回写入后的权限信息,便于让 login 如实汇报。
|
|
68
|
+
*/
|
|
69
|
+
export function writeCredentials(file, data, { now = Date.now() } = {}) {
|
|
70
|
+
const dir = path.dirname(file);
|
|
71
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
72
|
+
// 目录已存在时 mkdir 不改权限,显式补一次(0600 文件放 0755 目录里意义会打折)
|
|
73
|
+
try {
|
|
74
|
+
if (process.platform !== 'win32') fs.chmodSync(dir, 0o700);
|
|
75
|
+
} catch {
|
|
76
|
+
/* 权限收紧失败不阻塞主流程,下面会汇报实际权限 */
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const payload = {
|
|
80
|
+
version: CREDENTIALS_VERSION,
|
|
81
|
+
...data,
|
|
82
|
+
saved_at: new Date(now).toISOString(),
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
const tmp = `${file}.tmp-${process.pid}`;
|
|
86
|
+
const text = JSON.stringify(payload, null, 2) + '\n';
|
|
87
|
+
// 先以 0600 创建临时文件:避免"先写明文再 chmod"中间那一瞬间是 0644
|
|
88
|
+
const fd = fs.openSync(tmp, 'w', 0o600);
|
|
89
|
+
try {
|
|
90
|
+
fs.writeFileSync(fd, text, 'utf8');
|
|
91
|
+
} finally {
|
|
92
|
+
fs.closeSync(fd);
|
|
93
|
+
}
|
|
94
|
+
try {
|
|
95
|
+
fs.chmodSync(tmp, 0o600);
|
|
96
|
+
} catch {
|
|
97
|
+
/* Windows 上基本无效,忽略 */
|
|
98
|
+
}
|
|
99
|
+
fs.renameSync(tmp, file);
|
|
100
|
+
try {
|
|
101
|
+
fs.chmodSync(file, 0o600);
|
|
102
|
+
} catch {
|
|
103
|
+
/* 同上 */
|
|
104
|
+
}
|
|
105
|
+
return checkFileMode(file);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** 删除凭据。返回是否真的删了(不存在 → false) */
|
|
109
|
+
export function deleteCredentials(file) {
|
|
110
|
+
try {
|
|
111
|
+
fs.unlinkSync(file);
|
|
112
|
+
return true;
|
|
113
|
+
} catch (e) {
|
|
114
|
+
if (e && e.code === 'ENOENT') return false;
|
|
115
|
+
throw new CliError(`删除凭据文件失败:${e.message}`, { kind: 'credentials', hint: `文件位置:${file}` });
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** 令牌是否(按本地记录)已过期。留 60 秒时钟偏差余量,避免"刚好卡在边界"白跑一次请求。 */
|
|
120
|
+
export function isExpired(creds, { now = Date.now(), skewMs = 60000 } = {}) {
|
|
121
|
+
const exp = creds && creds.expires_at ? new Date(creds.expires_at).getTime() : null;
|
|
122
|
+
if (!exp || !Number.isFinite(exp)) return false; // 没有过期信息 → 交给服务端判
|
|
123
|
+
return exp - skewMs <= now;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** 取登录态;未登录/已过期都给"照做就行"的错误(exit code 3) */
|
|
127
|
+
export function requireCredentials(file, { allowExpired = false, now = Date.now() } = {}) {
|
|
128
|
+
const creds = readCredentials(file);
|
|
129
|
+
if (!creds) {
|
|
130
|
+
throw new CliError('尚未登录:本地没有凭据文件', {
|
|
131
|
+
kind: 'unauthenticated',
|
|
132
|
+
hint: '先运行 `wkgeo login` 完成一次授权',
|
|
133
|
+
exitCode: EXIT.AUTH,
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
if (!allowExpired && isExpired(creds, { now })) {
|
|
137
|
+
throw new CliError(`本地记录的令牌已过期(过期时间 ${creds.expires_at})`, {
|
|
138
|
+
kind: 'expired',
|
|
139
|
+
hint: '运行 `wkgeo login` 重新授权',
|
|
140
|
+
exitCode: EXIT.AUTH,
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
return creds;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** 由 token 响应构造凭据对象(**唯一**把 access_token 写进文件的地方) */
|
|
147
|
+
export function credentialsFromToken({ clientId, tokenResponse, account = null, now = Date.now(), scope = '' }) {
|
|
148
|
+
const expiresIn = Number(tokenResponse.expires_in);
|
|
149
|
+
return {
|
|
150
|
+
client_id: clientId,
|
|
151
|
+
access_token: tokenResponse.access_token,
|
|
152
|
+
refresh_token: tokenResponse.refresh_token || null,
|
|
153
|
+
token_type: tokenResponse.token_type || 'Bearer',
|
|
154
|
+
scope: tokenResponse.scope || scope || '',
|
|
155
|
+
expires_in: Number.isFinite(expiresIn) ? expiresIn : null,
|
|
156
|
+
obtained_at: new Date(now).toISOString(),
|
|
157
|
+
expires_at: Number.isFinite(expiresIn) ? new Date(now + expiresIn * 1000).toISOString() : null,
|
|
158
|
+
account,
|
|
159
|
+
};
|
|
160
|
+
}
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 「待完成的设备码登录」状态文件 —— 支撑 `login --device --no-wait` + `login --device-continue`。
|
|
3
|
+
*
|
|
4
|
+
* ===========================================================================
|
|
5
|
+
* ## 为什么需要它(老板 2026-10-02 的用法)
|
|
6
|
+
* "检测到有代理就**直接返回设备码**,用户把它输入到 AI 端的对话框里,Agent 拿这个
|
|
7
|
+
* 设备码也能获取……加一个这样的获取路径,因为这样比较友好。"
|
|
8
|
+
*
|
|
9
|
+
* AI 端(Agent)是**一轮一轮**工作的:它一次工具调用里没法"挂着等 10 分钟"再往下走
|
|
10
|
+
* (那会把用户晾住,还可能撞上工具超时)。所以更合适的形态是:
|
|
11
|
+
* ① `wkgeo login --device --no-wait` → 申请码、打印短码/网址、**立刻退出**
|
|
12
|
+
* ② AI 把短码/网址转达给用户,用户在自己浏览器里点「同意」
|
|
13
|
+
* ③ `wkgeo login --device-continue` → 用磁盘上那份状态换票、写凭据、完成登录
|
|
14
|
+
* ② 与 ③ 之间隔多久都行(只要没超过设备码有效期)。中间**不需要任何长驻进程**。
|
|
15
|
+
*
|
|
16
|
+
* ## 文件位置与权限
|
|
17
|
+
* 与凭据文件同目录、同前缀:`<credentials.json>.device-pending.json`。
|
|
18
|
+
* * 为什么跟凭据放一起:`--credentials` 指向哪,这份状态就跟着去哪 —— 测试/多环境
|
|
19
|
+
* 互不干扰(用户的 HOME 里也不会多出一个莫名其妙的文件)。
|
|
20
|
+
* * **0600**:`device_code` 是"用户一旦同意就能换到 30 天令牌"的东西,
|
|
21
|
+
* 等同于一次性凭据,绝不能比凭据文件宽松(踩过的坑:一开始用的是默认 0644)。
|
|
22
|
+
*
|
|
23
|
+
* ## ⚠️ 刻意不做的事
|
|
24
|
+
* * 不做自动清理定时器:这是一次性小文件,`--device-continue` 成功/失败(过期、拒绝)后
|
|
25
|
+
* 会立刻删掉;用户真想放弃时 `login --device` 会覆盖它。
|
|
26
|
+
* * 不在文件里放任何**账号**信息:此刻还不知道是谁在授权(用户还没点同意)。
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
import fs from 'node:fs';
|
|
30
|
+
import path from 'node:path';
|
|
31
|
+
|
|
32
|
+
import { CliError, EXIT } from './errors.mjs';
|
|
33
|
+
|
|
34
|
+
export const PENDING_VERSION = 1;
|
|
35
|
+
|
|
36
|
+
/** 待完成设备码的状态文件路径(与凭据文件同目录同前缀) */
|
|
37
|
+
export function pendingDeviceFile(credentialsFile) {
|
|
38
|
+
return `${credentialsFile}.device-pending.json`;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* 写状态文件(0600,原子写)。
|
|
43
|
+
* 与 credentials.mjs 的 writeCredentials 同一套做法:先 0600 建临时文件再 rename,
|
|
44
|
+
* 避免"写一半被 Ctrl+C"留下半个 JSON。
|
|
45
|
+
*/
|
|
46
|
+
export function savePendingDevice(file, device, { now = Date.now() } = {}) {
|
|
47
|
+
const dir = path.dirname(file);
|
|
48
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
49
|
+
const payload = {
|
|
50
|
+
version: PENDING_VERSION,
|
|
51
|
+
base: device.base || null,
|
|
52
|
+
client_id: device.client_id || null,
|
|
53
|
+
device_code: device.device_code,
|
|
54
|
+
user_code: device.user_code,
|
|
55
|
+
verification_uri: device.verification_uri,
|
|
56
|
+
verification_uri_complete: device.verification_uri_complete || null,
|
|
57
|
+
open_url: device.open_url || device.verification_uri_complete || device.verification_uri,
|
|
58
|
+
expires_in: device.expires_in,
|
|
59
|
+
interval: device.interval,
|
|
60
|
+
expires_at: device.expires_at,
|
|
61
|
+
requested_at: device.requested_at,
|
|
62
|
+
saved_at: new Date(now).toISOString(),
|
|
63
|
+
};
|
|
64
|
+
const tmp = `${file}.tmp-${process.pid}`;
|
|
65
|
+
const fd = fs.openSync(tmp, 'w', 0o600);
|
|
66
|
+
try {
|
|
67
|
+
fs.writeFileSync(fd, JSON.stringify(payload, null, 2) + '\n', 'utf8');
|
|
68
|
+
} finally {
|
|
69
|
+
fs.closeSync(fd);
|
|
70
|
+
}
|
|
71
|
+
try {
|
|
72
|
+
fs.chmodSync(tmp, 0o600);
|
|
73
|
+
} catch {
|
|
74
|
+
/* Windows 上基本无效,忽略(真正的保护来自用户目录 ACL) */
|
|
75
|
+
}
|
|
76
|
+
fs.renameSync(tmp, file);
|
|
77
|
+
return file;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** 读状态文件:不存在返回 null;内容坏掉 → 抛"照做就行"的错误,绝不静默 */
|
|
81
|
+
export function readPendingDevice(file) {
|
|
82
|
+
let text;
|
|
83
|
+
try {
|
|
84
|
+
text = fs.readFileSync(file, 'utf8');
|
|
85
|
+
} catch (e) {
|
|
86
|
+
if (e && e.code === 'ENOENT') return null;
|
|
87
|
+
throw new CliError(`读取待完成的设备码状态失败:${e.message}`, { kind: 'device_state', hint: `文件位置:${file}` });
|
|
88
|
+
}
|
|
89
|
+
let parsed;
|
|
90
|
+
try {
|
|
91
|
+
parsed = JSON.parse(text);
|
|
92
|
+
} catch {
|
|
93
|
+
throw new CliError(`待完成的设备码状态文件不是合法 JSON:${file}`, {
|
|
94
|
+
kind: 'device_state',
|
|
95
|
+
hint: '删掉它再运行 `wkgeo login --device` 重新申请一个短码',
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
if (!parsed || typeof parsed !== 'object' || !parsed.device_code || !parsed.user_code) {
|
|
99
|
+
throw new CliError(`待完成的设备码状态文件缺少 device_code / user_code:${file}`, {
|
|
100
|
+
kind: 'device_state',
|
|
101
|
+
hint: '删掉它再运行 `wkgeo login --device` 重新申请一个短码',
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
return parsed;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** 删除状态文件(幂等;不存在也算成功) */
|
|
108
|
+
export function deletePendingDevice(file) {
|
|
109
|
+
try {
|
|
110
|
+
fs.unlinkSync(file);
|
|
111
|
+
return true;
|
|
112
|
+
} catch (e) {
|
|
113
|
+
if (e && e.code === 'ENOENT') return false;
|
|
114
|
+
throw new CliError(`删除待完成的设备码状态失败:${e.message}`, { kind: 'device_state', hint: `文件位置:${file}` });
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** 该状态是否已过期(`now` 可注入,便于单测) */
|
|
119
|
+
export function isPendingExpired(pending, { now = Date.now(), skewMs = 0 } = {}) {
|
|
120
|
+
const exp = Number(pending && pending.expires_at);
|
|
121
|
+
if (!Number.isFinite(exp) || exp <= 0) return false; // 没记录到期时刻 → 交给服务端判
|
|
122
|
+
return exp - skewMs <= now;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** 给 `--device-continue` 用的:状态过期时的统一错误 */
|
|
126
|
+
export function pendingExpiredError(file) {
|
|
127
|
+
return new CliError('上一次的设备码已经过期(超过有效期),无法继续等待', {
|
|
128
|
+
kind: 'expired',
|
|
129
|
+
hint: `重新运行 \`wkgeo login --device\` 申请新的短码(状态文件:${file})`,
|
|
130
|
+
exitCode: EXIT.AUTH,
|
|
131
|
+
});
|
|
132
|
+
}
|