wdb/d_wiki/cli.py
yue02.sun 5bf9a2ed59 feat: 集成 d-auth 认证系统
## 改动

- 移除内置的 auth 模块,改为调用 d-auth CLI
- 添加登录拦截器,保护 index/compile/dream/search/get 命令
- 添加 d-auth 作为依赖项

## 认证流程

1. 用户执行需要认证的命令
2. d-wiki 调用 d-auth check 检查登录状态
3. 未登录则拦截并提示用户登录
4. 已登录则正常执行命令

## 相关文档

见 docs/AUTH.md

Co-Authored-By: Claude <noreply@anthropic.com>
2026-06-02 22:01:00 +08:00

142 lines
5.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from __future__ import annotations
import argparse
import json
import subprocess
import sys
from pathlib import Path
from typing import Any
from .config import DWikiConfig, load_config
from .compile import compile_kb
from .dreams import dream_kb
from .search import get_page, index_payload, search, status_payload
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(prog="d-wiki")
parser.add_argument("--config", type=Path, default=None)
subparsers = parser.add_subparsers(dest="command", required=True)
# auth 子命令 - 转发给 d-auth CLI
auth_parser = subparsers.add_parser("auth")
auth_sub = auth_parser.add_subparsers(dest="auth_action", required=True)
auth_login = auth_sub.add_parser("login")
auth_login.add_argument("--timeout", type=int, default=120)
auth_logout = auth_sub.add_parser("logout")
auth_status = auth_sub.add_parser("status")
status_parser = subparsers.add_parser("status")
status_parser.add_argument("--format", choices=["json"], default="json")
index_parser = subparsers.add_parser("index")
index_parser.add_argument("--kb", required=True)
index_parser.add_argument("--format", choices=["json"], default="json")
compile_parser = subparsers.add_parser("compile")
compile_parser.add_argument("--kb", required=True)
compile_parser.add_argument("--force", action="store_true")
compile_parser.add_argument("--llm", choices=["off", "auto", "require"], default="off")
compile_parser.add_argument("--llm-scope", choices=["queries", "all"], default="queries")
compile_parser.add_argument("--format", choices=["json"], default="json")
dream_parser = subparsers.add_parser("dream")
dream_parser.add_argument("--kb", required=True)
dream_parser.add_argument("--force", action="store_true")
dream_parser.add_argument("--format", choices=["json"], default="json")
search_parser = subparsers.add_parser("search")
search_parser.add_argument("--kb", required=True)
search_parser.add_argument("--query", required=True)
search_parser.add_argument("--max-results", type=int, default=5)
search_parser.add_argument("--format", choices=["json"], default="json")
get_parser = subparsers.add_parser("get")
get_parser.add_argument("--kb", required=True)
get_parser.add_argument("--id", required=True)
get_parser.add_argument("--format", choices=["json"], default="json")
args = parser.parse_args(argv)
try:
config = load_config(args.config)
payload = dispatch(args, config)
except Exception as exc:
print(json.dumps({"status": "error", "error": str(exc)}, ensure_ascii=False), file=sys.stderr)
return 2
print(json.dumps(payload, ensure_ascii=False, indent=2, sort_keys=True))
return 0
# 需要登录才能使用的命令
REQUIRES_AUTH = {"index", "compile", "dream", "search", "get"}
def call_d_auth(subcommand: str, extra_args: list[str] = None) -> dict[str, Any]:
"""调用 d-auth CLI 并返回结果"""
cmd = ["d-auth", subcommand]
if extra_args:
cmd.extend(extra_args)
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode != 0:
try:
return json.loads(result.stderr)
except json.JSONDecodeError:
return {"status": "error", "error": result.stderr.strip()}
return json.loads(result.stdout)
def check_auth_or_exit(command: str) -> None:
"""检查登录状态,未登录则打印错误并退出 - 通过调用 d-auth CLI"""
if command not in REQUIRES_AUTH:
return
# 调用 d-auth check 检查登录状态
result = call_d_auth("check")
if not result.get("logged_in", False):
print(json.dumps({
"status": "error",
"error": "D_WIKI_NOT_LOGGED_IN: 请先运行 'd-auth login' 登录",
"hint": "d-auth login"
}, ensure_ascii=False), file=sys.stderr)
sys.exit(1)
def dispatch(args: argparse.Namespace, config: DWikiConfig) -> dict[str, Any]:
# 先检查登录状态(通过 d-auth CLI)
check_auth_or_exit(args.command)
if args.command == "auth":
return handle_auth(args)
if args.command == "status":
return status_payload(config.path, config.knowledge_bases)
kb = config.knowledge_bases.get(args.kb)
if kb is None:
raise ValueError(f"D_WIKI_KB_NOT_FOUND: {args.kb}")
if args.command == "index":
return index_payload(kb)
if args.command == "compile":
return compile_kb(kb, force=args.force, llm_mode=args.llm, llm_scope=args.llm_scope)
if args.command == "dream":
return dream_kb(kb, force=args.force)
if args.command == "search":
return search(kb, args.query, args.max_results)
if args.command == "get":
return get_page(kb, args.id)
raise ValueError(f"D_WIKI_UNKNOWN_COMMAND: {args.command}")
def handle_auth(args: argparse.Namespace) -> dict[str, Any]:
"""处理 auth 子命令 - 转发给 d-auth CLI"""
if args.auth_action == "login":
return call_d_auth("login", ["--timeout", str(args.timeout)])
elif args.auth_action == "logout":
return call_d_auth("logout")
elif args.auth_action == "status":
return call_d_auth("status")
raise ValueError(f"D_WIKI_UNKNOWN_AUTH_ACTION: {args.auth_action}")