haoyuan 0.0.3 → 0.0.5
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/api/configs/configs.py +1 -1
- package/api/plugins/user-account/plugin.py +40 -0
- package/bin/haoyuan.js +92 -7
- package/package.json +1 -1
- package/web/package-lock.json +2 -2
- package/web/package.json +1 -1
package/api/configs/configs.py
CHANGED
|
@@ -6,7 +6,7 @@ from pathlib import Path
|
|
|
6
6
|
from configs.models import auto_default
|
|
7
7
|
|
|
8
8
|
APP_NAME = "HaoYuan"
|
|
9
|
-
APP_VERSION = "0.0.
|
|
9
|
+
APP_VERSION = "0.0.5"
|
|
10
10
|
SERVER_HOST = os.getenv("HAOYUAN_HOST", "127.0.0.1")
|
|
11
11
|
SERVER_PORT = int(os.getenv("HAOYUAN_PORT", "8030"))
|
|
12
12
|
prefix = "/api"
|
|
@@ -4,6 +4,7 @@ import base64
|
|
|
4
4
|
import hashlib
|
|
5
5
|
import hmac
|
|
6
6
|
import json
|
|
7
|
+
import os
|
|
7
8
|
import secrets
|
|
8
9
|
import threading
|
|
9
10
|
import time
|
|
@@ -25,6 +26,38 @@ DEFAULT_MAX_FAILURES = 5
|
|
|
25
26
|
MAX_FAILURES_LIMIT = 20
|
|
26
27
|
LOCK_SECONDS = 5 * 60
|
|
27
28
|
STATE_PATH = DATA_DIR / "user_account.json"
|
|
29
|
+
CLI_SECRET_PATH = DATA_DIR / "cli-secret"
|
|
30
|
+
|
|
31
|
+
_cli_secret_value: str | None = None
|
|
32
|
+
_cli_secret_lock = threading.Lock()
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def cli_secret() -> str:
|
|
36
|
+
"""本机 CLI 的免登录密钥:只写入本地数据目录,由同机 `haoyuan` 读取后随请求发送。"""
|
|
37
|
+
global _cli_secret_value
|
|
38
|
+
if _cli_secret_value is not None:
|
|
39
|
+
return _cli_secret_value
|
|
40
|
+
with _cli_secret_lock:
|
|
41
|
+
if _cli_secret_value is not None:
|
|
42
|
+
return _cli_secret_value
|
|
43
|
+
try:
|
|
44
|
+
value = ""
|
|
45
|
+
if CLI_SECRET_PATH.is_file():
|
|
46
|
+
value = CLI_SECRET_PATH.read_text(encoding="utf-8").strip()
|
|
47
|
+
if not value:
|
|
48
|
+
value = secrets.token_hex(32)
|
|
49
|
+
CLI_SECRET_PATH.parent.mkdir(parents=True, exist_ok=True)
|
|
50
|
+
temp = CLI_SECRET_PATH.with_suffix(".tmp")
|
|
51
|
+
temp.write_text(value, encoding="utf-8")
|
|
52
|
+
temp.replace(CLI_SECRET_PATH)
|
|
53
|
+
try:
|
|
54
|
+
os.chmod(CLI_SECRET_PATH, 0o600)
|
|
55
|
+
except OSError:
|
|
56
|
+
pass
|
|
57
|
+
_cli_secret_value = value
|
|
58
|
+
except OSError:
|
|
59
|
+
_cli_secret_value = ""
|
|
60
|
+
return _cli_secret_value
|
|
28
61
|
|
|
29
62
|
|
|
30
63
|
def _now() -> str:
|
|
@@ -261,6 +294,8 @@ class AuthGateMiddleware:
|
|
|
261
294
|
def __init__(self, app, state_path: str):
|
|
262
295
|
self.app = app
|
|
263
296
|
self.store = AuthStore(Path(state_path))
|
|
297
|
+
# 启动时即生成本机 CLI 免登录密钥,避免 CLI 首个请求早于文件生成
|
|
298
|
+
cli_secret()
|
|
264
299
|
|
|
265
300
|
async def __call__(self, scope, receive, send):
|
|
266
301
|
if scope["type"] not in {"http", "websocket"}:
|
|
@@ -278,6 +313,10 @@ class AuthGateMiddleware:
|
|
|
278
313
|
for key, value in scope.get("headers", [])
|
|
279
314
|
}
|
|
280
315
|
query = parse_qs(scope.get("query_string", b"").decode("latin-1"))
|
|
316
|
+
cli = headers.get("x-haoyuan-cli-secret", "").strip()
|
|
317
|
+
expected = cli_secret()
|
|
318
|
+
if cli and expected and hmac.compare_digest(cli, expected):
|
|
319
|
+
return await self.app(scope, receive, send)
|
|
281
320
|
token = _token_from_headers(headers, query)
|
|
282
321
|
if token and self.store.verify_token(token):
|
|
283
322
|
return await self.app(scope, receive, send)
|
|
@@ -533,6 +572,7 @@ def build_router(store: AuthStore) -> APIRouter:
|
|
|
533
572
|
def register(ctx) -> None:
|
|
534
573
|
store = AuthStore(STATE_PATH)
|
|
535
574
|
store.ensure()
|
|
575
|
+
cli_secret()
|
|
536
576
|
ctx.add_router(build_router(store))
|
|
537
577
|
ctx.add_middleware(AuthGateMiddleware, state_path=str(STATE_PATH))
|
|
538
578
|
|
package/bin/haoyuan.js
CHANGED
|
@@ -26,6 +26,7 @@ const API = path.join(ROOT, "api");
|
|
|
26
26
|
const RUNTIME_FILE = path.join(API, "data", "runtime.json");
|
|
27
27
|
const DIST_INDEX = path.join(WEB, "dist", "index.html");
|
|
28
28
|
const TOKEN_FILE = path.join(API, "data", "cli-token");
|
|
29
|
+
const CLI_SECRET_FILE = path.join(API, "data", "cli-secret");
|
|
29
30
|
let TOKEN = (process.env.HAOYUAN_TOKEN || "").trim();
|
|
30
31
|
if (!TOKEN) {
|
|
31
32
|
try {
|
|
@@ -55,6 +56,14 @@ function clearToken() {
|
|
|
55
56
|
}
|
|
56
57
|
}
|
|
57
58
|
|
|
59
|
+
function cliSecret() {
|
|
60
|
+
try {
|
|
61
|
+
return fs.readFileSync(CLI_SECRET_FILE, "utf8").trim();
|
|
62
|
+
} catch {
|
|
63
|
+
return "";
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
58
67
|
const COLOR = process.stdout.isTTY && !process.env.NO_COLOR;
|
|
59
68
|
const C = COLOR
|
|
60
69
|
? {
|
|
@@ -90,11 +99,9 @@ function run(cmd, args, opts = {}) {
|
|
|
90
99
|
const lenient = opts.lenient === true;
|
|
91
100
|
const useShell = IS_WIN && /\.(cmd|bat)$/i.test(cmd);
|
|
92
101
|
log(`${cmd} ${args.join(" ")}`);
|
|
93
|
-
const r =
|
|
94
|
-
cmd,
|
|
95
|
-
|
|
96
|
-
{ stdio: "inherit", cwd: ROOT, shell: useShell }
|
|
97
|
-
);
|
|
102
|
+
const r = useShell
|
|
103
|
+
? spawnSync([cmd, ...args.map(shellQuote)].join(" "), { stdio: "inherit", cwd: ROOT, shell: true })
|
|
104
|
+
: spawnSync(cmd, args, { stdio: "inherit", cwd: ROOT });
|
|
98
105
|
if (r.error) {
|
|
99
106
|
if (lenient) {
|
|
100
107
|
warn(`跳过(${r.error.message})`);
|
|
@@ -369,6 +376,8 @@ async function ensureServer() {
|
|
|
369
376
|
|
|
370
377
|
function apiHeaders() {
|
|
371
378
|
const headers = { "content-type": "application/json" };
|
|
379
|
+
const secret = cliSecret();
|
|
380
|
+
if (secret) headers["x-haoyuan-cli-secret"] = secret;
|
|
372
381
|
if (TOKEN) {
|
|
373
382
|
headers["authorization"] = `Bearer ${TOKEN}`;
|
|
374
383
|
headers["x-haoyuan-token"] = TOKEN;
|
|
@@ -626,6 +635,8 @@ async function chat(options = {}) {
|
|
|
626
635
|
if (state.streamReq || state.closing) return;
|
|
627
636
|
const qs = `after_id=${state.lastEventId}${TOKEN ? `&token=${encodeURIComponent(TOKEN)}` : ""}`;
|
|
628
637
|
const headers = { Accept: "text/event-stream" };
|
|
638
|
+
const secret = cliSecret();
|
|
639
|
+
if (secret) headers["x-haoyuan-cli-secret"] = secret;
|
|
629
640
|
if (TOKEN) headers["x-haoyuan-token"] = TOKEN;
|
|
630
641
|
const req = http.get(
|
|
631
642
|
{
|
|
@@ -704,7 +715,7 @@ async function chat(options = {}) {
|
|
|
704
715
|
state.inReasoning = false;
|
|
705
716
|
}
|
|
706
717
|
if (!state.inText) {
|
|
707
|
-
process.stdout.write(`${C.bold}[
|
|
718
|
+
process.stdout.write(`${C.bold}[HaoYuan]${C.reset} `);
|
|
708
719
|
state.inText = true;
|
|
709
720
|
}
|
|
710
721
|
if (payload.text) process.stdout.write(payload.text);
|
|
@@ -763,7 +774,7 @@ async function chat(options = {}) {
|
|
|
763
774
|
|
|
764
775
|
if (type === "done") {
|
|
765
776
|
if (!state.inText && payload.text) {
|
|
766
|
-
process.stdout.write(`${C.bold}[
|
|
777
|
+
process.stdout.write(`${C.bold}[HaoYuan]${C.reset} ${payload.text}\n`);
|
|
767
778
|
}
|
|
768
779
|
endLine();
|
|
769
780
|
if (state.busy) {
|
|
@@ -1070,6 +1081,75 @@ function printVersion() {
|
|
|
1070
1081
|
process.stdout.write(`${VERSION}\n`);
|
|
1071
1082
|
}
|
|
1072
1083
|
|
|
1084
|
+
function npmRegistryArgs() {
|
|
1085
|
+
const registry = (process.env.HAOYUAN_NPM_REGISTRY || "").trim();
|
|
1086
|
+
return registry ? ["--registry", registry] : [];
|
|
1087
|
+
}
|
|
1088
|
+
|
|
1089
|
+
function parseVersion(value) {
|
|
1090
|
+
return String(value || "")
|
|
1091
|
+
.trim()
|
|
1092
|
+
.replace(/^v/i, "")
|
|
1093
|
+
.split("-")[0]
|
|
1094
|
+
.split(".")
|
|
1095
|
+
.map((part) => {
|
|
1096
|
+
const n = Number.parseInt(part, 10);
|
|
1097
|
+
return Number.isFinite(n) ? n : 0;
|
|
1098
|
+
});
|
|
1099
|
+
}
|
|
1100
|
+
|
|
1101
|
+
function compareVersions(a, b) {
|
|
1102
|
+
const pa = parseVersion(a);
|
|
1103
|
+
const pb = parseVersion(b);
|
|
1104
|
+
const len = Math.max(pa.length, pb.length);
|
|
1105
|
+
for (let i = 0; i < len; i += 1) {
|
|
1106
|
+
const x = pa[i] || 0;
|
|
1107
|
+
const y = pb[i] || 0;
|
|
1108
|
+
if (x !== y) return x < y ? -1 : 1;
|
|
1109
|
+
}
|
|
1110
|
+
return 0;
|
|
1111
|
+
}
|
|
1112
|
+
|
|
1113
|
+
function npmCapture(args) {
|
|
1114
|
+
const full = [...args, ...npmRegistryArgs()];
|
|
1115
|
+
const useShell = IS_WIN && /\.(cmd|bat)$/i.test(NPM);
|
|
1116
|
+
const r = useShell
|
|
1117
|
+
? spawnSync([NPM, ...full.map(shellQuote)].join(" "), { cwd: ROOT, encoding: "utf8", shell: true })
|
|
1118
|
+
: spawnSync(NPM, full, { cwd: ROOT, encoding: "utf8" });
|
|
1119
|
+
if (r.error) return { ok: false, error: r.error.message };
|
|
1120
|
+
if (r.status !== 0) {
|
|
1121
|
+
const detail = (r.stderr || r.stdout || "").trim();
|
|
1122
|
+
return { ok: false, error: detail || `npm 退出码 ${r.status}` };
|
|
1123
|
+
}
|
|
1124
|
+
return { ok: true, out: (r.stdout || "").trim() };
|
|
1125
|
+
}
|
|
1126
|
+
|
|
1127
|
+
async function upgradeCommand() {
|
|
1128
|
+
log(`当前版本 v${VERSION}`);
|
|
1129
|
+
log("检查 npm 最新版本 ...");
|
|
1130
|
+
const result = npmCapture(["view", "haoyuan", "version"]);
|
|
1131
|
+
if (!result.ok) {
|
|
1132
|
+
fail(`检查最新版本失败: ${result.error}(可用 HAOYUAN_NPM_REGISTRY 指定 npm 源)`);
|
|
1133
|
+
}
|
|
1134
|
+
const latest = (result.out || "").split(/\s+/).filter(Boolean).pop() || "";
|
|
1135
|
+
if (!/^\d+\.\d+\.\d+/.test(latest)) {
|
|
1136
|
+
fail(`无法解析最新版本号: ${result.out || "(空)"}`);
|
|
1137
|
+
}
|
|
1138
|
+
log(`最新版本 v${latest}`);
|
|
1139
|
+
if (compareVersions(VERSION, latest) >= 0) {
|
|
1140
|
+
log("已是最新版本,无需升级。");
|
|
1141
|
+
return;
|
|
1142
|
+
}
|
|
1143
|
+
|
|
1144
|
+
log(`开始升级 v${VERSION} → v${latest} ...`);
|
|
1145
|
+
const ok = run(NPM, ["install", "-g", `haoyuan@${latest}`, ...npmRegistryArgs()], { lenient: true });
|
|
1146
|
+
if (!ok) {
|
|
1147
|
+
fail("升级失败。若提示权限不足,请用管理员权限运行,或手动执行: npm install -g haoyuan@latest");
|
|
1148
|
+
}
|
|
1149
|
+
log(`升级完成:v${VERSION} → v${latest}`);
|
|
1150
|
+
log("请重新运行 haoyuan 以使用新版本。");
|
|
1151
|
+
}
|
|
1152
|
+
|
|
1073
1153
|
function printHelp() {
|
|
1074
1154
|
process.stdout.write(
|
|
1075
1155
|
[
|
|
@@ -1086,6 +1166,7 @@ function printHelp() {
|
|
|
1086
1166
|
" haoyuan logout 清除本地登录令牌",
|
|
1087
1167
|
" haoyuan setup 安装后端/前端依赖",
|
|
1088
1168
|
" haoyuan build 仅构建前端",
|
|
1169
|
+
" haoyuan upgrade 升级到 npm 最新版本",
|
|
1089
1170
|
" haoyuan help 显示帮助",
|
|
1090
1171
|
"",
|
|
1091
1172
|
"选项:",
|
|
@@ -1152,6 +1233,10 @@ async function main() {
|
|
|
1152
1233
|
buildFrontend();
|
|
1153
1234
|
return;
|
|
1154
1235
|
}
|
|
1236
|
+
if (command === "upgrade" || command === "update") {
|
|
1237
|
+
await upgradeCommand();
|
|
1238
|
+
return;
|
|
1239
|
+
}
|
|
1155
1240
|
if (command === "postinstall") {
|
|
1156
1241
|
postinstall();
|
|
1157
1242
|
return;
|
package/package.json
CHANGED
package/web/package-lock.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "haoyuan-web",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.5",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "haoyuan-web",
|
|
9
|
-
"version": "0.0.
|
|
9
|
+
"version": "0.0.5",
|
|
10
10
|
"dependencies": {
|
|
11
11
|
"dompurify": "^3.2.4",
|
|
12
12
|
"marked": "^15.0.7",
|