342 lines
11 KiB
Markdown
342 lines
11 KiB
Markdown
---
|
|
phase: 07-login-auth
|
|
plan: 03
|
|
type: execute
|
|
wave: 2
|
|
depends_on:
|
|
- 07-01
|
|
- 07-02
|
|
files_modified:
|
|
- kb_workflow/auth/zhihu_login.py
|
|
- kb_workflow/auth/cookie_manager.py
|
|
- kb_workflow/kb_workflow.py
|
|
- tests/test_auth/test_cookie_validation.py
|
|
- tests/test_auth/test_cli_login.py
|
|
autonomous: false
|
|
requirements:
|
|
- AUTH-04
|
|
user_setup: []
|
|
|
|
must_haves:
|
|
truths:
|
|
- "用户可以通过 python3 kb-workflow/kb_workflow.py login 启动登录流程"
|
|
- "登录成功后 Cookie 自动保存到 ~/.kb_env"
|
|
- "Cookie 过期时系统自动检测并提示用户"
|
|
- "用户可以手动导入 Cookie 文件"
|
|
- "用户可以查看当前 Cookie 状态"
|
|
artifacts:
|
|
- path: "kb_workflow/auth/zhihu_login.py"
|
|
provides: "Cookie 验证方法"
|
|
exports: ["validate_cookie"]
|
|
- path: "kb_workflow/kb_workflow.py"
|
|
provides: "login CLI 子命令"
|
|
contains: "subparsers.add_parser('login')"
|
|
key_links:
|
|
- from: "kb_workflow.py login"
|
|
to: "ZhihuLogin.login_by_qrcode()"
|
|
via: "asyncio.run()"
|
|
pattern: "login_by_qrcode"
|
|
- from: "ZhihuLogin.login_by_qrcode()"
|
|
to: "CookieManager.save_cookie()"
|
|
via: "登录成功后保存"
|
|
pattern: "save_cookie"
|
|
- from: "validate_cookie()"
|
|
to: "/api/v4/me"
|
|
via: "Playwright request API"
|
|
pattern: "api/v4/me"
|
|
---
|
|
|
|
<objective>
|
|
实现 Cookie 验证机制和 CLI login 子命令。
|
|
|
|
Purpose: 整合登录功能到 CLI,支持 Cookie 验证和状态查询
|
|
Output: 完整的 login 命令 + Cookie 验证 + 端到端测试
|
|
</objective>
|
|
|
|
<execution_context>
|
|
@/home/starmen1265/.claude/get-shit-done/workflows/execute-plan.md
|
|
@/home/starmen1265/.claude/get-shit-done/templates/summary.md
|
|
</execution_context>
|
|
|
|
<context>
|
|
@.planning/PROJECT.md
|
|
@.planning/ROADMAP.md
|
|
@.planning/STATE.md
|
|
@.planning/phases/07-login-auth/07-CONTEXT.md
|
|
@.planning/phases/07-login-auth/07-RESEARCH.md
|
|
@.planning/phases/07-login-auth/07-01-PLAN.md
|
|
@.planning/phases/07-login-auth/07-02-PLAN.md
|
|
|
|
<interfaces>
|
|
<!-- Key interfaces from prior plans -->
|
|
|
|
From kb_workflow/auth/zhihu_login.py (Plan 01):
|
|
```python
|
|
class ZhihuLogin:
|
|
async def login_by_qrcode(self) -> ZhihuLoginResult
|
|
async def check_login_cookie(self) -> bool
|
|
async def get_cookies_str(self) -> str
|
|
```
|
|
|
|
From kb_workflow/auth/cookie_manager.py (Plan 02):
|
|
```python
|
|
def parse_json_cookies(json_path: str) -> str
|
|
|
|
class CookieManager:
|
|
def save_cookie(self, cookie_str: str) -> None
|
|
def load_cookie(self) -> str
|
|
```
|
|
|
|
From kb_workflow/kb_workflow.py (existing):
|
|
```python
|
|
def process_command(url: str, ...) -> Dict[str, Any]
|
|
|
|
def main():
|
|
subparsers = parser.add_subparsers(dest='command')
|
|
# 添加 login 子命令到此处
|
|
```
|
|
|
|
知乎 API:
|
|
- 验证接口: GET https://www.zhihu.com/api/v4/me
|
|
- 成功返回: {"id": 123, "name": "用户名", ...}
|
|
- 失败返回: 401 状态码
|
|
</interfaces>
|
|
</context>
|
|
|
|
<tasks>
|
|
|
|
<task type="auto" tdd="true">
|
|
<name>Task 1: 实现 Cookie 验证功能</name>
|
|
<files>kb_workflow/auth/zhihu_login.py, tests/test_auth/test_cookie_validation.py</files>
|
|
<behavior>
|
|
- Test 1: validate_cookie_valid - 有效 Cookie 返回 valid=True 和用户信息
|
|
- Test 2: validate_cookie_expired - 过期 Cookie 返回 valid=False
|
|
- Test 3: validate_cookie_empty - 空 Cookie 返回 valid=False
|
|
- Test 4: validate_cookie_malformed - 格式错误 Cookie 返回 valid=False
|
|
</behavior>
|
|
<action>
|
|
扩展 `kb_workflow/auth/zhihu_login.py` 添加 Cookie 验证功能:
|
|
|
|
1. 添加 `CookieValidationResult` Pydantic model:
|
|
```python
|
|
from pydantic import BaseModel
|
|
from typing import Optional
|
|
|
|
class CookieValidationResult(BaseModel):
|
|
"""Cookie 验证结果"""
|
|
valid: bool
|
|
username: Optional[str] = None
|
|
user_id: Optional[str] = None
|
|
reason: Optional[str] = None
|
|
```
|
|
|
|
2. 在 `ZhihuLogin` 类中添加验证方法:
|
|
```python
|
|
VALIDATION_URL = "https://www.zhihu.com/api/v4/me"
|
|
|
|
async def validate_cookie(self, cookie_str: str = None) -> CookieValidationResult:
|
|
"""验证 Cookie 有效性
|
|
|
|
通过请求知乎用户信息接口检测 Cookie 是否有效。
|
|
|
|
Args:
|
|
cookie_str: 要验证的 Cookie 字符串,为空时使用已加载的 Cookie
|
|
|
|
Returns:
|
|
CookieValidationResult 包含验证状态和用户信息
|
|
"""
|
|
# 如果提供了 cookie_str,需要重新启动浏览器并设置 Cookie
|
|
if cookie_str:
|
|
if self.browser.browser:
|
|
self.browser.close()
|
|
self.browser.start(cookie=cookie_str)
|
|
elif not self.browser.page:
|
|
return CookieValidationResult(valid=False, reason="No cookie provided")
|
|
|
|
try:
|
|
# 使用 Playwright 的 request API
|
|
response = await self.browser.page.request.get(self.VALIDATION_URL)
|
|
|
|
if response.status == 200:
|
|
user_info = await response.json()
|
|
return CookieValidationResult(
|
|
valid=True,
|
|
username=user_info.get("name", ""),
|
|
user_id=str(user_info.get("id", ""))
|
|
)
|
|
elif response.status == 401:
|
|
return CookieValidationResult(valid=False, reason="Cookie expired")
|
|
else:
|
|
return CookieValidationResult(
|
|
valid=False,
|
|
reason=f"Validation failed with status {response.status}"
|
|
)
|
|
except Exception as e:
|
|
return CookieValidationResult(valid=False, reason=str(e))
|
|
```
|
|
|
|
3. 创建 `tests/test_auth/test_cookie_validation.py`:
|
|
- 使用 mock 模拟 page.request.get() 返回不同状态码
|
|
- 测试有效、过期、空、格式错误等场景
|
|
</action>
|
|
<verify>
|
|
<automated>pytest tests/test_auth/test_cookie_validation.py -x -v</automated>
|
|
</verify>
|
|
<done>
|
|
- validate_cookie 方法可用
|
|
- 4 个单元测试全部通过
|
|
- 返回 CookieValidationResult 结构
|
|
</done>
|
|
</task>
|
|
|
|
<task type="auto" tdd="true">
|
|
<name>Task 2: 实现 login CLI 子命令</name>
|
|
<files>kb_workflow/kb_workflow.py, tests/test_auth/test_cli_login.py</files>
|
|
<behavior>
|
|
- Test 1: login_default_mode - 默认启动二维码登录
|
|
- Test 2: login_import_cookie - --import-cookie 参数导入 JSON
|
|
- Test 3: login_status - --status 参数检查 Cookie 状态
|
|
- Test 4: login_integration - 登录成功后 Cookie 保存到文件
|
|
</behavior>
|
|
<action>
|
|
扩展 `kb_workflow/kb_workflow.py` 添加 login 子命令:
|
|
|
|
1. 添加 login_command 函数:
|
|
```python
|
|
def login_command(
|
|
import_cookie: Optional[str] = None,
|
|
status: bool = False
|
|
) -> Dict[str, Any]:
|
|
"""Execute login command
|
|
|
|
Args:
|
|
import_cookie: Path to JSON cookie file
|
|
status: Check current cookie status
|
|
|
|
Returns:
|
|
Dictionary with login result
|
|
"""
|
|
try:
|
|
from kb_workflow.auth import ZhihuLogin
|
|
from kb_workflow.auth.cookie_manager import CookieManager, parse_json_cookies
|
|
from kb_workflow.pipeline.config import get_settings
|
|
|
|
settings = get_settings()
|
|
manager = CookieManager()
|
|
|
|
# 检查 Cookie 状态
|
|
if status:
|
|
current_cookie = settings.zhihu_cookie.get_secret_value()
|
|
if not current_cookie:
|
|
return {"valid": False, "reason": "No cookie found in ~/.kb_env"}
|
|
|
|
async def check_status():
|
|
login = ZhihuLogin(intermediate_path=settings.intermediate_path)
|
|
try:
|
|
login.browser.start(cookie=current_cookie)
|
|
return await login.validate_cookie(current_cookie)
|
|
finally:
|
|
login.browser.close()
|
|
|
|
result = asyncio.run(check_status())
|
|
return result.model_dump()
|
|
|
|
# 导入 Cookie
|
|
if import_cookie:
|
|
cookie_str = parse_json_cookies(import_cookie)
|
|
manager.save_cookie(cookie_str)
|
|
return {"success": True, "message": f"Cookie imported from {import_cookie}"}
|
|
|
|
# 二维码登录
|
|
async def qrcode_login():
|
|
login = ZhihuLogin(intermediate_path=settings.intermediate_path)
|
|
try:
|
|
result = await login.login_by_qrcode()
|
|
if result.success and result.cookie_str:
|
|
manager.save_cookie(result.cookie_str)
|
|
return result.model_dump()
|
|
finally:
|
|
if login.browser.browser:
|
|
login.browser.close()
|
|
|
|
result = asyncio.run(qrcode_login())
|
|
return result
|
|
|
|
except Exception as e:
|
|
return {"success": False, "error": str(e)}
|
|
```
|
|
|
|
2. 在 main() 函数中添加 login 子命令:
|
|
```python
|
|
# Login subcommand
|
|
login_parser = subparsers.add_parser('login', help='Zhihu login authentication')
|
|
login_parser.add_argument('--import-cookie', '-i', type=str,
|
|
help='Import cookie from JSON file')
|
|
login_parser.add_argument('--status', action='store_true',
|
|
help='Check current cookie status')
|
|
|
|
# Handle login subcommand
|
|
if args.command == 'login':
|
|
result = login_command(
|
|
import_cookie=args.import_cookie,
|
|
status=args.status
|
|
)
|
|
print(json.dumps(result, ensure_ascii=False, indent=2))
|
|
```
|
|
|
|
3. 创建 `tests/test_auth/test_cli_login.py`:
|
|
- 使用 mock 模拟 ZhihuLogin 和 CookieManager
|
|
- 测试各种命令行参数组合
|
|
</action>
|
|
<verify>
|
|
<automated>pytest tests/test_auth/test_cli_login.py -x -v</automated>
|
|
</verify>
|
|
<done>
|
|
- login 子命令可用
|
|
- 支持 --import-cookie 和 --status 参数
|
|
- 4 个单元测试全部通过
|
|
</done>
|
|
</task>
|
|
|
|
<task type="checkpoint:human-verify" gate="blocking">
|
|
<what-built>
|
|
完整的知乎登录认证系统:
|
|
- 二维码扫码登录 (python3 kb-workflow/kb_workflow.py login)
|
|
- JSON Cookie 导入 (python3 kb-workflow/kb_workflow.py login --import-cookie cookies.json)
|
|
- Cookie 状态检查 (python3 kb-workflow/kb_workflow.py login --status)
|
|
- Cookie 自动持久化到 ~/.kb_env
|
|
</what-built>
|
|
<how-to-verify>
|
|
1. 运行 `python3 kb-workflow/kb_workflow.py login`
|
|
2. 验证二维码图片生成在 `~/work/intermediate/zhihu_qrcode_*.png`
|
|
3. 使用知乎 APP 扫码确认登录
|
|
4. 验证命令返回 `{"success": true, "cookie_str": "..."}`
|
|
5. 检查 `~/.kb_env` 文件包含 `ZHIHU_COOKIE="..."` 行
|
|
6. 运行 `python3 kb-workflow/kb_workflow.py login --status`
|
|
7. 验证返回用户信息
|
|
</how-to-verify>
|
|
<resume-signal>Type "approved" if login works, or describe issues</resume-signal>
|
|
</task>
|
|
|
|
</tasks>
|
|
|
|
<verification>
|
|
1. 所有测试通过: `pytest tests/test_auth/ -v`
|
|
2. login 命令可用: `python3 kb-workflow/kb_workflow.py login --help`
|
|
3. Cookie 验证功能: `python3 -c "from kb_workflow.auth import ZhihuLogin; print(ZhihuLogin.validate_cookie)"`
|
|
</verification>
|
|
|
|
<success_criteria>
|
|
- 用户可以通过命令行扫码登录知乎
|
|
- 扫码成功后 Cookie 自动保存
|
|
- 用户可以手动导入 JSON Cookie
|
|
- 用户可以查看 Cookie 状态
|
|
- Cookie 过期时系统提示重新登录
|
|
- 所有单元测试通过 (18+ tests)
|
|
- 手动验证登录流程成功
|
|
</success_criteria>
|
|
|
|
<output>
|
|
After completion, create `.planning/phases/07-login-auth/07-03-SUMMARY.md`
|
|
</output>
|