@jeecg/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.
package/README.md CHANGED
@@ -1,3 +1,169 @@
1
- # Temporary Holding Version
1
+ # @jeecg/cli
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 在浏览器里登录 JeecgBoot / 敲敲云,给 AI skills 提供 token,不用再从 F12 复制 `X-Access-Token`。
4
+
5
+ 需要 Node.js 18 以上,不依赖第三方包。
6
+
7
+ ## 取 token(一条命令)
8
+
9
+ ```bash
10
+ jeecg auth token --host http://127.0.0.1:8080/jeecg-boot
11
+ ```
12
+
13
+ - 已登录:直接输出 token;快过期时自动用 refresh_token 换新的
14
+ - 没登录过,或者登录已过期 / 被撤销:自动打开浏览器,CLI 在本机起一个登录页,输入账号、密码、验证码,确认租户后点「授权」,命令输出 token
15
+ - `--host` 填后端地址,敲敲云 SaaS 是 `https://api.qiaoqiaoyun.com`;JeecgBoot 和敲敲云是同一套后端,用法一样
16
+ - 第一次要给地址,之后会记住,不用再带
17
+ - 提示信息都打到 stderr,stdout 只有 token,所以脚本里直接这样用:
18
+
19
+ ```bash
20
+ python xxx.py --api-base <地址> --token "$(jeecg auth token)"
21
+ ```
22
+
23
+ token 由 shell 在执行时代入,不会出现在命令和对话记录里。自动登录时最多等 110 秒(AI 工具执行命令一般 2 分钟超时),超时会提示重新执行。
24
+
25
+ ## 其他命令
26
+
27
+ ```bash
28
+ jeecg auth login [--host <地址>] # 只登录(最多等 5 分钟),不输出 token;已登录时直接确认租户,页面上可以切换账号
29
+ jeecg auth status --json # 本机登录状态:地址、用户、租户(不输出 token)
30
+ jeecg auth logout [--host <地址>] # 撤销授权并删除本机凭证
31
+ ```
32
+
33
+ ## 登录页
34
+
35
+ - 页面由 CLI 在本机 `127.0.0.1` 随机端口提供,不依赖 vue3 前端,后端也不用配置前端地址
36
+ - 验证码用原来的 `/sys/randomImage/{key}`,要不要验证码跟系统的 `jeecg.firewall.enableLoginCaptcha` 开关走;登录失败次数和网页登录共用(失败 5 次锁 10 分钟)
37
+ - 签发的是 CLI 专用的 token,不会把浏览器里的登录顶掉,开了「禁止多地登录」也一样
38
+ - 租户只记在本机(`jeecg auth status --json` 里的 `tenant_id`);用户没点名租户时,skill 用它做请求头 `X-Tenant-Id`;换租户再执行一次 `jeecg auth login`
39
+ - 地址里带随机串,只接受页面自己发的请求,别的网页操作不了;账号密码只在本机和后端之间传
40
+
41
+ ### 登录页是怎么来的
42
+
43
+ CLI 是 Node.js 写的命令行程序,跑在用户自己的电脑上,既不是 JeecgBoot 的前端(vue3),也不是后端(Java)。登录页靠 Node.js 自带的 `http` 模块提供,不用 vue,也不装第三方包:
44
+
45
+ 1. 执行 `jeecg auth login`(或者 `jeecg auth token` 发现要登录)时,CLI 在本机 `127.0.0.1` 随机挑一个端口起一个小服务器
46
+ 2. 浏览器打开 `http://127.0.0.1:端口/随机串`,服务器返回登录页;页面的 HTML、CSS、JS 都写在 `lib/page.js` 里
47
+ 3. 页面上的 JS 请求同一个本机服务器(`/api/login`、`/api/confirm` 等),CLI 再转给 JeecgBoot 后端
48
+ 4. 点「授权」后 CLI 保存 token,关掉这个服务器,页面也就没了
49
+
50
+ ```
51
+ 浏览器(显示登录页)
52
+ │ 页面、/api/login 等请求
53
+ ▼
54
+ jeecg CLI(Node.js,本机 127.0.0.1:端口) ← 既提供页面,又负责转发
55
+ │ /oauth2/token 等
56
+ ▼
57
+ JeecgBoot 后端(Java,服务器)
58
+ ```
59
+
60
+ | 部分 | 跑在哪 | 做什么 |
61
+ |---|---|---|
62
+ | 登录页(HTML + JS) | 用户的浏览器 | 输入账号、密码、验证码,选租户,点「授权」;只和本机的 CLI 通信 |
63
+ | jeecg CLI(Node.js) | 用户自己的电脑 | 提供登录页;把账号密码转给后端;保存、加密 token;自动续期 |
64
+ | JeecgBoot 后端(Java) | 服务器 | 校验账号、密码、验证码,签发 token |
65
+
66
+ 这个服务器只在登录那一会儿存在,只监听本机地址,别的电脑访问不到。
67
+
68
+ ## 打不开浏览器时(SSH 登录的服务器、没有图形界面的 Linux)
69
+
70
+ - 执行 `jeecg auth login`,它会打印登录页地址,在你自己电脑的浏览器里打开
71
+ - VS Code、Cursor 等远程连接会自动转发端口,直接点开链接即可
72
+ - 普通 SSH:先在自己电脑上执行 `ssh -L <端口>:127.0.0.1:<端口> <用户>@<服务器>`,再打开链接
73
+ - 被 AI 调用时,`jeecg auth token` 直接打印提示并退出(退出码 2):AI 改为在后台执行 `jeecg auth login`,把登录页地址发给用户
74
+ - 本机有浏览器但不想自动打开:加 `--no-open`
75
+
76
+ ## Windows PowerShell
77
+
78
+ PowerShell 里执行 `jeecg` 报「无法加载文件 ...\jeecg.ps1,因为在此系统上禁止运行脚本」时,执行一次:
79
+
80
+ ```powershell
81
+ Set-ExecutionPolicy -Scope CurrentUser RemoteSigned
82
+ ```
83
+
84
+ 只对当前用户生效,npm 全局装的 pnpm、yarn 等命令也需要这一步。不想改的话,用 `jeecg.cmd` 代替 `jeecg`。Git Bash、cmd 和 Python 的 `subprocess(..., shell=True)` 不受影响。
85
+
86
+ ## macOS / Linux / WSL
87
+
88
+ - 安装报 `EACCES`:Node 装在系统目录时(Linux 用 apt 装的、macOS 用官网安装包装的)全局安装要权限,用 `sudo npm i -g @jeecg/cli`,或者用 nvm 装 Node(不用 sudo)
89
+ - Node 版本:Linux 发行版自带的 Node 常常低于 18(例如 Ubuntu 22.04 的 apt 装的是 12),`jeecg` 会直接提示升级
90
+ - 打开浏览器:macOS 用 `open`,Linux 桌面用 `xdg-open`;没装 xdg-utils 或打不开时会提示,复制链接到浏览器打开即可
91
+ - WSL:自动打开 Windows 上的默认浏览器,WSL2 默认把 Windows 的 `127.0.0.1` 端口转发到 WSL,登录页能直接打开;关掉了端口转发(`.wslconfig` 里 `localhostForwarding=false`)时打不开,要把转发打开
92
+ - SSH 到 Mac / Linux 上执行:按上面「打不开浏览器时」处理
93
+ - refresh_token:Mac 存钥匙串,Linux 桌面存密钥环;Mac 钥匙串锁着(例如 SSH 登录)、Linux 没有密钥环(服务器、WSL、Docker 常见)时退回明文,文件权限 600
94
+
95
+ ## 服务器上的地址
96
+
97
+ - `--host` 填前端调接口用的后端地址(nginx 转发后的外网地址,例如 `https://boot.example.com/jeecgboot`),登录、换 token 都走这个地址
98
+ - 多个环境各登录一次,用 `--host` 切换,最后登录的是默认地址
99
+
100
+ ## 凭证
101
+
102
+ 存在当前用户主目录下的 `.jeecg/credentials.json`,按地址区分:
103
+
104
+ | 系统 | 位置 |
105
+ |---|---|
106
+ | Windows | `C:\Users\<用户名>\.jeecg\credentials.json` |
107
+ | macOS | `/Users/<用户名>/.jeecg/credentials.json` |
108
+ | Linux | `/home/<用户名>/.jeecg/credentials.json`(root 是 `/root/.jeecg/credentials.json`) |
109
+ | WSL | WSL 里自己的 `/home/<用户名>/.jeecg/credentials.json`,和 Windows 那份分开 |
110
+
111
+ Mac、Linux 上文件权限 600,Windows 由用户目录本身的权限保护。
112
+
113
+ refresh_token(30 天有效、能换出新 token)加密保存:Windows 用系统自带的 DPAPI(密文和当前 Windows 账号绑定),macOS 存系统钥匙串(钥匙串锁着时退回明文),Linux 有 `secret-tool` 就存系统密钥环,没有时退回明文并提示;存进去后会读回来比对,存失败不会悄悄丢掉 refresh_token;access_token 每次取 token 都要读,保持原样,取 token 不变慢。access_token 有效期和网页登录一样(84 小时),refresh_token 30 天,每次刷新换新的。
114
+
115
+ ## 后端要求
116
+
117
+ `/oauth2/metadata`(授权配置)、`/oauth2/token`(账号密码登录、refresh_token 续期)、`/oauth2/revoke`、`/oauth2/userinfo`,验证码用原来的 `/sys/randomImage/{key}`;不需要前端页面。老版本会提示「没有开启在线授权」(LHZP-2457)。
118
+
119
+ 积木报表独立部署:宿主加上前三个接口就能用,`--host` 填积木应用地址(不带 `/jmreport`);`/oauth2/userinfo` 和验证码可以不做。写法参考 jimureport-example 的 `OAuth2Controller`(用 Sa-Token 签发 token)。
120
+
121
+ ## 发布到 npm(维护者)
122
+
123
+ 包名 `@jeecg/cli`(`package.json` 的 `name`)。
124
+
125
+ **1. 改版本号**
126
+
127
+ npm 上已经发过的版本号不能再用,每次发布前把 `package.json` 里的 `version` 加一,例如 `0.1.3` → `0.1.4`;也可以执行 `npm version patch` 自动加。
128
+
129
+ **2. 检查要发布的文件**
130
+
131
+ ```bash
132
+ npm pack --dry-run
133
+ ```
134
+
135
+ 只会打包 `bin`、`lib`、`README.md`、`package.json`(由 `package.json` 的 `files` 决定),确认列表里没有多余的文件。
136
+
137
+ **3. 登录 npm**
138
+
139
+ ```bash
140
+ npm login --registry=https://registry.npmjs.org
141
+ ```
142
+
143
+ 一定要带 `--registry`:本机 npm 默认用的可能是阿里云等镜像,登录到镜像上发布不了。登录会过期,发布时报 `E401` / `E404` 就重新登录一次;`npm whoami --registry=https://registry.npmjs.org` 能看到当前登录的账号。
144
+
145
+ **4. 发布**
146
+
147
+ ```bash
148
+ npm publish
149
+ ```
150
+
151
+ - 不用带 `--registry` 和 `--access public`:`package.json` 的 `publishConfig` 已经写好发到 npmjs 官方源、公开发布(带 scope 的包默认是私有的)
152
+ - 账号开了二次验证:会提示在浏览器里确认(安全密钥或通行密钥),用验证器 App 的话加 `--otp=<6 位验证码>`
153
+ - 要在自己的终端里执行:AI 工具、脚本这类非交互环境里,npm 会把验证链接打码,提示 `EOTP` 后直接退出
154
+
155
+ **5. 确认发布成功**
156
+
157
+ ```bash
158
+ npm view @jeecg/cli version --registry=https://registry.npmjs.org
159
+ ```
160
+
161
+ npm 收到发布请求后要过几分钟才生效:这期间查到的还是旧版本,安装新版本会报 `ETARGET`,等一会儿再试。
162
+
163
+ **6. 安装或升级到新版本**
164
+
165
+ ```bash
166
+ npm i -g @jeecg/cli@<版本号> --registry=https://registry.npmjs.org --prefer-online
167
+ ```
168
+
169
+ `--prefer-online` 让 npm 不用本地缓存的旧版本信息,刚发布完马上安装时要加。
package/bin/jeecg.js ADDED
@@ -0,0 +1,73 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+ // 用到 Node 18 自带的 fetch。Linux 发行版自带的 Node 常常偏旧(例如 Ubuntu 22.04 用 apt 装的是 12),
4
+ // 不先拦住的话会报一串语法错误或 fetch is not defined,看不出原因
5
+ if (Number(process.versions.node.split('.')[0]) < 18) {
6
+ console.error('jeecg 需要 Node.js 18 及以上,当前是 ' + process.version + ',请升级后再试(可以用 nvm 或从 https://nodejs.org 安装)');
7
+ process.exit(1);
8
+ }
9
+ const auth = require('../lib/auth');
10
+
11
+ const USAGE = `jeecg 命令行工具
12
+
13
+ 用法:
14
+ jeecg auth token [--host <地址>] [--no-open]
15
+ 输出可用的 access_token,给脚本用:--token "$(jeecg auth token)"
16
+ 快过期自动刷新;没登录过或登录已失效时自动打开浏览器登录,完成后输出(提示信息打到 stderr,不影响取值)
17
+ jeecg auth login [--host <地址>] [--no-open]
18
+ 只登录(最多等 5 分钟),不输出 token;已经登录过时直接确认租户,也可以在页面上切换账号
19
+ jeecg auth status [--host <地址>] [--json]
20
+ 查看本机登录状态:地址、用户、租户(不输出 token)
21
+ jeecg auth logout [--host <地址>]
22
+ 撤销授权并删除本机凭证
23
+
24
+ --host 后端地址,例如 http://127.0.0.1:8080/jeecg-boot,敲敲云 SaaS 为 https://api.qiaoqiaoyun.com;
25
+ 不填时用上次登录的地址
26
+
27
+ 登录页:CLI 在本机打开登录页,输入账号、密码、验证码,确认租户后点「授权」
28
+
29
+ 打不开浏览器时(SSH 登录的服务器):
30
+ 在自己电脑的浏览器里打开命令打印的登录页地址;VS Code、Cursor 远程会自动转发端口,
31
+ 普通 SSH 先执行 ssh -L <端口>:127.0.0.1:<端口> <用户>@<服务器>;
32
+ 被 AI 调用时 jeecg auth token 直接提示后退出(退出码 2),改为在后台执行 jeecg auth login 等用户登录`;
33
+
34
+ const VALUE_OPTIONS = ['host'];
35
+
36
+ function parseArgs(argv) {
37
+ const args = { _: [] };
38
+ for (let i = 0; i < argv.length; i++) {
39
+ const a = argv[i];
40
+ const name = a.startsWith('--') ? a.slice(2).split('=')[0] : null;
41
+ if (a === '--no-open') {
42
+ args.open = false;
43
+ } else if (a === '--json') {
44
+ args.json = true;
45
+ } else if (a === '-h' || a === '--help') {
46
+ args.help = true;
47
+ } else if (VALUE_OPTIONS.includes(name)) {
48
+ // 支持 --host x 和 --host=x 两种写法
49
+ args[name] = a.includes('=') ? a.slice(a.indexOf('=') + 1) : argv[++i];
50
+ } else {
51
+ args._.push(a);
52
+ }
53
+ }
54
+ return args;
55
+ }
56
+
57
+ async function main() {
58
+ const args = parseArgs(process.argv.slice(2));
59
+ const [group, cmd] = args._;
60
+ const commands = { login: auth.login, token: auth.token, status: auth.status, logout: auth.logout };
61
+ const handler = group === 'auth' ? commands[cmd] : null;
62
+ if (args.help || !handler) {
63
+ console.log(USAGE);
64
+ process.exitCode = args.help ? 0 : 1;
65
+ return;
66
+ }
67
+ await handler(args);
68
+ }
69
+
70
+ main().catch((e) => {
71
+ console.error(e.message || e);
72
+ process.exitCode = 1;
73
+ });
package/lib/auth.js ADDED
@@ -0,0 +1,392 @@
1
+ 'use strict';
2
+ /**
3
+ * jeecg auth login / token / status / logout
4
+ *
5
+ * 登录:CLI 在本机 127.0.0.1 起登录页(见 page.js),浏览器里登录、确认租户,CLI 用账号密码向后端 /oauth2/token 换 token。
6
+ * 不依赖 vue3 前端,也不用配置前端地址;JeecgBoot 和敲敲云是同一套后端,不用区分。
7
+ *
8
+ * token 存到 ~/.jeecg/credentials.json(refresh_token 加密,见 secret.js),快过期时用 refresh_token 自动续期
9
+ *
10
+ * 输出约定:stdout 只放给程序用的结果(token、status --json),提示信息一律打到 stderr,
11
+ * 这样 --token "$(jeecg auth token)" 里就算触发了登录,拿到的也只有 token
12
+ */
13
+ const fs = require('fs');
14
+ const readline = require('readline');
15
+ const { spawn } = require('child_process');
16
+ const store = require('./store');
17
+ const secret = require('./secret');
18
+ const { pageLogin } = require('./page');
19
+
20
+ /** 后端内置的公共客户端,没有 secret */
21
+ const CLIENT_ID = 'jeecg-cli';
22
+ /** 手动执行 jeecg auth login 时,最多等 5 分钟 */
23
+ const LOGIN_TIMEOUT_MS = 5 * 60 * 1000;
24
+ /** jeecg auth token 自动登录时只等 110 秒:AI 工具执行命令默认 2 分钟超时,先自己超时退出、给出提示,别被直接杀掉 */
25
+ const AUTO_LOGIN_TIMEOUT_MS = 110 * 1000;
26
+ /** access_token 还剩 5 分钟就提前刷新 */
27
+ const REFRESH_AHEAD_MS = 5 * 60 * 1000;
28
+ /** 被 AI 调用又打不开浏览器时的退出码:这次没拿到 token,按命令打印的提示让用户在自己电脑上完成登录 */
29
+ const MANUAL_EXIT_CODE = 2;
30
+ const HOST_EXAMPLE = '后端地址,例如 http://127.0.0.1:8080/jeecg-boot';
31
+ /** 打不开浏览器时(SSH 登录的服务器),告诉用户怎么在自己电脑上打开本机登录页;{port} 换成登录页的端口 */
32
+ const REMOTE_HINT =
33
+ '这台机器打不开浏览器(例如 SSH 登录的服务器),请在你自己电脑的浏览器里打开上面的地址:\n' +
34
+ '- VS Code、Cursor 等远程连接会自动转发端口,直接点开链接即可\n' +
35
+ '- 普通 SSH:先在自己电脑上执行 ssh -L {port}:127.0.0.1:{port} <用户>@<服务器>,再打开链接';
36
+
37
+ async function login(args) {
38
+ const host = await resolveHost(args, true);
39
+ const cred = await browserLogin(host, args, LOGIN_TIMEOUT_MS, true);
40
+ if (cred) {
41
+ console.error(successText(cred));
42
+ }
43
+ }
44
+
45
+ /**
46
+ * 输出可用的 access_token(给脚本用:--token "$(jeecg auth token)"),一条命令把取 token 的几种情况都处理掉:
47
+ * 1. 已登录且没过期:直接输出
48
+ * 2. 快过期:用 refresh_token 换新的
49
+ * 3. 没登录过,或者登录已过期 / 被撤销:自动打开浏览器登录,完成后输出
50
+ */
51
+ async function token(args) {
52
+ const host = await resolveHost(args, true);
53
+ const cred = store.load().hosts[host];
54
+ if (cred && Date.now() < cred.expiresAt - REFRESH_AHEAD_MS) {
55
+ process.stdout.write(cred.accessToken + '\n');
56
+ return;
57
+ }
58
+ const refreshed = cred ? await refresh(host, cred) : null;
59
+ if (refreshed) {
60
+ process.stdout.write(refreshed.accessToken + '\n');
61
+ return;
62
+ }
63
+ console.error(cred ? `登录已过期或已被撤销(${host}),重新登录:` : `还没有登录 ${host},开始登录:`);
64
+ const fresh = await browserLogin(host, args, AUTO_LOGIN_TIMEOUT_MS, false);
65
+ if (!fresh) {
66
+ // 打不开浏览器:已经打印了怎么在用户自己电脑上登录,这次不输出 token
67
+ return;
68
+ }
69
+ console.error(successText(fresh));
70
+ process.stdout.write(fresh.accessToken + '\n');
71
+ }
72
+
73
+ /**
74
+ * 只看本机保存的登录信息,不输出 token;--json 给程序读地址、用户和租户
75
+ */
76
+ async function status(args) {
77
+ const data = store.load();
78
+ const hosts = args.host ? [await resolveHost(args, false)] : Object.keys(data.hosts);
79
+ const list = hosts
80
+ .filter((h) => data.hosts[h])
81
+ .map((h) => ({
82
+ host: h,
83
+ username: data.hosts[h].username,
84
+ tenant_id: data.hosts[h].tenantId,
85
+ tenant_name: data.hosts[h].tenantName || null,
86
+ default: h === data.defaultHost,
87
+ }));
88
+ if (args.json) {
89
+ console.log(JSON.stringify({ logged_in: list.length > 0, default_host: data.defaultHost, hosts: list }, null, 2));
90
+ return;
91
+ }
92
+ if (list.length === 0) {
93
+ console.log('还没有登录,请执行:jeecg auth login --host <后端地址>');
94
+ process.exitCode = 1;
95
+ return;
96
+ }
97
+ for (const c of list) {
98
+ console.log(`${c.default ? '* ' : ' '}${c.host} 用户 ${c.username}${tenantText(c.tenant_id, c.tenant_name, ' 租户 ')}`);
99
+ }
100
+ }
101
+
102
+ async function logout(args) {
103
+ const host = await resolveHost(args, false);
104
+ const data = store.load();
105
+ const cred = data.hosts[host];
106
+ if (!cred) {
107
+ console.log(`本机没有 ${host} 的登录信息`);
108
+ return;
109
+ }
110
+ const refreshToken = secret.unprotect(host, cred.refreshToken);
111
+ if (refreshToken) {
112
+ try {
113
+ await revokeToken(cred.revocationEndpoint, refreshToken);
114
+ } catch (e) {
115
+ console.log(`服务器撤销失败(${e.message}),只删除了本机凭证`);
116
+ }
117
+ }
118
+ secret.remove(host, cred.refreshToken);
119
+ delete data.hosts[host];
120
+ if (data.defaultHost === host) {
121
+ data.defaultHost = Object.keys(data.hosts)[0] || null;
122
+ }
123
+ store.save(data);
124
+ console.log(`已退出 ${host}`);
125
+ }
126
+
127
+ /**
128
+ * 在本机登录页登录(page.js),登录、确认租户后保存凭证并设为默认地址;被 AI 调用又打不开浏览器时返回 null
129
+ *
130
+ * @param explicitLogin 是不是 jeecg auth login:已经登录过时登录页直接显示确认租户(用来换租户);
131
+ * 打不开浏览器时也起登录页等用户。jeecg auth token 自动登录时为 false
132
+ */
133
+ async function browserLogin(host, args, timeoutMs, explicitLogin) {
134
+ const meta = await fetchMetadata(host);
135
+ if (!meta) {
136
+ throw new Error(`${host} 没有开启在线授权:后端版本太旧,或者地址不对(${HOST_EXAMPLE})`);
137
+ }
138
+ // 换 token、撤销直接用用户给的地址拼:nginx 常把外网 /jeecgboot 转发到后端 /jeecg-boot,
139
+ // 后端按请求算出来的 token_endpoint(.../jeecg-boot/oauth2/token)在外网访问不到
140
+ const endpoints = { tokenEndpoint: `${host}/oauth2/token`, revocationEndpoint: `${host}/oauth2/revoke` };
141
+ // 被 AI 调用(不在终端里)又打不开浏览器(例如 SSH 登录的服务器):AI 的命令执行完才看得到输出,
142
+ // 登录页地址等到超时也转不到用户手里,直接说明怎么做并退出
143
+ if (!explicitLogin && !process.stdin.isTTY && !hasLocalBrowser()) {
144
+ console.error(
145
+ `这台机器打不开浏览器(例如 SSH 登录的服务器),没法自动登录。请在后台执行:\n jeecg auth login --host ${host}\n` +
146
+ '它会打印登录页地址并等待 5 分钟:把地址发给用户,在用户自己电脑的浏览器里打开(VS Code、Cursor 远程会自动转发端口;' +
147
+ '普通 SSH 先在自己电脑上执行 ssh -L <端口>:127.0.0.1:<端口> <用户>@<服务器>),登录并点「授权」后,再重新执行刚才的命令'
148
+ );
149
+ process.exitCode = MANUAL_EXIT_CODE;
150
+ return null;
151
+ }
152
+ const old = store.load().hosts[host];
153
+ // 已经登录过:用已有的 token 查当前账号,登录页直接显示确认租户(页面上可以点「切换账号」重新登录)
154
+ const user = explicitLogin && old ? await currentUser(host, old) : null;
155
+ // 默认选中本机上次选的租户(后端返回的默认租户是网页上次登录的租户)
156
+ if (user && old.tenantId != null && (user.tenants || []).some((t) => t.id === old.tenantId)) {
157
+ user.tenant_id = old.tenantId;
158
+ }
159
+ const result = await pageLogin({
160
+ host,
161
+ captcha: meta.login_captcha !== false,
162
+ tokenEndpoint: endpoints.tokenEndpoint,
163
+ revocationEndpoint: endpoints.revocationEndpoint,
164
+ user,
165
+ openBrowser: args.open !== false && hasLocalBrowser(),
166
+ open: openBrowser,
167
+ remoteHint: hasLocalBrowser() ? '' : REMOTE_HINT,
168
+ timeoutMs,
169
+ });
170
+ const tenants = result.token ? result.token.tenants : user.tenants;
171
+ const tenant = (tenants || []).find((t) => t.id === result.tenantId);
172
+ const data = store.load();
173
+ if (result.token) {
174
+ // 重新登录了:之前的 refresh_token 用不上了,撤销掉(要在保存新凭证之前取出来,钥匙串里同一个地址只存一份)
175
+ const oldRefreshToken = old ? secret.unprotect(host, old.refreshToken) : null;
176
+ data.hosts[host] = toCredential(result.token, host, endpoints.tokenEndpoint, endpoints.revocationEndpoint, result.tenantId, tenant && tenant.name);
177
+ if (oldRefreshToken) {
178
+ revokeToken(old.revocationEndpoint, oldRefreshToken).catch(() => {});
179
+ }
180
+ } else {
181
+ // 沿用已有的登录,只换了租户
182
+ data.hosts[host] = { ...old, tenantId: result.tenantId, tenantName: tenant ? tenant.name : null };
183
+ }
184
+ data.defaultHost = host;
185
+ store.save(data);
186
+ return data.hosts[host];
187
+ }
188
+
189
+ /**
190
+ * CLI 已有的 token 还能用时,查当前账号和可选租户;过期、被撤销或者后端没有这个接口时返回 null(登录页显示登录表单)
191
+ */
192
+ async function currentUser(host, cred) {
193
+ if (Date.now() >= cred.expiresAt) {
194
+ return null;
195
+ }
196
+ try {
197
+ const res = await fetch(`${host}/oauth2/userinfo`, { headers: { 'X-Access-Token': cred.accessToken } });
198
+ const body = await res.json().catch(() => ({}));
199
+ return res.ok && body.success && body.result ? body.result : null;
200
+ } catch (e) {
201
+ return null;
202
+ }
203
+ }
204
+
205
+ /**
206
+ * 用 refresh_token 换新 token;登录已过期、被撤销或 refresh_token 解不开时返回 null(由调用方重新登录)
207
+ */
208
+ async function refresh(host, cred) {
209
+ const refreshToken = secret.unprotect(host, cred.refreshToken);
210
+ if (!refreshToken) {
211
+ return null;
212
+ }
213
+ try {
214
+ const t = await requestToken(cred.tokenEndpoint, { grant_type: 'refresh_token', refresh_token: refreshToken, client_id: CLIENT_ID });
215
+ const data = store.load();
216
+ // 租户是登录页上选的,只记在本机,刷新时沿用
217
+ data.hosts[host] = toCredential(t, host, cred.tokenEndpoint, cred.revocationEndpoint, cred.tenantId, cred.tenantName);
218
+ store.save(data);
219
+ return data.hosts[host];
220
+ } catch (e) {
221
+ if (e.oauthError !== 'invalid_grant') {
222
+ throw e;
223
+ }
224
+ // refresh_token 每次刷新都会换新的:两个脚本同时刷新时后到的会失败,先看看另一个进程是不是已经刷新好了
225
+ // (比 accessToken:refresh_token 存进钥匙串时记录里只有 keychain: 标记,前后一样,比不出来)
226
+ await new Promise((r) => setTimeout(r, 1000));
227
+ const latest = store.load().hosts[host];
228
+ return latest && latest.accessToken !== cred.accessToken ? latest : null;
229
+ }
230
+ }
231
+
232
+ /**
233
+ * 后端地址:--host 优先,其次上次登录的地址;都没有时在终端里提示输入(第一次使用)
234
+ */
235
+ async function resolveHost(args, allowPrompt) {
236
+ if (args.host) {
237
+ return normalizeHost(args.host);
238
+ }
239
+ const data = store.load();
240
+ if (data.defaultHost) {
241
+ return data.defaultHost;
242
+ }
243
+ if (allowPrompt && process.stdin.isTTY) {
244
+ return normalizeHost(await prompt(`请输入${HOST_EXAMPLE}:`));
245
+ }
246
+ throw new Error(`还没有登录过,请用 --host 指定${HOST_EXAMPLE}`);
247
+ }
248
+
249
+ function normalizeHost(host) {
250
+ const h = String(host || '').trim().replace(/\/+$/, '');
251
+ if (!/^https?:\/\/[^/]+/i.test(h)) {
252
+ throw new Error(`地址要以 http:// 或 https:// 开头(${HOST_EXAMPLE})`);
253
+ }
254
+ return h;
255
+ }
256
+
257
+ /**
258
+ * 读授权配置;连不上直接报错,接口不存在(老版本、地址不对)或者不支持账号密码登录时返回 null
259
+ */
260
+ async function fetchMetadata(host) {
261
+ let res;
262
+ try {
263
+ res = await fetch(`${host}/oauth2/metadata`);
264
+ } catch (e) {
265
+ throw new Error(`连不上 ${host}:${(e.cause && e.cause.code) || e.message}`);
266
+ }
267
+ // 可能是 404,也可能被 Shiro 拦成 401(Token失效),前端开发服务器还会返回 index.html
268
+ const meta = await res.json().catch(() => ({}));
269
+ return res.ok && meta.token_endpoint && (meta.grant_types_supported || []).includes('password') ? meta : null;
270
+ }
271
+
272
+ /**
273
+ * SSH 会话、没有图形界面的 Linux 打不开本机浏览器(和 claude mcp login 的判断一样)
274
+ */
275
+ function hasLocalBrowser() {
276
+ if (process.env.SSH_CONNECTION || process.env.SSH_TTY) {
277
+ return false;
278
+ }
279
+ // WSL 里一般没有图形界面,但可以打开 Windows 上的浏览器
280
+ if (isWsl()) {
281
+ return true;
282
+ }
283
+ return !(process.platform === 'linux' && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY);
284
+ }
285
+
286
+ /**
287
+ * 是否在 WSL(Windows 里的 Linux)里:Windows 上用 Claude Code 的人常在 WSL 里跑。
288
+ * 浏览器在 Windows 那边,WSL2 默认把 Windows 的 127.0.0.1 端口转发到 WSL,浏览器打开本机登录页时 CLI 能收到
289
+ */
290
+ function isWsl() {
291
+ if (process.platform !== 'linux') {
292
+ return false;
293
+ }
294
+ if (process.env.WSL_DISTRO_NAME || process.env.WSL_INTEROP) {
295
+ return true;
296
+ }
297
+ try {
298
+ return /microsoft/i.test(fs.readFileSync('/proc/version', 'utf8'));
299
+ } catch (e) {
300
+ return false;
301
+ }
302
+ }
303
+
304
+ function successText(cred) {
305
+ return `登录成功:${cred.username}${tenantText(cred.tenantId, cred.tenantName, ',租户 ')}`;
306
+ }
307
+
308
+ /** 租户显示成「十二只绵羊(1014)」,以前存的只有 id */
309
+ function tenantText(id, name, prefix) {
310
+ if (id == null) {
311
+ return '';
312
+ }
313
+ return prefix + (name ? `${name}(${id})` : id);
314
+ }
315
+
316
+ async function requestToken(endpoint, form) {
317
+ const res = await fetch(endpoint, {
318
+ method: 'POST',
319
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
320
+ body: new URLSearchParams(form),
321
+ });
322
+ const body = await res.json().catch(() => ({}));
323
+ if (!res.ok || !body.access_token) {
324
+ // OAuth 错误在 error_description 里;后端抛异常时走的是 JeecgBoot 的 Result 格式,原因在 message 里
325
+ const err = new Error(`换取 token 失败:${body.error_description || body.error || body.message || `HTTP ${res.status}`}`);
326
+ err.oauthError = body.error;
327
+ throw err;
328
+ }
329
+ return body;
330
+ }
331
+
332
+ async function revokeToken(endpoint, refreshToken) {
333
+ await fetch(endpoint, {
334
+ method: 'POST',
335
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
336
+ body: new URLSearchParams({ token: refreshToken, client_id: CLIENT_ID }),
337
+ });
338
+ }
339
+
340
+ function toCredential(t, host, tokenEndpoint, revocationEndpoint, tenantId, tenantName) {
341
+ return {
342
+ username: t.username,
343
+ // 登录页上选的租户:租户由请求头 X-Tenant-Id 决定,不绑在 token 上,只记在本机给 skill 用
344
+ tenantId: tenantId == null ? null : tenantId,
345
+ tenantName: tenantName || null,
346
+ accessToken: t.access_token,
347
+ refreshToken: secret.protect(host, t.refresh_token),
348
+ expiresAt: Date.now() + Number(t.expires_in || 0) * 1000,
349
+ tokenEndpoint,
350
+ revocationEndpoint,
351
+ };
352
+ }
353
+
354
+ function openBrowser(url) {
355
+ // Windows 不走 cmd /c start:URL 里的 & 会被 cmd 当成命令分隔符截断;WSL 里调 Windows 的 rundll32.exe,打开 Windows 上的默认浏览器
356
+ const [cmd, cmdArgs] =
357
+ process.platform === 'win32'
358
+ ? ['rundll32', ['url.dll,FileProtocolHandler', url]]
359
+ : isWsl()
360
+ ? ['rundll32.exe', ['url.dll,FileProtocolHandler', url]]
361
+ : process.platform === 'darwin'
362
+ ? ['open', [url]]
363
+ : ['xdg-open', [url]];
364
+ const tip = () => console.error('没能自动打开浏览器,请手动复制上面的链接到浏览器打开');
365
+ try {
366
+ const child = spawn(cmd, cmdArgs, { stdio: 'ignore', detached: true });
367
+ // 命令不存在(例如精简的 Linux 没装 xdg-utils)会触发 error
368
+ child.on('error', tip);
369
+ // open / xdg-open 找不到能打开链接的浏览器时不触发 error,只是退出码不为 0(xdg-open 是 3 或 4)
370
+ if (cmd === 'open' || cmd === 'xdg-open') {
371
+ child.on('exit', (code) => code && tip());
372
+ }
373
+ child.unref();
374
+ } catch (e) {
375
+ tip();
376
+ }
377
+ }
378
+
379
+ /**
380
+ * 提示打到 stderr:在 $(jeecg auth token) 里第一次使用时,stdout 会被当成 token 收走
381
+ */
382
+ function prompt(question) {
383
+ const rl = readline.createInterface({ input: process.stdin, output: process.stderr });
384
+ return new Promise((resolve) =>
385
+ rl.question(question, (answer) => {
386
+ rl.close();
387
+ resolve(answer);
388
+ })
389
+ );
390
+ }
391
+
392
+ module.exports = { login, token, status, logout };
package/lib/page.js ADDED
@@ -0,0 +1,458 @@
1
+ 'use strict';
2
+ /**
3
+ * 登录页:CLI 在本机 127.0.0.1 起一个页面,浏览器里登录、确认租户后拿到 token。
4
+ * 不依赖 vue3 前端,也不用配置前端地址;JeecgBoot、敲敲云、积木报表用的是同一套后端登录,页面统一。
5
+ *
6
+ * 页面只和本机这个服务通信,由 CLI 转给后端:
7
+ * - 验证码图片:原来的 /sys/randomImage/{key}
8
+ * - 登录:/oauth2/token(grant_type=password),返回 token 和可选租户
9
+ * - CLI 已经登录过(再次执行 jeecg auth login):/oauth2/userinfo 取当前账号,直接显示确认租户,可以点「切换账号」重新登录
10
+ *
11
+ * 防止别的网页操作这个本机服务:地址里带随机串,猜不到;提交只接受同源的 JSON 请求
12
+ */
13
+ const crypto = require('crypto');
14
+ const http = require('http');
15
+
16
+ const CLIENT_ID = 'jeecg-cli';
17
+ /** 请求体上限,登录表单用不了这么多 */
18
+ const MAX_BODY = 16 * 1024;
19
+
20
+ /**
21
+ * 起登录页,等用户在浏览器里登录并确认租户
22
+ *
23
+ * @param {object} opts
24
+ * @param {string} opts.host 后端地址,例如 http://127.0.0.1:8080/jeecg-boot
25
+ * @param {boolean} opts.captcha 登录要不要验证码(后端授权配置里的 login_captcha)
26
+ * @param {string} opts.tokenEndpoint 换 token 的地址
27
+ * @param {string} opts.revocationEndpoint 撤销授权的地址
28
+ * @param {object|null} opts.user CLI 已登录时的当前账号(username、realname、tenant_id、tenants),没有时为 null
29
+ * @param {boolean} opts.openBrowser 是否自动打开浏览器
30
+ * @param {function} opts.open 打开浏览器的方法
31
+ * @param {string} opts.remoteHint 打不开浏览器时额外打印的提示(端口转发说明),没有时为空
32
+ * @param {number} opts.timeoutMs 最多等多久
33
+ * @returns {Promise<{token: object|null, tenantId: number|null}>} token 为 null 表示沿用已有的登录,只换了租户
34
+ */
35
+ async function pageLogin(opts) {
36
+ const secret = crypto.randomBytes(16).toString('base64url');
37
+ const nonce = crypto.randomBytes(16).toString('base64');
38
+ // 登录成功、还没点「授权」的 token:点「取消」、超时或换账号重新登录时要撤销
39
+ let pending = null;
40
+ let settle;
41
+ const result = new Promise((resolve, reject) => {
42
+ settle = { resolve, reject };
43
+ });
44
+ result.catch(() => {});
45
+
46
+ const server = http.createServer((req, res) => {
47
+ handle(req, res).catch((e) => {
48
+ // 请求体太大时连接已经断开,回不了
49
+ if (!res.headersSent && !res.destroyed) {
50
+ sendJson(res, 500, { error: e.message });
51
+ }
52
+ });
53
+ });
54
+
55
+ async function handle(req, res) {
56
+ const url = new URL(req.url, 'http://127.0.0.1');
57
+ const base = `/${secret}`;
58
+ if (url.pathname !== base && !url.pathname.startsWith(base + '/')) {
59
+ res.writeHead(404, { Connection: 'close' });
60
+ res.end();
61
+ return;
62
+ }
63
+ const path = url.pathname.slice(base.length) || '/';
64
+ if (req.method === 'GET' && path === '/') {
65
+ sendHtml(res, renderPage(nonce), nonce);
66
+ return;
67
+ }
68
+ if (req.method === 'GET' && path === '/api/init') {
69
+ sendJson(res, 200, { host: opts.host, captcha: opts.captcha, user: opts.user ? pickUser(opts.user) : null });
70
+ return;
71
+ }
72
+ if (req.method === 'GET' && path === '/api/captcha') {
73
+ sendJson(res, 200, await fetchCaptcha(opts.host, url.searchParams.get('key')));
74
+ return;
75
+ }
76
+ if (req.method !== 'POST' || !isSameOrigin(req)) {
77
+ sendJson(res, 403, { error: '请求不合法' });
78
+ return;
79
+ }
80
+ const body = await readJson(req);
81
+ if (path === '/api/login') {
82
+ const t = await passwordLogin(opts, body);
83
+ if (t.error) {
84
+ sendJson(res, 200, { error: t.error });
85
+ return;
86
+ }
87
+ // 在页面上换了账号重新登录:前一个账号的 token 用不上了,撤销掉
88
+ if (pending) {
89
+ revoke(opts.revocationEndpoint, pending.refresh_token);
90
+ }
91
+ pending = t;
92
+ sendJson(res, 200, pickUser(t));
93
+ return;
94
+ }
95
+ if (path === '/api/confirm') {
96
+ const user = pending ? pickUser(pending) : opts.user ? pickUser(opts.user) : null;
97
+ if (!user) {
98
+ sendJson(res, 200, { error: '请先登录' });
99
+ return;
100
+ }
101
+ // 只认列表里的租户,页面传来的值对不上就不设
102
+ const tenant = user.tenants.find((t) => String(t.id) === String(body.tenantId));
103
+ // 响应发完(或页面已断开)再结束:结束时会断开所有连接,断早了页面收不到结果,会显示「连接已断开」
104
+ res.on('close', () => settle.resolve({ token: pending, tenantId: tenant ? tenant.id : null }));
105
+ sendJson(res, 200, { ok: true });
106
+ return;
107
+ }
108
+ if (path === '/api/cancel') {
109
+ if (pending) {
110
+ await revoke(opts.revocationEndpoint, pending.refresh_token);
111
+ pending = null;
112
+ }
113
+ res.on('close', () => settle.reject(new Error('已在浏览器中取消授权')));
114
+ sendJson(res, 200, { ok: true });
115
+ return;
116
+ }
117
+ sendJson(res, 404, { error: '不支持的请求' });
118
+ }
119
+
120
+ await new Promise((resolve, reject) => {
121
+ server.on('error', reject);
122
+ server.listen(0, '127.0.0.1', resolve);
123
+ });
124
+ const pageUrl = `http://127.0.0.1:${server.address().port}/${secret}`;
125
+ console.error(`请在浏览器中登录:\n${pageUrl}\n`);
126
+ if (opts.remoteHint) {
127
+ console.error(opts.remoteHint.replace(/\{port\}/g, server.address().port) + '\n');
128
+ }
129
+ if (opts.openBrowser) {
130
+ opts.open(pageUrl);
131
+ }
132
+
133
+ const timer = setTimeout(() => settle.reject(new Error(`等待登录超时(${Math.round(opts.timeoutMs / 1000)} 秒),请重新执行`)), opts.timeoutMs);
134
+ try {
135
+ return await result;
136
+ } catch (e) {
137
+ // 登录了但没点「授权」就超时:这个 token 不会被保存,撤销掉
138
+ if (pending) {
139
+ await revoke(opts.revocationEndpoint, pending.refresh_token);
140
+ }
141
+ throw e;
142
+ } finally {
143
+ clearTimeout(timer);
144
+ server.close();
145
+ // 浏览器会保持长连接,不断开的话进程要等几秒才退出
146
+ if (server.closeAllConnections) {
147
+ server.closeAllConnections();
148
+ }
149
+ }
150
+ }
151
+
152
+ /**
153
+ * 账号密码换 token;失败时返回 { error: 给用户看的原因 }
154
+ */
155
+ async function passwordLogin(opts, body) {
156
+ const username = String(body.username || '').trim();
157
+ const password = String(body.password || '');
158
+ if (!username || !password) {
159
+ return { error: '请输入账号和密码' };
160
+ }
161
+ const form = { grant_type: 'password', username, password, client_id: CLIENT_ID };
162
+ if (opts.captcha) {
163
+ form.captcha = String(body.captcha || '').trim();
164
+ form.check_key = String(body.checkKey || '');
165
+ }
166
+ let res;
167
+ try {
168
+ res = await fetch(opts.tokenEndpoint, {
169
+ method: 'POST',
170
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
171
+ body: new URLSearchParams(form),
172
+ });
173
+ } catch (e) {
174
+ return { error: `连不上 ${opts.host}:${(e.cause && e.cause.code) || e.message}` };
175
+ }
176
+ const t = await res.json().catch(() => ({}));
177
+ if (!res.ok || !t.access_token) {
178
+ return { error: t.error_description || t.message || `登录失败(HTTP ${res.status})` };
179
+ }
180
+ return t;
181
+ }
182
+
183
+ /**
184
+ * 取验证码图片:原来的 /sys/randomImage/{key},返回 data:image/...;base64 开头的图片
185
+ */
186
+ async function fetchCaptcha(host, key) {
187
+ if (!/^[A-Za-z0-9]{1,64}$/.test(key || '')) {
188
+ return { error: '验证码参数不对' };
189
+ }
190
+ try {
191
+ const res = await fetch(`${host}/sys/randomImage/${key}`);
192
+ const body = await res.json().catch(() => ({}));
193
+ const image = body.result;
194
+ return typeof image === 'string' && image.startsWith('data:image/') ? { image } : { error: body.message || '获取验证码失败' };
195
+ } catch (e) {
196
+ return { error: `连不上 ${host}` };
197
+ }
198
+ }
199
+
200
+ /**
201
+ * 撤销 refresh_token(对应的 access_token 一起作废),失败不影响主流程
202
+ */
203
+ async function revoke(endpoint, refreshToken) {
204
+ try {
205
+ await fetch(endpoint, {
206
+ method: 'POST',
207
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
208
+ body: new URLSearchParams({ token: refreshToken, client_id: CLIENT_ID }),
209
+ });
210
+ } catch (e) {
211
+ // 撤销不了就让它自然过期
212
+ }
213
+ }
214
+
215
+ /** 页面只需要账号和租户,不把 token 交给页面 */
216
+ function pickUser(u) {
217
+ return { username: u.username, realname: u.realname || u.username, tenantId: u.tenant_id == null ? null : u.tenant_id, tenants: Array.isArray(u.tenants) ? u.tenants : [] };
218
+ }
219
+
220
+ /**
221
+ * 只接受页面自己发的请求:别的网站跨域提交时 Origin 是它自己的域名。
222
+ * 不限定 Host:VS Code 远程等端口转发后,浏览器里的地址可能换了端口或域名
223
+ */
224
+ function isSameOrigin(req) {
225
+ if (!String(req.headers['content-type'] || '').startsWith('application/json')) {
226
+ return false;
227
+ }
228
+ const origin = req.headers.origin;
229
+ return !origin || origin === `http://${req.headers.host}` || origin === `https://${req.headers.host}`;
230
+ }
231
+
232
+ function readJson(req) {
233
+ return new Promise((resolve, reject) => {
234
+ let size = 0;
235
+ const chunks = [];
236
+ req.on('data', (c) => {
237
+ size += c.length;
238
+ if (size > MAX_BODY) {
239
+ reject(new Error('请求太大'));
240
+ req.destroy();
241
+ return;
242
+ }
243
+ chunks.push(c);
244
+ });
245
+ req.on('end', () => {
246
+ try {
247
+ resolve(JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}'));
248
+ } catch (e) {
249
+ resolve({});
250
+ }
251
+ });
252
+ req.on('error', reject);
253
+ });
254
+ }
255
+
256
+ function sendJson(res, status, data) {
257
+ res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store', Connection: 'close' });
258
+ res.end(JSON.stringify(data));
259
+ }
260
+
261
+ function sendHtml(res, html, nonce) {
262
+ res.writeHead(200, {
263
+ 'Content-Type': 'text/html; charset=utf-8',
264
+ 'Cache-Control': 'no-store',
265
+ 'X-Frame-Options': 'DENY',
266
+ 'Referrer-Policy': 'no-referrer',
267
+ // 页面脚本只允许带 nonce 的那一段;不能被嵌进别的网页(防止诱导点「授权」)
268
+ 'Content-Security-Policy': `default-src 'none'; script-src 'nonce-${nonce}'; style-src 'unsafe-inline'; img-src data:; connect-src 'self'; form-action 'none'; frame-ancestors 'none'; base-uri 'none'`,
269
+ Connection: 'close',
270
+ });
271
+ res.end(html);
272
+ }
273
+
274
+ /**
275
+ * 登录页:登录 → 确认租户 → 结果,三步在同一个页面里切换
276
+ */
277
+ function renderPage(nonce) {
278
+ return `<!DOCTYPE html>
279
+ <html lang="zh-CN">
280
+ <head>
281
+ <meta charset="UTF-8">
282
+ <meta name="viewport" content="width=device-width, initial-scale=1">
283
+ <title>授权登录 - AI Skills</title>
284
+ <style>
285
+ * { box-sizing: border-box; }
286
+ body { margin: 0; min-height: 100vh; display: flex; align-items: center; justify-content: center; background: #f2f4f7;
287
+ font: 14px/1.5 -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif; color: #1f2329; }
288
+ .card { width: 420px; max-width: calc(100vw - 32px); background: #fff; border-radius: 12px; box-shadow: 0 8px 32px rgba(31, 35, 41, .08); padding: 32px 36px 28px; }
289
+ .brand { display: flex; align-items: center; gap: 12px; padding-bottom: 20px; margin-bottom: 24px; border-bottom: 1px solid #eef0f3; }
290
+ .logo { width: 40px; height: 40px; border-radius: 10px; background: linear-gradient(135deg, #3b82f6, #1d4ed8); color: #fff;
291
+ display: flex; align-items: center; justify-content: center; font-size: 18px; font-weight: 700; flex-shrink: 0; }
292
+ .brand-name { font-size: 16px; font-weight: 600; }
293
+ .muted { font-size: 12px; color: #8f959e; word-break: break-all; }
294
+ h1 { font-size: 20px; margin: 0 0 6px; }
295
+ .sub { color: #646a73; margin: 0 0 22px; }
296
+ .field { display: block; margin-bottom: 16px; }
297
+ .field > span { display: block; margin-bottom: 6px; color: #646a73; font-size: 13px; }
298
+ input, select { width: 100%; height: 40px; padding: 0 12px; border: 1px solid #d5d8dc; border-radius: 8px; font-size: 14px; outline: none; background: #fff; color: inherit; }
299
+ input:focus, select:focus { border-color: #3b82f6; box-shadow: 0 0 0 3px rgba(59, 130, 246, .15); }
300
+ .captcha { display: flex; gap: 10px; }
301
+ .captcha img { height: 40px; width: 120px; border: 1px solid #d5d8dc; border-radius: 8px; cursor: pointer; flex-shrink: 0; }
302
+ .btn { width: 100%; height: 42px; border: 0; border-radius: 8px; background: #2563eb; color: #fff; font-size: 15px; cursor: pointer; }
303
+ .btn:hover { background: #1d4ed8; }
304
+ .btn:disabled { opacity: .6; cursor: default; }
305
+ .btn.ghost { background: #fff; color: #1f2329; border: 1px solid #d5d8dc; }
306
+ .btn.ghost:hover { background: #f5f6f7; }
307
+ .actions { display: flex; gap: 12px; margin-top: 24px; }
308
+ .error { color: #e5484d; min-height: 20px; margin: -4px 0 12px; font-size: 13px; }
309
+ .account { display: flex; align-items: center; gap: 12px; padding: 12px 14px; background: #f7f8fa; border-radius: 10px; margin-bottom: 18px; }
310
+ .avatar { width: 40px; height: 40px; border-radius: 50%; background: #dbeafe; color: #1d4ed8; display: flex; align-items: center; justify-content: center; font-weight: 600; flex-shrink: 0; }
311
+ .account-name { font-weight: 600; }
312
+ .switch { margin-left: auto; color: #2563eb; cursor: pointer; font-size: 13px; background: none; border: 0; padding: 0; }
313
+ .perm { margin: 0; padding: 0; list-style: none; color: #646a73; }
314
+ .perm li { position: relative; padding-left: 20px; margin-bottom: 6px; }
315
+ .perm li::before { content: ""; position: absolute; left: 4px; top: 8px; width: 6px; height: 6px; border-radius: 50%; background: #3b82f6; }
316
+ .result { text-align: center; padding: 8px 0 4px; }
317
+ .result-icon { width: 56px; height: 56px; margin: 0 auto 14px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 28px; color: #fff; background: #22c55e; }
318
+ .result-icon.cancel { background: #9ca3af; }
319
+ .hidden { display: none !important; }
320
+ </style>
321
+ </head>
322
+ <body>
323
+ <div class="card">
324
+ <div class="brand">
325
+ <div class="logo">J</div>
326
+ <div><div class="brand-name">JeecgBoot / 敲敲云 / 积木报表</div><div class="muted" id="host"></div></div>
327
+ </div>
328
+
329
+ <form id="login" class="hidden" autocomplete="on">
330
+ <h1>登录</h1>
331
+ <p class="sub">登录后授权 AI Skills 以你的身份调用接口</p>
332
+ <label class="field"><span>账号</span><input name="username" autocomplete="username" required></label>
333
+ <label class="field"><span>密码</span><input name="password" type="password" autocomplete="current-password" required></label>
334
+ <div class="field hidden" id="captchaRow">
335
+ <span>验证码</span>
336
+ <div class="captcha"><input name="captcha" autocomplete="off" maxlength="8"><img id="captchaImg" alt="验证码" title="看不清?点击换一张"></div>
337
+ </div>
338
+ <div class="error" id="loginError"></div>
339
+ <button class="btn" type="submit">登录</button>
340
+ </form>
341
+
342
+ <div id="confirm" class="hidden">
343
+ <h1>授权 AI Skills</h1>
344
+ <p class="sub">AI Skills 申请以你的身份访问 <span id="host2"></span></p>
345
+ <div class="account">
346
+ <div class="avatar" id="avatar"></div>
347
+ <div><div class="account-name" id="realname"></div><div class="muted" id="username"></div></div>
348
+ <button class="switch" id="switch" type="button">切换账号</button>
349
+ </div>
350
+ <label class="field" id="tenantRow"><span>租户</span><select id="tenant"></select></label>
351
+ <ul class="perm">
352
+ <li>以你的身份调用系统接口,生成报表、表单、流程等</li>
353
+ <li>实际权限不会超过你在系统中的权限</li>
354
+ </ul>
355
+ <div class="error" id="confirmError"></div>
356
+ <div class="actions">
357
+ <button class="btn ghost" id="cancel" type="button">取消</button>
358
+ <button class="btn" id="approve" type="button">授权</button>
359
+ </div>
360
+ </div>
361
+
362
+ <div id="done" class="hidden result">
363
+ <div class="result-icon" id="doneIcon">✓</div>
364
+ <h1 id="doneTitle"></h1>
365
+ <p class="sub" id="doneText"></p>
366
+ </div>
367
+ </div>
368
+ <script nonce="${nonce}">
369
+ var base = location.pathname.replace(/\\/$/, '');
370
+ var state = null;
371
+ var checkKey = '';
372
+ function $(id) { return document.getElementById(id); }
373
+ function show(id) { ['login', 'confirm', 'done'].forEach(function (v) { $(v).classList.toggle('hidden', v !== id); }); }
374
+ function api(path, body) {
375
+ var init = body === undefined ? {} : { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) };
376
+ return fetch(base + '/api/' + path, init).then(function (r) { return r.json(); });
377
+ }
378
+ function lost() { showDone(false, '连接已断开', '登录程序已经退出,请重新发起登录。'); }
379
+ function showDone(ok, title, text) {
380
+ $('doneIcon').textContent = ok ? '✓' : '×';
381
+ $('doneIcon').classList.toggle('cancel', !ok);
382
+ $('doneTitle').textContent = title;
383
+ $('doneText').textContent = text;
384
+ show('done');
385
+ }
386
+ function refreshCaptcha() {
387
+ if (!state.captcha) { return; }
388
+ checkKey = Date.now() + '' + Math.floor(Math.random() * 1000);
389
+ api('captcha?key=' + checkKey).then(function (r) {
390
+ if (r.image) { $('captchaImg').src = r.image; } else { $('loginError').textContent = r.error || '获取验证码失败'; }
391
+ }).catch(lost);
392
+ }
393
+ function showLogin() {
394
+ show('login');
395
+ $('loginError').textContent = '';
396
+ refreshCaptcha();
397
+ document.forms.login.username.focus();
398
+ }
399
+ function showConfirm(user) {
400
+ $('realname').textContent = user.realname;
401
+ $('username').textContent = user.username;
402
+ $('avatar').textContent = (user.realname || '?').slice(0, 1);
403
+ var select = $('tenant');
404
+ select.innerHTML = '';
405
+ user.tenants.forEach(function (t) {
406
+ var option = document.createElement('option');
407
+ option.value = t.id;
408
+ option.textContent = t.name;
409
+ option.selected = String(t.id) === String(user.tenantId);
410
+ select.appendChild(option);
411
+ });
412
+ $('tenantRow').classList.toggle('hidden', user.tenants.length === 0);
413
+ $('confirmError').textContent = '';
414
+ show('confirm');
415
+ }
416
+ document.forms.login.addEventListener('submit', function (e) {
417
+ e.preventDefault();
418
+ var form = e.target;
419
+ var button = form.querySelector('button');
420
+ button.disabled = true;
421
+ $('loginError').textContent = '';
422
+ api('login', { username: form.username.value, password: form.password.value, captcha: form.captcha.value, checkKey: checkKey }).then(function (r) {
423
+ if (r.error) {
424
+ $('loginError').textContent = r.error;
425
+ form.captcha.value = '';
426
+ refreshCaptcha();
427
+ return;
428
+ }
429
+ form.password.value = '';
430
+ form.captcha.value = '';
431
+ showConfirm(r);
432
+ }).catch(lost).then(function () { button.disabled = false; });
433
+ });
434
+ $('captchaImg').addEventListener('click', refreshCaptcha);
435
+ $('switch').addEventListener('click', showLogin);
436
+ $('approve').addEventListener('click', function () {
437
+ $('approve').disabled = true;
438
+ api('confirm', { tenantId: $('tenant').value }).then(function (r) {
439
+ if (r.error) { $('confirmError').textContent = r.error; return; }
440
+ showDone(true, '授权成功', '可以关闭此页面,回到终端继续使用。');
441
+ }).catch(lost).then(function () { $('approve').disabled = false; });
442
+ });
443
+ $('cancel').addEventListener('click', function () {
444
+ api('cancel', {}).then(function () { showDone(false, '已取消授权', '可以关闭此页面。'); }).catch(lost);
445
+ });
446
+ api('init').then(function (r) {
447
+ state = r;
448
+ $('host').textContent = r.host;
449
+ $('host2').textContent = r.host;
450
+ $('captchaRow').classList.toggle('hidden', !r.captcha);
451
+ if (r.user) { showConfirm(r.user); } else { showLogin(); }
452
+ }).catch(lost);
453
+ </script>
454
+ </body>
455
+ </html>`;
456
+ }
457
+
458
+ module.exports = { pageLogin };
package/lib/secret.js ADDED
@@ -0,0 +1,99 @@
1
+ 'use strict';
2
+ /**
3
+ * refresh_token 加密存储:它 30 天有效、能换出新 token,是本机凭证里最要紧的。
4
+ * access_token 有效期短,而且每次 jeecg auth token 都要读,保持原样,取 token 不变慢。
5
+ *
6
+ * - Windows:DPAPI,系统自带,密文和当前 Windows 账号绑定(拷到别的电脑或账号解不开);通过 PowerShell 调用,一次约 0.35 秒
7
+ * - macOS:系统钥匙串(security 命令);钥匙串锁着时(例如 SSH 登录)退回明文
8
+ * - Linux:有 secret-tool 就存进系统密钥环;没有(服务器上常见)或调用失败,就退回明文(文件权限 600)并提示
9
+ * - WSL、Docker 容器等其它 Linux 环境同上,一般没有密钥环,走明文
10
+ *
11
+ * credentials.json 里存的值带前缀说明存在哪:dpapi:<密文> / keychain: / secret-tool: ;没有前缀的是明文(以前存的或退回明文的)
12
+ */
13
+ const { execFileSync } = require('child_process');
14
+
15
+ const SERVICE = 'jeecg-cli';
16
+ // 调系统命令最多等 30 秒:Linux 密钥环被锁时会弹窗等用户输密码,等不到就退回明文,不让命令一直卡着
17
+ const TIMEOUT_MS = 30 * 1000;
18
+ // 明文和密文都从环境变量传给 PowerShell,不出现在进程命令行里
19
+ const PROTECT_PS =
20
+ "Add-Type -AssemblyName System.Security;[Convert]::ToBase64String([Security.Cryptography.ProtectedData]::Protect([Text.Encoding]::UTF8.GetBytes($env:JEECG_SECRET),$null,'CurrentUser'))";
21
+ const UNPROTECT_PS =
22
+ "Add-Type -AssemblyName System.Security;[Text.Encoding]::UTF8.GetString([Security.Cryptography.ProtectedData]::Unprotect([Convert]::FromBase64String($env:JEECG_SECRET),$null,'CurrentUser'))";
23
+
24
+ function protect(host, secret) {
25
+ if (!secret) {
26
+ return secret;
27
+ }
28
+ try {
29
+ if (process.platform === 'win32') {
30
+ return 'dpapi:' + powershell(PROTECT_PS, secret);
31
+ }
32
+ // 存完读回来比对一次:security -i 里的命令失败时退出码也可能是 0(例如 SSH 登录的 Mac 钥匙串是锁着的),
33
+ // 不比对的话会以为存进去了,之后读不出来,每次 token 过期都要重新授权
34
+ const stored = process.platform === 'darwin' ? 'keychain:' : 'secret-tool:';
35
+ if (process.platform === 'darwin') {
36
+ // security -i 从标准输入读命令,密钥不出现在进程命令行里
37
+ execFileSync('security', ['-i'], { input: `add-generic-password -U -a "${host}" -s "${SERVICE}" -w "${secret}"\n`, stdio: ['pipe', 'ignore', 'pipe'], timeout: TIMEOUT_MS });
38
+ } else {
39
+ execFileSync('secret-tool', ['store', `--label=jeecg CLI ${host}`, 'service', SERVICE, 'account', host], { input: secret, stdio: ['pipe', 'ignore', 'pipe'], timeout: TIMEOUT_MS });
40
+ }
41
+ if (unprotect(host, stored) !== secret) {
42
+ throw new Error('写入后读不出来');
43
+ }
44
+ return stored;
45
+ } catch (e) {
46
+ console.error(`提示:本机没有可用的系统密钥存储(${e.code || e.message}),refresh_token 以明文保存在 ~/.jeecg/credentials.json(文件权限 600)`);
47
+ return secret;
48
+ }
49
+ }
50
+
51
+ /**
52
+ * 取回明文;解不开(换了电脑或账号、钥匙串里被删了)返回 null,调用方按「没有 refresh_token」处理,重新授权
53
+ */
54
+ function unprotect(host, stored) {
55
+ if (!stored) {
56
+ return null;
57
+ }
58
+ try {
59
+ if (stored.startsWith('dpapi:')) {
60
+ return powershell(UNPROTECT_PS, stored.slice('dpapi:'.length));
61
+ }
62
+ if (stored === 'keychain:') {
63
+ return execFileSync('security', ['find-generic-password', '-a', host, '-s', SERVICE, '-w'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: TIMEOUT_MS }).trim();
64
+ }
65
+ if (stored === 'secret-tool:') {
66
+ return execFileSync('secret-tool', ['lookup', 'service', SERVICE, 'account', host], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: TIMEOUT_MS }).trim();
67
+ }
68
+ } catch (e) {
69
+ return null;
70
+ }
71
+ return stored;
72
+ }
73
+
74
+ /**
75
+ * 退出时把钥匙串 / 密钥环里的那份也删掉(DPAPI 和明文都在 credentials.json 里,删记录就没了)
76
+ */
77
+ function remove(host, stored) {
78
+ try {
79
+ if (stored === 'keychain:') {
80
+ execFileSync('security', ['delete-generic-password', '-a', host, '-s', SERVICE], { stdio: 'ignore', timeout: TIMEOUT_MS });
81
+ } else if (stored === 'secret-tool:') {
82
+ execFileSync('secret-tool', ['clear', 'service', SERVICE, 'account', host], { stdio: 'ignore', timeout: TIMEOUT_MS });
83
+ }
84
+ } catch (e) {
85
+ // 本来就没有,不用处理
86
+ }
87
+ }
88
+
89
+ function powershell(script, input) {
90
+ return execFileSync('powershell', ['-NoProfile', '-NonInteractive', '-Command', script], {
91
+ env: { ...process.env, JEECG_SECRET: input },
92
+ encoding: 'utf8',
93
+ windowsHide: true,
94
+ stdio: ['ignore', 'pipe', 'pipe'],
95
+ timeout: TIMEOUT_MS,
96
+ }).trim();
97
+ }
98
+
99
+ module.exports = { protect, unprotect, remove };
package/lib/store.js ADDED
@@ -0,0 +1,29 @@
1
+ 'use strict';
2
+ /**
3
+ * 本机凭证:按地址存在 ~/.jeecg/credentials.json(文件权限 600)
4
+ * 结构:{ defaultHost, hosts: { "<地址>": { username, tenantId, tenantName, accessToken, refreshToken, expiresAt, ... } } }
5
+ */
6
+ const fs = require('fs');
7
+ const os = require('os');
8
+ const path = require('path');
9
+
10
+ const DIR = path.join(os.homedir(), '.jeecg');
11
+ const FILE = path.join(DIR, 'credentials.json');
12
+
13
+ function load() {
14
+ try {
15
+ const data = JSON.parse(fs.readFileSync(FILE, 'utf8'));
16
+ return { defaultHost: data.defaultHost || null, hosts: data.hosts || {} };
17
+ } catch (e) {
18
+ return { defaultHost: null, hosts: {} };
19
+ }
20
+ }
21
+
22
+ function save(data) {
23
+ fs.mkdirSync(DIR, { recursive: true, mode: 0o700 });
24
+ fs.writeFileSync(FILE, JSON.stringify(data, null, 2), { mode: 0o600 });
25
+ // 文件已存在时 writeFileSync 不会改权限,这里再收紧一次(Windows 上由用户目录的 ACL 保护)
26
+ fs.chmodSync(FILE, 0o600);
27
+ }
28
+
29
+ module.exports = { load, save, FILE };
package/package.json CHANGED
@@ -1,6 +1,20 @@
1
1
  {
2
2
  "name": "@jeecg/cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "JEECG 命令行工具:在浏览器里登录 JeecgBoot / 敲敲云,给 AI skills 提供 token",
5
+ "publishConfig": {
6
+ "registry": "https://registry.npmjs.org",
7
+ "access": "public"
8
+ },
9
+ "bin": {
10
+ "jeecg": "bin/jeecg.js"
11
+ },
12
+ "files": [
13
+ "bin",
14
+ "lib",
15
+ "README.md"
16
+ ],
17
+ "engines": {
18
+ "node": ">=18"
19
+ }
20
+ }