@wkgeo/cli 0.0.0-stage → 1.0.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.
Files changed (51) hide show
  1. package/CHANGELOG.md +208 -0
  2. package/LICENSE +21 -0
  3. package/README.md +1042 -3
  4. package/SKILL.md +927 -0
  5. package/lib/ai/client.mjs +161 -0
  6. package/lib/ai/config.mjs +221 -0
  7. package/lib/ai/context.mjs +468 -0
  8. package/lib/ai/log.mjs +53 -0
  9. package/lib/api.mjs +339 -0
  10. package/lib/args.mjs +235 -0
  11. package/lib/cli.mjs +168 -0
  12. package/lib/cms.mjs +330 -0
  13. package/lib/commands/ai.mjs +392 -0
  14. package/lib/commands/apps.mjs +116 -0
  15. package/lib/commands/auth.mjs +1288 -0
  16. package/lib/commands/billing.mjs +666 -0
  17. package/lib/commands/cms.mjs +2533 -0
  18. package/lib/commands/config-auth.mjs +621 -0
  19. package/lib/commands/config.mjs +434 -0
  20. package/lib/commands/dnscred.mjs +428 -0
  21. package/lib/commands/domainops.mjs +546 -0
  22. package/lib/commands/domainorder.mjs +439 -0
  23. package/lib/commands/import.mjs +164 -0
  24. package/lib/commands/index.mjs +528 -0
  25. package/lib/commands/logs.mjs +141 -0
  26. package/lib/commands/orders.mjs +444 -0
  27. package/lib/commands/overview.mjs +394 -0
  28. package/lib/commands/plugins.mjs +678 -0
  29. package/lib/commands/site.mjs +435 -0
  30. package/lib/commands/siteops.mjs +1012 -0
  31. package/lib/commands/sites.mjs +905 -0
  32. package/lib/commands/skill.mjs +119 -0
  33. package/lib/config.mjs +351 -0
  34. package/lib/credentials.mjs +160 -0
  35. package/lib/device-store.mjs +132 -0
  36. package/lib/device.mjs +464 -0
  37. package/lib/errors.mjs +299 -0
  38. package/lib/format.mjs +339 -0
  39. package/lib/http.mjs +71 -0
  40. package/lib/index.mjs +44 -0
  41. package/lib/local-import.mjs +185 -0
  42. package/lib/login.mjs +1638 -0
  43. package/lib/oauth-urls.mjs +163 -0
  44. package/lib/page.mjs +393 -0
  45. package/lib/pkce.mjs +48 -0
  46. package/lib/proxy.mjs +454 -0
  47. package/lib/qr.mjs +31 -0
  48. package/lib/runtime.mjs +650 -0
  49. package/lib/site-state.mjs +137 -0
  50. package/package.json +53 -4
  51. package/wkgeo.mjs +17 -0
