haoyuan 0.0.4 → 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.
@@ -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.4"
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 = spawnSync(
94
- cmd,
95
- useShell ? args.map(shellQuote) : args,
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}[助手]${C.reset} `);
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}[助手]${C.reset} ${payload.text}\n`);
777
+ process.stdout.write(`${C.bold}[HaoYuan]${C.reset} ${payload.text}\n`);
767
778
  }
768
779
  endLine();
769
780
  if (state.busy) {
@@ -1102,11 +1113,9 @@ function compareVersions(a, b) {
1102
1113
  function npmCapture(args) {
1103
1114
  const full = [...args, ...npmRegistryArgs()];
1104
1115
  const useShell = IS_WIN && /\.(cmd|bat)$/i.test(NPM);
1105
- const r = spawnSync(NPM, useShell ? full.map(shellQuote) : full, {
1106
- cwd: ROOT,
1107
- encoding: "utf8",
1108
- shell: useShell,
1109
- });
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" });
1110
1119
  if (r.error) return { ok: false, error: r.error.message };
1111
1120
  if (r.status !== 0) {
1112
1121
  const detail = (r.stderr || r.stdout || "").trim();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "haoyuan",
3
- "version": "0.0.4",
3
+ "version": "0.0.5",
4
4
  "description": "豪源 · HaoYuan — 个人指挥 AI 实现多个 AI 员工异步并行工作的 AI 工作室",
5
5
  "bin": {
6
6
  "haoyuan": "bin/haoyuan.js"
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "haoyuan-web",
3
- "version": "0.0.4",
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.4",
9
+ "version": "0.0.5",
10
10
  "dependencies": {
11
11
  "dompurify": "^3.2.4",
12
12
  "marked": "^15.0.7",
package/web/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "haoyuan-web",
3
- "version": "0.0.4",
3
+ "version": "0.0.5",
4
4
  "private": true,
5
5
  "type": "module",
6
6
  "scripts": {