@@ -0,0 +1,392 @@
1
+ /**
2
+ * `wkgeo ai`(本地大模型)+ `wkgeo context export`(把站点上下文导成文件)。
3
+ *
4
+ * 两个命令共用 `lib/ai/context.mjs` 的白名单取数:**同一个出口**,
5
+ * 所以"模型能读到什么"只有一个答案,改一处两处都变。
6
+ *
7
+ * 三条底线(写死在代码里,不是文档口号):
8
+ * 1. 只连本机(`assertLocalEndpoint`)——除非配置显式开 `ai.allowRemote`;
9
+ * 2. 上下文先脱敏再拼 prompt(`collectContext` 内部就 `maskPiiDeep`);
10
+ * 3. 日志只记元信息(`lib/ai/log.mjs`),**不记 prompt、不记回答**。
11
+ */
12
+
13
+ import fs from 'node:fs';
14
+ import path from 'node:path';
15
+
16
+ import { UsageError } from '../errors.mjs';
17
+ import { maskPii } from '../format.mjs';
18
+ import { resolveAiConfig, assertLocalEndpoint, hostOf } from '../ai/config.mjs';
19
+ import { createAiClient, estimateTokens } from '../ai/client.mjs';
20
+ import {
21
+ CONTEXT_DOMAINS,
22
+ DEFAULT_CONTEXT_DOMAINS,
23
+ contextNames,
24
+ parseContextDomains,
25
+ collectContext,
26
+ contextToText,
27
+ contextToMarkdown,
28
+ domainTableRows,
29
+ } from '../ai/context.mjs';
30
+ import { createAiLogger, aiLogFile } from '../ai/log.mjs';
31
+
32
+ /** `ai` 命令组共用的两个"连哪台"标志(`--model` / `--base-url` 都只覆盖本次调用) */
33
+ const AI_CONNECT_FLAGS = {
34
+ model: { type: 'string', desc: '本次用的模型(默认取配置 ai.model,Ollama 默认 qwen2.5:7b)' },
35
+ 'base-url': { type: 'string', desc: '本次用的 OpenAI 兼容地址(默认配置 ai.baseUrl;**只允许本机**)' },
36
+ };
37
+
38
+ const CONTEXT_FLAG = {
39
+ context: {
40
+ type: 'string',
41
+ desc: `取哪些数据域(逗号分隔;可用:${contextNames()};默认 ${DEFAULT_CONTEXT_DOMAINS.join(',')})`,
42
+ },
43
+ };
44
+
45
+ /** 给模型的系统提示词(写清楚"你是谁、数据从哪来、不许编") */
46
+ function systemPrompt() {
47
+ return [
48
+ '你是「云站(wkgeo)」的站点运营助手,回答关于**某一个站点**的问题。',
49
+ '',
50
+ '规则:',
51
+ '1. 下面「站点上下文」由 CLI 抓取并**已脱敏**(手机号/邮箱/IP/浏览器标识/订单号/密钥已抹掉)。',
52
+ '2. 只依据上下文回答;上下文没有的信息就说"上下文里没有",**不要编造**栏目名、数量、状态。',
53
+ '3. 数字类问题(多少栏目、多少内容、多久没更新)先给结论,再给依据。',
54
+ '4. 用中文回答,简短、可执行;需要改站点时给出对应的 `wkgeo` 命令建议。',
55
+ ].join('\n');
56
+ }
57
+
58
+ /** 精简的 AI 配置回执(**绝不含 Key**) */
59
+ function aiReceipt(ai, extra = {}) {
60
+ return {
61
+ base_url: ai.baseUrl,
62
+ model: ai.model,
63
+ provider: ai.provider,
64
+ local: true,
65
+ key_configured: Boolean(ai.apiKey),
66
+ timeout_ms: ai.timeoutMs,
67
+ ...extra,
68
+ };
69
+ }
70
+
71
+ /** 把上下文裁到上限(超了就在末尾标一下,别默默吃掉) */
72
+ function clipContext(text, maxChars) {
73
+ const s = String(text || '');
74
+ const limit = Math.max(2000, Number(maxChars) || 120000);
75
+ if (s.length <= limit) return { text: s, truncated: false };
76
+ return { text: `${s.slice(0, limit)}\n\n(上下文已截断:超出 ai.maxContextChars=${limit} 的部分没有发给模型)`, truncated: true };
77
+ }
78
+
79
+ /** 造客户端:闸门 + 警告都在这里(`ai ping` / `ai ask` / `ai chat` 三处行为一致) */
80
+ function makeClient(ctx, ai) {
81
+ const { remote } = assertLocalEndpoint(ai.baseUrl, { allowRemote: ai.allowRemote });
82
+ if (remote) {
83
+ ctx.out.warn(
84
+ `⚠️ 正在连接非本机地址「${hostOf(ai.baseUrl)}」(配置里开了 ai.allowRemote):站点数据会离开这台机器。`,
85
+ );
86
+ }
87
+ return createAiClient({ config: ai, fetchImpl: ctx.fetchImpl });
88
+ }
89
+
90
+ /* ------------------------------------------------------------------ */
91
+ /* ai ping */
92
+ /* ------------------------------------------------------------------ */
93
+
94
+ export const aiPingCommand = {
95
+ name: 'ai ping',
96
+ summary: '检查本地模型能不能用(列可用模型;不打印任何 Key)',
97
+ usage: 'wkgeo ai ping [--base-url <地址>] [--json]',
98
+ args: [],
99
+ flags: { ...AI_CONNECT_FLAGS },
100
+ examples: [
101
+ 'wkgeo ai ping',
102
+ 'wkgeo ai ping --base-url http://127.0.0.1:1234/v1 # LM Studio',
103
+ ],
104
+ notes: [
105
+ '默认打 http://127.0.0.1:11434/v1(Ollama 的 OpenAI 兼容层);LM Studio 是 :1234/v1。',
106
+ '**只连本机**:非 localhost / 127.0.0.1 / ::1 会被拒绝(除非配置 ai.allowRemote=true)。',
107
+ 'Key 只从环境变量取(默认 WKONGAI_AI_KEY),任何输出里都不会出现它的值。',
108
+ ],
109
+ async run(ctx) {
110
+ const ai = resolveAiConfig({ flags: ctx.flags, env: ctx.env, siteStateFile: ctx.config.siteStateFile });
111
+ const client = makeClient(ctx, ai);
112
+ const { models } = await client.listModels();
113
+ const ready = models.includes(ai.model);
114
+
115
+ ctx.out.line('');
116
+ ctx.out.line(`本地模型端点:${ai.baseUrl}`);
117
+ ctx.out.line(`配置的模型:${ai.model}${ready ? '(已就绪)' : models.length ? '(不在模型清单里,用 --model 换一个)' : ''}`);
118
+ if (models.length) {
119
+ ctx.out.line(`可用模型(${models.length} 个):`);
120
+ ctx.out.table([{ title: '模型', key: 'id', width: 40 }], models.map((id) => ({ id })));
121
+ } else {
122
+ ctx.out.warn('端点没返回任何模型:先 `ollama pull qwen2.5:7b`(或 LM Studio 里下载一个模型)。');
123
+ }
124
+ ctx.out.info(`配置来源:${ai.sources.join(';')}`);
125
+ ctx.done(
126
+ aiReceipt(ai, {
127
+ ready,
128
+ models,
129
+ model_known: ready,
130
+ }),
131
+ );
132
+ },
133
+ };
134
+
135
+ /* ------------------------------------------------------------------ */
136
+ /* ai ask */
137
+ /* ------------------------------------------------------------------ */
138
+
139
+ /**
140
+ * 一次问答(`ai ask` 与 `ai chat` 的第一轮共用)。
141
+ * @returns {Promise<{answer:string, model:string, collected:object, clipped:object, ms:number}>}
142
+ */
143
+ async function askOnce(ctx, ai, client, { question, domains, history = [], logger }) {
144
+ const collected = await collectContext(ctx, { domains });
145
+ const text = contextToText(collected);
146
+ const clipped = clipContext(text, ai.maxContextChars);
147
+ const messages = [
148
+ { role: 'system', content: systemPrompt() },
149
+ { role: 'system', content: `## 站点上下文\n\n${clipped.text}` },
150
+ ...history,
151
+ { role: 'user', content: question },
152
+ ];
153
+
154
+ const started = ctx.now();
155
+ const res = await client.chat({ messages, model: ai.model });
156
+ const ms = Math.max(0, ctx.now() - started);
157
+
158
+ if (logger) {
159
+ logger.log({
160
+ cmd: ctx.spec.name,
161
+ model: res.model,
162
+ ms,
163
+ promptChars: messages.reduce((sum, m) => sum + String(m.content || '').length, 0),
164
+ outputChars: res.text.length,
165
+ contextChars: clipped.text.length,
166
+ truncated: clipped.truncated,
167
+ domains,
168
+ redactedFields: ['phone', 'email', 'ip', 'user_agent', 'order_no', 'secret', 'oss_signature'],
169
+ ok: true,
170
+ });
171
+ }
172
+ return { answer: res.text, model: res.model, collected, clipped, ms };
173
+ }
174
+
175
+ export const aiAskCommand = {
176
+ name: 'ai ask',
177
+ summary: '问本地大模型一个关于站点的问题(CLI 现场取数 + 脱敏后喂给模型)',
178
+ usage: 'wkgeo ai ask <问题> [--context <数据域>] [--site <站点ID>] [--model <模型>] [--json]',
179
+ args: [{ name: 'question', required: true, desc: '要问的问题(含空格时要加引号)' }],
180
+ flags: {
181
+ ...CONTEXT_FLAG,
182
+ site: {
183
+ type: 'string',
184
+ desc: '站点 ID(默认用 `wkgeo site use` 选中的站点,可用 WKONGAI_SITE 覆盖)',
185
+ },
186
+ ...AI_CONNECT_FLAGS,
187
+ },
188
+ examples: [
189
+ 'wkgeo ai ask "这个站有哪些栏目?"',
190
+ 'wkgeo ai ask "内容里有多少草稿还没发?" --context site,overview,contents',
191
+ 'wkgeo ai ask "插件开了哪些?" --context plugins --model qwen2.5:3b',
192
+ ],
193
+ notes: [
194
+ '数据只从白名单的数据域取(`--context`),取到立刻脱敏;**订单明细/钱包流水/用户明细永远不喂**。',
195
+ '只连本机模型端点;模型回答会原样打印,不写进日志(日志只有时长/模型/字数)。',
196
+ '上下文超限时会截断并在末尾注明;减少 `--context` 的数据域最有效。',
197
+ ],
198
+ async run(ctx) {
199
+ const question = String(ctx.positional.question || '').trim();
200
+ if (!question) throw new UsageError('请给出要问的问题');
201
+
202
+ const ai = resolveAiConfig({ flags: ctx.flags, env: ctx.env, siteStateFile: ctx.config.siteStateFile });
203
+ const domains = parseContextDomains(ctx.flags.context, { config: ai });
204
+ const client = makeClient(ctx, ai);
205
+ const logger = createAiLogger({ file: aiLogFile(ctx.config.siteStateFile, new Date(ctx.now())), now: () => new Date(ctx.now()) });
206
+
207
+ const { answer, model, collected, clipped } = await askOnce(ctx, ai, client, { question, domains, logger });
208
+
209
+ ctx.out.line('');
210
+ ctx.out.notice(answer);
211
+ ctx.out.line('');
212
+ ctx.out.info(
213
+ `(模型 ${model};上下文 ${clipped.text.length} 字符≈${estimateTokens(clipped.text)} tokens${clipped.truncated ? ',已截断' : ''};数据域 ${domains.join(',')})`,
214
+ );
215
+ if (collected.notes.length) {
216
+ for (const note of collected.notes) ctx.out.info(`· ${note}`);
217
+ }
218
+ ctx.done(
219
+ aiReceipt(ai, {
220
+ answer,
221
+ model,
222
+ domains,
223
+ context_chars: clipped.text.length,
224
+ truncated: clipped.truncated,
225
+ notes: collected.notes,
226
+ redacted: true,
227
+ }),
228
+ );
229
+ },
230
+ };
231
+
232
+ /* ------------------------------------------------------------------ */
233
+ /* ai chat */
234
+ /* ------------------------------------------------------------------ */
235
+
236
+ export const aiChatCommand = {
237
+ name: 'ai chat',
238
+ summary: '和本地大模型多轮对话(非交互环境自动退化成一次 ask)',
239
+ usage: 'wkgeo ai chat [--context <数据域>] [--site <站点ID>] [--model <模型>]',
240
+ args: [],
241
+ flags: { ...CONTEXT_FLAG, site: { type: 'string', desc: '站点 ID(默认用已选中的站点)' }, ...AI_CONNECT_FLAGS },
242
+ examples: ['wkgeo ai chat', 'wkgeo ai chat --context site,overview,categories'],
243
+ notes: [
244
+ '上下文只在**开始对话时取一次**(省时间);站点数据在对话期间变了请重开一次。',
245
+ '输入 `quit` / `exit` / `:q` 或直接回车(空行)结束。',
246
+ '非 TTY / `--json` 时不进循环:读一行问题、答一次就退出(等价于 `ai ask`)。',
247
+ ],
248
+ async run(ctx) {
249
+ const ai = resolveAiConfig({ flags: ctx.flags, env: ctx.env, siteStateFile: ctx.config.siteStateFile });
250
+ const domains = parseContextDomains(ctx.flags.context, { config: ai });
251
+ const client = makeClient(ctx, ai);
252
+ const logger = createAiLogger({ file: aiLogFile(ctx.config.siteStateFile, new Date(ctx.now())), now: () => new Date(ctx.now()) });
253
+
254
+ /** 非交互 / JSON:退化成"读一行 → 答一次"(脚本里也能用,不会卡在循环里) */
255
+ if (!ctx.isTTY || ctx.out.json) {
256
+ const q = String((await ctx.ask('')) || '').trim();
257
+ if (!q) {
258
+ throw new UsageError('非交互环境下 `ai chat` 需要从 stdin 读一个问题', {
259
+ hint: '脚本里请直接用 `wkgeo ai ask "<问题>"`;`ai chat` 是给人用的多轮界面。',
260
+ });
261
+ }
262
+ const { answer, model, clipped } = await askOnce(ctx, ai, client, { question: q, domains, logger });
263
+ ctx.out.notice(answer);
264
+ ctx.done(aiReceipt(ai, { answer, model, domains, context_chars: clipped.text.length, turns: 1 }));
265
+ return;
266
+ }
267
+
268
+ // 交互:先把上下文取好,再进循环(每轮只发历史 + 新问题)
269
+ const collected = await collectContext(ctx, { domains });
270
+ const text = contextToText(collected);
271
+ const clipped = clipContext(text, ai.maxContextChars);
272
+ const base = [
273
+ { role: 'system', content: systemPrompt() },
274
+ { role: 'system', content: `## 站点上下文\n\n${clipped.text}` },
275
+ ];
276
+ const history = [];
277
+
278
+ ctx.out.line('');
279
+ ctx.out.line(`本地模型:${ai.model}(${ai.baseUrl})`);
280
+ ctx.out.info(`数据域:${domains.join(',')};上下文 ${clipped.text.length} 字符${clipped.truncated ? '(已截断)' : ''}`);
281
+ ctx.out.info('输入问题开始对话;空行 / quit 结束。');
282
+ for (const note of collected.notes) ctx.out.info(`· ${note}`);
283
+
284
+ let turns = 0;
285
+ for (;;) {
286
+ const q = String((await ctx.ask('你> ')) || '').trim();
287
+ if (!q || /^(quit|exit|:q)$/i.test(q)) break;
288
+ const started = ctx.now();
289
+ const res = await client.chat({ messages: [...base, ...history, { role: 'user', content: q }], model: ai.model });
290
+ const ms = Math.max(0, ctx.now() - started);
291
+ turns += 1;
292
+ history.push({ role: 'user', content: q }, { role: 'assistant', content: res.text });
293
+ // 历史别无限长:只留最近 12 条(6 轮),否则小模型的上下文会被自己撑爆
294
+ while (history.length > 12) history.splice(0, 2);
295
+
296
+ ctx.out.line('');
297
+ ctx.out.notice(res.text);
298
+ ctx.out.info(`(${ms}ms)`);
299
+ ctx.out.line('');
300
+
301
+ logger.log({
302
+ cmd: 'ai chat',
303
+ model: res.model,
304
+ ms,
305
+ promptChars: [...base, ...history].reduce((sum, m) => sum + String(m.content || '').length, 0),
306
+ outputChars: res.text.length,
307
+ contextChars: clipped.text.length,
308
+ truncated: clipped.truncated,
309
+ domains,
310
+ turn: turns,
311
+ ok: true,
312
+ });
313
+ }
314
+ ctx.done(aiReceipt(ai, { turns, domains, context_chars: clipped.text.length }));
315
+ },
316
+ };
317
+
318
+ /* ------------------------------------------------------------------ */
319
+ /* context export */
320
+ /* ------------------------------------------------------------------ */
321
+
322
+ export const contextExportCommand = {
323
+ name: 'context export',
324
+ summary: '把站点上下文(栏目/内容/插件/表单/发布)导成 JSON 或 Markdown,供任意模型使用',
325
+ usage: 'wkgeo context export [--site <站点ID>] [--out <文件>] [--format json|md] [--with-body] [--context <域>]',
326
+ args: [],
327
+ flags: {
328
+ site: { type: 'string', desc: '站点 ID(默认用已选中的站点)' },
329
+ out: { type: 'string', desc: '写到这个文件(不给就打到终端)' },
330
+ format: { type: 'string', desc: 'json(默认)或 md' },
331
+ 'with-body': { type: 'boolean', desc: '把前 10 条内容的正文也带进来(默认只给标题/摘要)' },
332
+ ...CONTEXT_FLAG,
333
+ },
334
+ examples: [
335
+ 'wkgeo context export --out site-context.json',
336
+ 'wkgeo context export --format md --out site-context.md',
337
+ 'wkgeo context export --with-body --out site-full.md',
338
+ ],
339
+ notes: [
340
+ '导出物**默认不含**手机号 / client_ip / user_agent / 订单号 / 密钥 / OSS 签名链接(统一走 `maskPii`)。',
341
+ '文件只写到 `--out` 指定的位置,**CLI 不会上传到任何地方**;`--with-body` 才带正文(前 10 条)。',
342
+ '要喂给别的模型:`--format md` 最省事;要程序处理用 `--format json`。',
343
+ ],
344
+ async run(ctx) {
345
+ const ai = resolveAiConfig({ flags: ctx.flags, env: ctx.env, siteStateFile: ctx.config.siteStateFile });
346
+ const domains = parseContextDomains(ctx.flags.context, { config: ai });
347
+ const collected = await collectContext(ctx, { domains, withBody: ctx.flags.withBody === true });
348
+
349
+ const format = String(ctx.flags.format || 'json').toLowerCase();
350
+ if (!['json', 'md', 'markdown'].includes(format)) {
351
+ throw new UsageError(`--format 只支持 json / md,收到:${format}`);
352
+ }
353
+ const isMd = format === 'md' || format === 'markdown';
354
+ const generatedAt = new Date(ctx.now()).toISOString();
355
+
356
+ const payload = {
357
+ version: 1,
358
+ generated_at: generatedAt,
359
+ site_id: collected.siteId,
360
+ domains: collected.domains,
361
+ notes: collected.notes,
362
+ with_body: ctx.flags.withBody === true,
363
+ redacted: true,
364
+ };
365
+ const text = isMd
366
+ ? contextToMarkdown(collected, { generatedAt, withBody: ctx.flags.withBody === true })
367
+ : `${JSON.stringify(payload, null, 2)}\n`;
368
+
369
+ if (ctx.flags.out) {
370
+ const target = path.resolve(process.cwd(), String(ctx.flags.out));
371
+ fs.mkdirSync(path.dirname(target), { recursive: true });
372
+ fs.writeFileSync(target, text, 'utf8');
373
+ ctx.out.ok(`已导出:${target}(${text.length} 字符)`);
374
+ ctx.out.info('这个文件只在本机;CLI 不会上传。喂模型时按需截断。');
375
+ ctx.done({ ...payload, out: target, format: isMd ? 'md' : 'json', chars: text.length });
376
+ return;
377
+ }
378
+
379
+ // 不给 --out:Markdown 直接打到终端(不套信封,重定向就能直接用);JSON 走信封
380
+ if (isMd) {
381
+ ctx.out.plain(text);
382
+ ctx.done({ ...payload, format: 'md', chars: text.length });
383
+ } else {
384
+ ctx.done({ ...payload, format: 'json', chars: text.length });
385
+ if (!ctx.out.json) ctx.out.plain(text);
386
+ }
387
+ },
388
+ };
389
+
390
+ /** 文档/`ai ping` 表格用的域清单(保持与 `CONTEXT_DOMAINS` 同一份) */
391
+ export const AI_DOMAIN_ROWS = domainTableRows;
392
+ export { CONTEXT_DOMAINS };
@@ -0,0 +1,116 @@
1
+ /**
2
+ * 应用授权命令:`apps list` / `apps revoke`
3
+ *
4
+ * 这两个动作**用户自助**(能力 `billing:self`,所有登录用户都有),
5
+ * 所以用 OAuth 令牌本身就能调 —— 不需要管理员。
6
+ *
7
+ * ⚠️ 线上状态:`listMyOAuthAuthorizations` / `revokeMyOAuthAuthorization` 是**新加的 action**,
8
+ * 线上是否已部署要看 data 云函数有没有发版。未部署时服务端会返回
9
+ * 「未知操作: xxx」或「动作 xxx 未在权限表中登记」——这不是用户的错,
10
+ * 必须把这句话翻译成"服务端还没部署这个功能",否则会让人以为是自己用错了命令。
11
+ */
12
+
13
+ import { CliError } from '../errors.mjs';
14
+ import { formatTime } from '../format.mjs';
15
+
16
+ /** 判断"这个 action 线上还没部署"(新旧两种 dispatcher 的兜底文案都认) */
17
+ function isActionNotDeployed(err) {
18
+ const msg = String((err && err.message) || '');
19
+ return /未知操作|未在权限表中登记|未知的 action|Unknown action/i.test(msg) || (err && err.kind === 'unknown' && /action/i.test(msg));
20
+ }
21
+
22
+ export const appsListCommand = {
23
+ name: 'apps list',
24
+ summary: '我授权过的应用(应用名 / 首次授权时间 / 过期时间 / 最后使用时间 / 能力)',
25
+ usage: 'wkgeo apps list',
26
+ async run(ctx) {
27
+ const { out } = ctx;
28
+ let res;
29
+ try {
30
+ res = await ctx.callData('listMyOAuthAuthorizations', {});
31
+ } catch (e) {
32
+ if (isActionNotDeployed(e)) {
33
+ throw new CliError('服务端尚未部署「我已授权的应用」接口(listMyOAuthAuthorizations)', {
34
+ kind: 'not_deployed',
35
+ code: e.code,
36
+ hint: '这是服务端缺口(data 云函数未发版),不是命令用错了;本地仍可用 `wkgeo logout` 清理登录态',
37
+ raw: e.raw,
38
+ });
39
+ }
40
+ throw e;
41
+ }
42
+ const rows = (res && Array.isArray(res.rows) ? res.rows : []).map((r) => ({
43
+ client_id: r.client_id,
44
+ client_name: r.client_name || r.client_id,
45
+ is_public: r.is_public === undefined ? null : !!r.is_public,
46
+ scopes: Array.isArray(r.scopes) ? r.scopes : [],
47
+ first_authorized_at: r.first_authorized_at || null,
48
+ expires_at: r.expires_at || null,
49
+ last_used_at: r.last_used_at || null,
50
+ token_count: Number(r.token_count) || 0,
51
+ is_current_cli: r.client_id === ctx.config.clientId,
52
+ }));
53
+ const data = { rows, total: rows.length, current_cli_client_id: ctx.config.clientId };
54
+
55
+ if (!out.json) {
56
+ out.head(`我已授权的应用(${rows.length} 个)`);
57
+ out.table(
58
+ [
59
+ { title: '应用', key: 'client_name', width: 22 },
60
+ { title: 'client_id', key: 'client_id', width: 26 },
61
+ { title: '令牌数', key: 'token_count', width: 8 },
62
+ { title: '首次授权', key: 'first_authorized_at', format: (v) => formatTime(v), width: 20 },
63
+ { title: '过期时间', key: 'expires_at', format: (v) => formatTime(v), width: 20 },
64
+ { title: '最后使用', key: 'last_used_at', format: (v) => formatTime(v), width: 20 },
65
+ ],
66
+ rows,
67
+ );
68
+ out.info(` 当前 CLI 使用的 client_id:${ctx.config.clientId}`);
69
+ out.info(' 吊销某个应用:wkgeo apps revoke <client_id>');
70
+ }
71
+ ctx.done(data);
72
+ return data;
73
+ },
74
+ };
75
+
76
+ export const appsRevokeCommand = {
77
+ name: 'apps revoke',
78
+ summary: '吊销某个应用对我的授权(该应用所有令牌立即失效;之后需要重新授权)',
79
+ usage: 'wkgeo apps revoke <client_id>',
80
+ args: [{ name: 'clientId', required: true, desc: '应用的 client_id(见 apps list)' }],
81
+ async run(ctx) {
82
+ const { out, config } = ctx;
83
+ const clientId = ctx.positional.clientId;
84
+ let res;
85
+ try {
86
+ res = await ctx.callData('revokeMyOAuthAuthorization', { client_id: clientId });
87
+ } catch (e) {
88
+ if (isActionNotDeployed(e)) {
89
+ throw new CliError('服务端尚未部署「一键吊销授权」接口(revokeMyOAuthAuthorization)', {
90
+ kind: 'not_deployed',
91
+ code: e.code,
92
+ hint: '这是服务端缺口(data 云函数未发版);临时止血可调用 POST /api/oauth/revoke 吊销单把令牌',
93
+ raw: e.raw,
94
+ });
95
+ }
96
+ throw e;
97
+ }
98
+ const revoked = Number(res && res.revoked) || 0;
99
+ const isSelf = clientId === config.clientId;
100
+ const data = {
101
+ client_id: clientId,
102
+ revoked,
103
+ is_current_cli_client: isSelf,
104
+ local_credentials_still_present: isSelf ? !!ctx.readCredentials() : null,
105
+ };
106
+
107
+ if (!out.json) {
108
+ out.ok(`已吊销应用「${clientId}」的授权,作废令牌 ${revoked} 把`);
109
+ if (isSelf) {
110
+ out.warn('你吊销的是**当前 CLI 自己**的授权:本地令牌已失效,请重新运行 `wkgeo login`(或 `wkgeo logout` 清掉本地凭据)');
111
+ }
112
+ }
113
+ ctx.done(data);
114
+ return data;
115
+ },
116
+ };