Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 1ba7a0f4a1 | |||
| 71b20e6e4a | |||
| 7709292f1c | |||
| b93b2ea36e | |||
| 44eafff757 | |||
| 3ce0cc40a1 |
33
CHANGELOG.md
Normal file
33
CHANGELOG.md
Normal file
@@ -0,0 +1,33 @@
|
||||
# Changelog
|
||||
|
||||
本文件对应技能市场 **「更新日志」** Tab。
|
||||
发布 CI 会按当前 tag 版本提取匹配的 `##` 小节。
|
||||
|
||||
## 2.0.30
|
||||
|
||||
- 「打开浏览器」为本账号 Profile 附加稳定本机调试口(与科力普等采集技能约定同一端口算法),便于采集挂接已打开的原生窗口;仍使用 `--restore-last-session` 恢复登录态
|
||||
|
||||
## 2.0.29
|
||||
|
||||
- 「打开浏览器」有可恢复会话时改用 `--restore-last-session` 强制恢复标签与 Session Cookie;不再裸写受 Secure Preferences HMAC 保护的 `restore_on_startup`(该写法会被 Chrome 否掉并落到新标签页)
|
||||
|
||||
## 2.0.28
|
||||
|
||||
- 「打开浏览器」识别现代 Chrome `Default/Sessions/Session_*`(及 `Tabs_*`),有可恢复会话时不再强制带平台首页 URL,避免冲掉 Session Cookie 登录态
|
||||
|
||||
## 2.0.27
|
||||
|
||||
- 「打开浏览器」:Profile 已占用时复用窗口;加固 Preferences/Local State「继续上次会话」;有历史会话时冷启动不带 URL,避免冲掉登录态
|
||||
|
||||
## 2.0.26
|
||||
|
||||
- 「打开浏览器」启动前写入 Profile「继续上次会话」,减轻独立 Profile 下 Session Cookie 关窗后丢失(科力普等站点更明显)
|
||||
|
||||
## 2.0.25
|
||||
|
||||
- 「账号租约」表新增行右键「强制释放租约」:仅状态为 active 时显示,确认后立刻释放,无需租约令牌
|
||||
- 同步提供 CLI:`lease force-release --id <租约编号>`
|
||||
|
||||
## 2.0.24
|
||||
|
||||
- (历史版本,见 git tag)
|
||||
4
SKILL.md
4
SKILL.md
@@ -1,7 +1,7 @@
|
||||
---
|
||||
name: 账号与凭据管理
|
||||
description: "通用账号 & 凭据 & 登录流程管理器。管理网页/RPA 账号、API Key/Token;支持 9 种登录策略(账密自动、扫码、2FA、SSO 等);提供加密本地存储(Fernet);提供 rpa_helpers 库供业务 skill 同进程调用 ensure_logged_in 完成多平台自动登录。涵盖物流、LLM、内容、开发、API 五类平台。"
|
||||
version: 2.0.24
|
||||
version: 2.0.30
|
||||
author: 深圳匠厂科技有限公司
|
||||
metadata:
|
||||
openclaw:
|
||||
@@ -39,7 +39,7 @@ allowed-tools:
|
||||
10. **获取 API Key(凭据表)**:`credential pick` — 默认隐藏 secret,`--reveal` 时才返回。
|
||||
11. **打开浏览器**:`account open <id>`(或兼容别名 `open <id>`)— **本进程**直接拉起系统 Chrome/Edge(独立 `--user-data-dir`),最大化并跳过 Chrome 首次欢迎页,直接打开平台链接;与「打开目录」同为一点即走,不做登录判定。数据管理「打开目录 / 打开浏览器」成功不弹提示。
|
||||
12. **打开目录**:`account reveal-profile <id>` — 在系统文件管理器中打开该账号 `profile_dir`。
|
||||
13. **管理 lease**:`lease release/list/cleanup` — 防止 RPA 并发。
|
||||
13. **管理 lease**:`lease release/force-release/list/cleanup` — 防止 RPA 并发;数据管理「账号租约」行右键可强制释放。
|
||||
14. **初始化加密**:`account init-master-key` — 生成 Fernet master.key。
|
||||
15. **加密备份与迁移**:`account export-credentials --plaintext` / `account import-credentials` — 导出明文 JSON、在新环境重新加密写入。
|
||||
16. **按 lease 取明文密码**:`account get-credential <id> --reveal --lease-token <token>` — 结合 pick-web 返回的 lease 解密 `local_encrypted` 等路径。
|
||||
|
||||
@@ -248,6 +248,44 @@
|
||||
"command": "account",
|
||||
"args": ["open", "{{accountId}}"]
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "lease-force-release",
|
||||
"label": "强制释放租约",
|
||||
"description": "强制释放这条活跃租约,让账号立刻可被其它任务占用。仅状态为 active 时可用。",
|
||||
"placements": ["row"],
|
||||
"executionProfile": "sync",
|
||||
"interaction": "confirm",
|
||||
"confirmation": {
|
||||
"message": "强制释放后,其它任务可立刻占用该账号。若原任务仍在跑,可能冲突。是否继续?"
|
||||
},
|
||||
"bind": {
|
||||
"tables": ["account_leases"],
|
||||
"inputMapping": {
|
||||
"leaseId": "$row.$pk"
|
||||
},
|
||||
"visibleWhen": {
|
||||
"status": "active"
|
||||
}
|
||||
},
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"required": ["leaseId"],
|
||||
"properties": {
|
||||
"leaseId": {
|
||||
"type": "number",
|
||||
"title": "租约编号",
|
||||
"description": "当前行编号,一般无需修改",
|
||||
"readOnly": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"steps": [{ "when": "afterSuccess", "do": "reloadTable" }],
|
||||
"entrypoint": {
|
||||
"type": "cli",
|
||||
"command": "lease",
|
||||
"args": ["force-release", "--id", "{{leaseId}}"]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -76,6 +76,7 @@
|
||||
| `credential pick --platform <p> [--type <type>] [--environment <env>] [--role <role>] [--reveal]` | v1 兼容:挑选凭据 |
|
||||
| `credential resolve --id <credential_id> [--reveal]` | v1 兼容:按凭据 id 解析 |
|
||||
| `lease release <lease_token>` | 释放租约 |
|
||||
| `lease force-release --id <租约编号>` | 按行编号强制释放活跃租约(数据管理右键) |
|
||||
| `lease list [--active]` | 列出租约 |
|
||||
| `lease cleanup` | 清理过期租约 |
|
||||
| `account open <id>` / `open <id>` | 打开浏览器 |
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
| 前缀 | 含义 |
|
||||
|---|---|
|
||||
| `ERROR:LEASE_CONFLICT` | 同账号已有 active 未过期 lease |
|
||||
| `ERROR:LEASE_NOT_FOUND` | 未找到活跃租约 |
|
||||
| `ERROR:LEASE_NOT_FOUND` | 未找到活跃租约(含 force-release 时行不存在或已非 active) |
|
||||
| `ERROR:LEASE_EXPIRED` | 租约已过期 |
|
||||
|
||||
---
|
||||
|
||||
@@ -59,4 +59,4 @@ description: "通用账号 & 凭据 & 登录流程管理器。管理网页/RPA
|
||||
|
||||
---
|
||||
|
||||
**作者**:深圳匠厂科技有限公司 · **版本**:2.0.24
|
||||
**作者**:深圳匠厂科技有限公司 · **版本**:2.0.27
|
||||
|
||||
@@ -7,7 +7,7 @@ Subcommand tree:
|
||||
account add-web|copy|update|ensure-web|add-secret|get|get-credential|list|resolve|pick-web|mark-session|mark-error|mark-used|open|reveal-profile
|
||||
init-master-key|export-credentials|import-credentials
|
||||
credential pick|resolve
|
||||
lease release|list|cleanup
|
||||
lease release|force-release|list|cleanup
|
||||
(legacy) add|list|get|list-json|pick-web|open|delete
|
||||
|
||||
Machine commands output single-line JSON where appropriate.
|
||||
@@ -42,6 +42,7 @@ from service.account_service import (
|
||||
cmd_get,
|
||||
cmd_init_db,
|
||||
cmd_lease_cleanup,
|
||||
cmd_lease_force_release,
|
||||
cmd_lease_list,
|
||||
cmd_lease_release,
|
||||
cmd_list,
|
||||
@@ -121,6 +122,7 @@ _USAGE = """account-manager v2 — Credential & Browser Profile Manager
|
||||
|
||||
租约管理:
|
||||
lease release <lease_token>
|
||||
lease force-release --id <租约编号>
|
||||
lease list [--active]
|
||||
lease cleanup
|
||||
|
||||
@@ -369,7 +371,7 @@ def main() -> None:
|
||||
# ---- lease subcommand ----
|
||||
elif cmd == "lease":
|
||||
if len(av) < 3:
|
||||
print("ERROR:CLI_BAD_ARGS lease 需要子命令:release | list | cleanup")
|
||||
print("ERROR:CLI_BAD_ARGS lease 需要子命令:release | force-release | list | cleanup")
|
||||
sys.exit(1)
|
||||
sub = av[2]
|
||||
if sub == "release":
|
||||
@@ -377,13 +379,25 @@ def main() -> None:
|
||||
print("ERROR:CLI_BAD_ARGS lease release 需要 <lease_token>。")
|
||||
sys.exit(1)
|
||||
cmd_lease_release(av[3])
|
||||
elif sub == "force-release":
|
||||
lease_id = _get_opt(av, "--id")
|
||||
if lease_id is None and len(av) >= 4 and not str(av[3]).startswith("-"):
|
||||
lease_id = av[3]
|
||||
if lease_id is None:
|
||||
print("ERROR:CLI_BAD_ARGS lease force-release 需要 --id <租约编号>。")
|
||||
sys.exit(1)
|
||||
try:
|
||||
cmd_lease_force_release(int(lease_id))
|
||||
except ValueError:
|
||||
print("ERROR:CLI_BAD_ARGS 租约编号必须是数字。")
|
||||
sys.exit(1)
|
||||
elif sub == "list":
|
||||
active = _has_flag(av, "--active")
|
||||
cmd_lease_list(active)
|
||||
elif sub == "cleanup":
|
||||
cmd_lease_cleanup()
|
||||
else:
|
||||
print("ERROR:CLI_BAD_ARGS lease 子命令必须是 release、list 或 cleanup。")
|
||||
print("ERROR:CLI_BAD_ARGS lease 子命令必须是 release、force-release、list 或 cleanup。")
|
||||
sys.exit(1)
|
||||
|
||||
# ---- Legacy aliases ----
|
||||
|
||||
@@ -795,6 +795,59 @@ def release_lease(lease_token: str) -> bool:
|
||||
conn.close()
|
||||
|
||||
|
||||
def release_lease_by_id(lease_id: int) -> Optional[dict]:
|
||||
"""Force-release an active lease by row id. Returns released row summary or None."""
|
||||
log = get_skill_logger()
|
||||
log.info("lease_force_release_attempt lease_id=%s", lease_id)
|
||||
conn = get_conn()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
now = _now_unix()
|
||||
cur.execute(
|
||||
"SELECT id, account_id, lease_token, holder, purpose, status "
|
||||
"FROM account_leases WHERE id = ?",
|
||||
(int(lease_id),),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
log.warning("lease_force_release_not_found lease_id=%s", lease_id)
|
||||
return None
|
||||
status = str(row[5] or "")
|
||||
if status != "active":
|
||||
log.warning(
|
||||
"lease_force_release_not_active lease_id=%s status=%s",
|
||||
lease_id,
|
||||
status,
|
||||
)
|
||||
return None
|
||||
cur.execute(
|
||||
"UPDATE account_leases SET status = 'released', released_at = ?, updated_at = ? "
|
||||
"WHERE id = ? AND status = 'active'",
|
||||
(now, now, int(lease_id)),
|
||||
)
|
||||
conn.commit()
|
||||
if cur.rowcount == 0:
|
||||
return None
|
||||
token = str(row[2] or "")
|
||||
log.info(
|
||||
"lease_force_release_success lease_id=%s account_id=%s token_prefix=%s",
|
||||
lease_id,
|
||||
row[1],
|
||||
token[:8] if token else "",
|
||||
)
|
||||
return {
|
||||
"id": int(row[0]),
|
||||
"account_id": int(row[1]),
|
||||
"lease_token": token,
|
||||
"holder": row[3] or "",
|
||||
"purpose": row[4] or "",
|
||||
"status": "released",
|
||||
"released_at": _unix_to_iso_local(now),
|
||||
}
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def list_active_leases() -> list[dict]:
|
||||
"""List all active (non-expired, non-released) leases."""
|
||||
conn = get_conn()
|
||||
|
||||
@@ -39,7 +39,12 @@ from service.legacy_commands import (
|
||||
cmd_delete_by_platform_phone,
|
||||
cmd_list,
|
||||
)
|
||||
from service.lease_commands import cmd_lease_cleanup, cmd_lease_list, cmd_lease_release
|
||||
from service.lease_commands import (
|
||||
cmd_lease_cleanup,
|
||||
cmd_lease_force_release,
|
||||
cmd_lease_list,
|
||||
cmd_lease_release,
|
||||
)
|
||||
from service.platform_commands import (
|
||||
cmd_init_db,
|
||||
cmd_platform_ensure,
|
||||
@@ -70,6 +75,7 @@ __all__ = [
|
||||
"cmd_get",
|
||||
"cmd_init_db",
|
||||
"cmd_lease_cleanup",
|
||||
"cmd_lease_force_release",
|
||||
"cmd_lease_list",
|
||||
"cmd_lease_release",
|
||||
"cmd_list",
|
||||
|
||||
@@ -14,6 +14,10 @@ import sys
|
||||
|
||||
from db.connection import get_conn, init_db
|
||||
from db.accounts_repo import get_account_by_id, get_platform_from_db
|
||||
from service.chrome_profile_prefs import (
|
||||
ensure_session_restore,
|
||||
profile_has_restorable_session,
|
||||
)
|
||||
from util.logging_config import get_skill_logger
|
||||
from util.platforms import PLATFORMS
|
||||
|
||||
@@ -83,21 +87,50 @@ HUMAN_CHROME_FLAGS = (
|
||||
"--disable-search-engine-choice-screen",
|
||||
)
|
||||
|
||||
# 强制恢复上次会话(含 Session Cookie)。不依赖 Preferences.restore_on_startup
|
||||
#(该项受 Secure Preferences HMAC 保护,裸写会被 Chrome 否掉)。
|
||||
RESTORE_LAST_SESSION_FLAG = "--restore-last-session"
|
||||
|
||||
def human_chrome_launch_args(profile_dir, url=None):
|
||||
# 与 scrape-product-colipu 等业务技能约定同一算法,便于 CDP 挂接已打开的账号窗口。
|
||||
_CDP_PORT_BASE = 9330
|
||||
_CDP_PORT_SPAN = 60
|
||||
|
||||
|
||||
def cdp_port_for_profile(profile_dir: str) -> int:
|
||||
"""按 profile 绝对路径派生稳定本机调试端口(9330–9389)。"""
|
||||
import hashlib
|
||||
|
||||
key = os.path.abspath(profile_dir).replace("/", "\\").lower().encode("utf-8")
|
||||
digest = hashlib.sha1(key).hexdigest()
|
||||
return _CDP_PORT_BASE + (int(digest[:8], 16) % _CDP_PORT_SPAN)
|
||||
|
||||
|
||||
def human_chrome_launch_args(profile_dir, url=None, restore_session=False, *, enable_cdp=True):
|
||||
"""chrome.exe 之后的参数(Popen 列表形式,路径不额外加引号)。"""
|
||||
profile_abs = os.path.abspath(profile_dir)
|
||||
args = [f"--user-data-dir={profile_abs}", *HUMAN_CHROME_FLAGS]
|
||||
if restore_session:
|
||||
args.append(RESTORE_LAST_SESSION_FLAG)
|
||||
if enable_cdp:
|
||||
port = cdp_port_for_profile(profile_abs)
|
||||
args.append(f"--remote-debugging-port={port}")
|
||||
args.append("--remote-debugging-address=127.0.0.1")
|
||||
cleaned = (url or "").strip()
|
||||
if cleaned:
|
||||
args.append(cleaned)
|
||||
return args
|
||||
|
||||
|
||||
def human_chrome_shortcut_arguments(profile_dir, url=None):
|
||||
def human_chrome_shortcut_arguments(profile_dir, url=None, restore_session=False, *, enable_cdp=True):
|
||||
"""Windows .lnk Arguments 字符串(user-data-dir 带引号)。"""
|
||||
profile_abs = os.path.abspath(profile_dir)
|
||||
parts = [f'--user-data-dir="{profile_abs}"', *HUMAN_CHROME_FLAGS]
|
||||
if restore_session:
|
||||
parts.append(RESTORE_LAST_SESSION_FLAG)
|
||||
if enable_cdp:
|
||||
port = cdp_port_for_profile(profile_abs)
|
||||
parts.append(f"--remote-debugging-port={port}")
|
||||
parts.append("--remote-debugging-address=127.0.0.1")
|
||||
cleaned = (url or "").strip()
|
||||
if cleaned:
|
||||
parts.append(cleaned)
|
||||
@@ -191,6 +224,51 @@ def cmd_reveal_profile(account_id):
|
||||
)
|
||||
|
||||
|
||||
def _list_profile_browser_pids(profile_dir: str):
|
||||
"""找出已占用本 Profile 的 chrome/msedge PID(与采集技能同逻辑)。"""
|
||||
import json as _json
|
||||
|
||||
profile_abs = os.path.abspath(profile_dir)
|
||||
needle = os.path.normcase(profile_abs)
|
||||
if sys.platform != "win32":
|
||||
return []
|
||||
ps = (
|
||||
"Get-CimInstance Win32_Process -Filter "
|
||||
"\"name='chrome.exe' or name='msedge.exe'\" |"
|
||||
" Select-Object ProcessId,CommandLine | ConvertTo-Json -Compress"
|
||||
)
|
||||
try:
|
||||
completed = subprocess.run(
|
||||
["powershell", "-NoProfile", "-Command", ps],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=20,
|
||||
check=False,
|
||||
)
|
||||
except Exception:
|
||||
return []
|
||||
raw = (completed.stdout or "").strip()
|
||||
if not raw:
|
||||
return []
|
||||
try:
|
||||
payload = _json.loads(raw)
|
||||
except Exception:
|
||||
return []
|
||||
rows = payload if isinstance(payload, list) else [payload]
|
||||
pids = []
|
||||
for row in rows:
|
||||
if not isinstance(row, dict):
|
||||
continue
|
||||
cmdline = str(row.get("CommandLine") or "")
|
||||
if needle not in os.path.normcase(cmdline):
|
||||
continue
|
||||
try:
|
||||
pids.append(int(row.get("ProcessId")))
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
return sorted(set(pids))
|
||||
|
||||
|
||||
def cmd_open(account_id):
|
||||
"""
|
||||
打开该账号的持久化浏览器,仅用于肉眼核对 / 手工登录 / 抓 DOM。
|
||||
@@ -225,20 +303,70 @@ def cmd_open(account_id):
|
||||
profile_abs = os.path.abspath(profile_dir)
|
||||
os.makedirs(profile_abs, exist_ok=True)
|
||||
|
||||
existing = _list_profile_browser_pids(profile_abs)
|
||||
if existing:
|
||||
log.info(
|
||||
"browser_open_reuse account_id=%s profile_dir=%s pids=%s",
|
||||
account_id,
|
||||
profile_abs,
|
||||
existing,
|
||||
)
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"type": "result",
|
||||
"schema_version": 1,
|
||||
"status": "success",
|
||||
"message": "已复用打开中的浏览器窗口",
|
||||
"success": True,
|
||||
"data": {
|
||||
"account_id": int(target["id"]) if target.get("id") is not None else account_id,
|
||||
"account_label": target.get("account_label"),
|
||||
"browser": "Google Chrome",
|
||||
"browser_exe": browser_exe,
|
||||
"profile_dir": profile_abs,
|
||||
"url": resolve_account_browser_url(target),
|
||||
"pid": existing[0],
|
||||
"reused": True,
|
||||
"pids": existing,
|
||||
},
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
)
|
||||
return
|
||||
|
||||
# 清理 exit_type 等(不写 MAC 保护的 restore_on_startup);有会话时靠 --restore-last-session
|
||||
prefs_result = ensure_session_restore(profile_abs)
|
||||
log.info("browser_open_prefs %s", prefs_result)
|
||||
|
||||
conn = get_conn()
|
||||
try:
|
||||
url = resolve_account_browser_url(target, conn=conn)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
# 与 profile_shortcut 同一套人用参数:独立 user-data-dir 保存登录态
|
||||
cmd = [browser_exe, *human_chrome_launch_args(profile_abs, url)]
|
||||
# 有可恢复会话:不带 URL + --restore-last-session(恢复标签与 Session Cookie)。
|
||||
# 首次/空 Profile:仍打开平台首页便于登录。
|
||||
has_session = profile_has_restorable_session(profile_abs)
|
||||
launch_url = None if has_session else url
|
||||
cdp_port = cdp_port_for_profile(profile_abs)
|
||||
cmd = [
|
||||
browser_exe,
|
||||
*human_chrome_launch_args(
|
||||
profile_abs, launch_url, restore_session=has_session, enable_cdp=True
|
||||
),
|
||||
]
|
||||
|
||||
log.info(
|
||||
"browser_open_launch exe=%s profile_dir=%s url=%s platform=%s",
|
||||
"browser_open_launch exe=%s profile_dir=%s launch_url=%s has_session=%s "
|
||||
"restore_last_session=%s cdp_port=%s platform=%s",
|
||||
browser_exe,
|
||||
profile_abs,
|
||||
url,
|
||||
launch_url or "(restore)",
|
||||
has_session,
|
||||
has_session,
|
||||
cdp_port,
|
||||
target.get("platform_key"),
|
||||
)
|
||||
|
||||
@@ -289,6 +417,10 @@ def cmd_open(account_id):
|
||||
"profile_dir": profile_abs,
|
||||
"url": url,
|
||||
"pid": child.pid,
|
||||
"has_session": has_session,
|
||||
"restore_last_session": has_session,
|
||||
"cdp_port": cdp_port,
|
||||
"session_restore_on_startup": prefs_result.get("restore_after"),
|
||||
},
|
||||
},
|
||||
ensure_ascii=False,
|
||||
|
||||
163
scripts/service/chrome_profile_prefs.py
Normal file
163
scripts/service/chrome_profile_prefs.py
Normal file
@@ -0,0 +1,163 @@
|
||||
"""Chrome/Edge 独立 Profile:启动前清理退出标记,便于会话文件可被恢复。
|
||||
|
||||
注意:``session.restore_on_startup`` 受 Secure Preferences HMAC 保护,
|
||||
裸写 Preferences 会被 Chrome 校验否掉并回落到新标签页。真正强制恢复会话
|
||||
应在启动参数使用 ``--restore-last-session``(见 browser_service)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
from typing import Any, Dict
|
||||
|
||||
from util.logging_config import get_skill_logger
|
||||
|
||||
# Chromium ≤ roughly mid-era: session files lived under Default/
|
||||
_LEGACY_SESSION_FILES = (
|
||||
"Current Session",
|
||||
"Last Session",
|
||||
"Current Tabs",
|
||||
"Last Tabs",
|
||||
)
|
||||
|
||||
|
||||
def profile_has_restorable_session(profile_dir: str) -> bool:
|
||||
"""True when the profile has on-disk session data Chrome can restore.
|
||||
|
||||
Modern Chrome/Edge write ``Default/Sessions/Session_*`` (and ``Tabs_*``).
|
||||
Older builds used ``Default/Current Session`` etc. Either form counts.
|
||||
"""
|
||||
default_dir = os.path.join(os.path.abspath(profile_dir), "Default")
|
||||
if any(
|
||||
os.path.isfile(os.path.join(default_dir, name))
|
||||
for name in _LEGACY_SESSION_FILES
|
||||
):
|
||||
return True
|
||||
|
||||
sessions_dir = os.path.join(default_dir, "Sessions")
|
||||
if not os.path.isdir(sessions_dir):
|
||||
return False
|
||||
try:
|
||||
names = os.listdir(sessions_dir)
|
||||
except OSError:
|
||||
return False
|
||||
return any(
|
||||
name.startswith("Session_") or name.startswith("Tabs_")
|
||||
for name in names
|
||||
if os.path.isfile(os.path.join(sessions_dir, name))
|
||||
)
|
||||
|
||||
|
||||
def preferences_path(profile_dir: str) -> str:
|
||||
return os.path.join(os.path.abspath(profile_dir), "Default", "Preferences")
|
||||
|
||||
|
||||
def local_state_path(profile_dir: str) -> str:
|
||||
return os.path.join(os.path.abspath(profile_dir), "Local State")
|
||||
|
||||
|
||||
def _patch_preferences_dict(data: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""只改不受 Secure Preferences MAC 保护的退出标记;不动 restore_on_startup。"""
|
||||
restore_before = int((data.get("session") or {}).get("restore_on_startup") or 0)
|
||||
exit_before = str((data.get("profile") or {}).get("exit_type") or "")
|
||||
|
||||
profile = data.setdefault("profile", {})
|
||||
if str(profile.get("exit_type") or "").lower() == "crashed":
|
||||
profile["exit_type"] = "Normal"
|
||||
profile["exited_cleanly"] = True
|
||||
|
||||
browser = data.setdefault("browser", {})
|
||||
browser["has_seen_welcome_page"] = True
|
||||
browser["check_default_browser"] = False
|
||||
|
||||
return {"restore_before": restore_before, "exit_type_before": exit_before}
|
||||
|
||||
|
||||
def _patch_local_state(profile_dir: str, log) -> Dict[str, Any]:
|
||||
path = local_state_path(profile_dir)
|
||||
if not os.path.isfile(path):
|
||||
return {"ok": True, "skipped": True, "path": path}
|
||||
try:
|
||||
with open(path, "r", encoding="utf-8") as fh:
|
||||
data = json.load(fh)
|
||||
except Exception as exc:
|
||||
log.warning("chrome_local_state_read_failed path=%s err=%s", path, exc)
|
||||
return {"ok": False, "path": path, "error": str(exc)}
|
||||
|
||||
profile = data.setdefault("profile", {})
|
||||
info = profile.setdefault("info_cache", {}).setdefault("Default", {})
|
||||
info["active_time"] = float(info.get("active_time") or 0.0) or 1.0
|
||||
exited = profile.get("exited_cleanly", True)
|
||||
profile["exited_cleanly"] = True
|
||||
try:
|
||||
with open(path, "w", encoding="utf-8") as fh:
|
||||
json.dump(data, fh, ensure_ascii=False, separators=(",", ":"))
|
||||
except Exception as exc:
|
||||
log.warning("chrome_local_state_write_failed path=%s err=%s", path, exc)
|
||||
return {"ok": False, "path": path, "error": str(exc), "exited_cleanly_before": exited}
|
||||
|
||||
log.info("chrome_local_state_patched path=%s exited_cleanly %s->True", path, exited)
|
||||
return {"ok": True, "path": path, "exited_cleanly_before": exited}
|
||||
|
||||
|
||||
def ensure_session_restore(profile_dir: str) -> Dict[str, Any]:
|
||||
"""启动前清理 exit_type / exited_cleanly(不受 MAC 保护);不写 restore_on_startup。"""
|
||||
log = get_skill_logger()
|
||||
profile_abs = os.path.abspath(profile_dir)
|
||||
prefs = preferences_path(profile_abs)
|
||||
os.makedirs(os.path.dirname(prefs), exist_ok=True)
|
||||
data: Dict[str, Any] = {}
|
||||
existed = os.path.isfile(prefs)
|
||||
if existed:
|
||||
try:
|
||||
with open(prefs, "r", encoding="utf-8") as fh:
|
||||
data = json.load(fh)
|
||||
except Exception:
|
||||
log.exception("chrome_prefs_read_failed path=%s", prefs)
|
||||
data = {}
|
||||
|
||||
meta = _patch_preferences_dict(data)
|
||||
before = int(meta["restore_before"])
|
||||
exit_before = str(meta["exit_type_before"] or "")
|
||||
|
||||
try:
|
||||
with open(prefs, "w", encoding="utf-8") as fh:
|
||||
json.dump(data, fh, ensure_ascii=False, separators=(",", ":"))
|
||||
except Exception as exc:
|
||||
log.warning("chrome_prefs_write_failed path=%s err=%s", prefs, exc)
|
||||
return {
|
||||
"ok": False,
|
||||
"path": prefs,
|
||||
"existed": existed,
|
||||
"restore_before": before,
|
||||
"restore_after": before,
|
||||
"exit_type_before": exit_before,
|
||||
"error": str(exc),
|
||||
}
|
||||
|
||||
after = int((data.get("session") or {}).get("restore_on_startup") or 0)
|
||||
exit_after = str((data.get("profile") or {}).get("exit_type") or "")
|
||||
local = _patch_local_state(profile_abs, log)
|
||||
log.info(
|
||||
"chrome_session_restore_prepared profile_dir=%s prefs=%s existed=%s "
|
||||
"restore_on_startup_unchanged=%s exit_type %s->%s local_state=%s",
|
||||
profile_abs,
|
||||
prefs,
|
||||
existed,
|
||||
after,
|
||||
exit_before or "-",
|
||||
exit_after or "-",
|
||||
local,
|
||||
)
|
||||
return {
|
||||
"ok": True,
|
||||
"path": prefs,
|
||||
"existed": existed,
|
||||
"restore_before": before,
|
||||
"restore_after": after,
|
||||
"exit_type_before": exit_before,
|
||||
"exit_type_after": exit_after,
|
||||
"local_state": local,
|
||||
"prefs_restore_on_startup_touched": False,
|
||||
}
|
||||
@@ -1,6 +1,11 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Lease management CLI commands."""
|
||||
from db.accounts_repo import cleanup_expired_leases, list_active_leases, release_lease
|
||||
from db.accounts_repo import (
|
||||
cleanup_expired_leases,
|
||||
list_active_leases,
|
||||
release_lease,
|
||||
release_lease_by_id,
|
||||
)
|
||||
from service._svc_common import _err_json, _ok_json, _say
|
||||
from util.logging_config import get_skill_logger
|
||||
|
||||
@@ -16,6 +21,41 @@ def cmd_lease_release(lease_token: str) -> None:
|
||||
_say(_err_json("ERROR:LEASE_NOT_FOUND", "未找到活跃的租约,或租约已释放/过期。"))
|
||||
|
||||
|
||||
def cmd_lease_force_release(lease_id: int) -> None:
|
||||
"""lease force-release --id <lease_row_id> — data-management row action."""
|
||||
log = get_skill_logger()
|
||||
log.info("cli_start subcommand=lease_force_release lease_id=%s", lease_id)
|
||||
try:
|
||||
lid = int(lease_id)
|
||||
except (TypeError, ValueError):
|
||||
_say(_err_json("ERROR:CLI_BAD_ARGS", "租约编号必须是数字。"))
|
||||
return
|
||||
if lid <= 0:
|
||||
_say(_err_json("ERROR:CLI_BAD_ARGS", "租约编号必须是正整数。"))
|
||||
return
|
||||
released = release_lease_by_id(lid)
|
||||
if not released:
|
||||
_say(
|
||||
_err_json(
|
||||
"ERROR:LEASE_NOT_FOUND",
|
||||
"未找到可释放的活跃租约(可能已释放、已过期清理,或不存在)。",
|
||||
)
|
||||
)
|
||||
return
|
||||
_say(
|
||||
_ok_json(
|
||||
{
|
||||
"id": released["id"],
|
||||
"account_id": released["account_id"],
|
||||
"holder": released.get("holder") or "",
|
||||
"purpose": released.get("purpose") or "",
|
||||
"status": "released",
|
||||
"message": "已强制释放租约,该账号可被其它任务占用。",
|
||||
}
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def cmd_lease_list(active_only: bool = False) -> None:
|
||||
"""lease list [--active]"""
|
||||
log = get_skill_logger()
|
||||
|
||||
@@ -18,16 +18,76 @@ class TestPlaywrightLaunchHelpers:
|
||||
assert "--start-maximized" in args
|
||||
|
||||
|
||||
class TestEnsureSessionRestoreDoesNotTouchProtectedPref:
|
||||
def test_leaves_restore_on_startup_unchanged(self, tmp_path, fake_env):
|
||||
from pathlib import Path
|
||||
|
||||
from service.chrome_profile_prefs import ensure_session_restore, preferences_path
|
||||
from util.logging_config import setup_skill_logging
|
||||
|
||||
setup_skill_logging("account-manager", "openclaw.skill.account_manager_test")
|
||||
|
||||
profile = tmp_path / "prof"
|
||||
prefs = Path(preferences_path(str(profile)))
|
||||
prefs.parent.mkdir(parents=True, exist_ok=True)
|
||||
prefs.write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"session": {"restore_on_startup": 5},
|
||||
"profile": {"exit_type": "Crashed", "exited_cleanly": False},
|
||||
}
|
||||
),
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
result = ensure_session_restore(str(profile))
|
||||
assert result["ok"] is True
|
||||
assert result["prefs_restore_on_startup_touched"] is False
|
||||
data = json.loads(prefs.read_text(encoding="utf-8"))
|
||||
assert data["session"]["restore_on_startup"] == 5
|
||||
assert data["profile"]["exit_type"] == "Normal"
|
||||
assert data["profile"]["exited_cleanly"] is True
|
||||
|
||||
|
||||
class TestProfileHasRestorableSession:
|
||||
def test_empty_profile_false(self, tmp_path):
|
||||
from service.chrome_profile_prefs import profile_has_restorable_session
|
||||
|
||||
assert profile_has_restorable_session(str(tmp_path / "prof")) is False
|
||||
|
||||
def test_legacy_current_session(self, tmp_path):
|
||||
from service.chrome_profile_prefs import profile_has_restorable_session
|
||||
|
||||
default = tmp_path / "prof" / "Default"
|
||||
default.mkdir(parents=True)
|
||||
(default / "Current Session").write_bytes(b"x")
|
||||
assert profile_has_restorable_session(str(tmp_path / "prof")) is True
|
||||
|
||||
def test_modern_sessions_dir(self, tmp_path):
|
||||
from service.chrome_profile_prefs import profile_has_restorable_session
|
||||
|
||||
sessions = tmp_path / "prof" / "Default" / "Sessions"
|
||||
sessions.mkdir(parents=True)
|
||||
(sessions / "Session_13434010951759956").write_bytes(b"sess")
|
||||
assert profile_has_restorable_session(str(tmp_path / "prof")) is True
|
||||
|
||||
def test_modern_tabs_only(self, tmp_path):
|
||||
from service.chrome_profile_prefs import profile_has_restorable_session
|
||||
|
||||
sessions = tmp_path / "prof" / "Default" / "Sessions"
|
||||
sessions.mkdir(parents=True)
|
||||
(sessions / "Tabs_13434010952144072").write_bytes(b"tabs")
|
||||
assert profile_has_restorable_session(str(tmp_path / "prof")) is True
|
||||
|
||||
|
||||
class TestCmdOpenDirectBrowser:
|
||||
"""account open = same-process Chrome/Edge launch (like reveal-profile)."""
|
||||
|
||||
def test_cmd_open_launches_browser_exe(self, clean_db, tmp_path, capsys, monkeypatch):
|
||||
def _seed_account(self, clean_db, tmp_path, profile):
|
||||
from db.accounts_repo import insert_account
|
||||
from service import browser_service
|
||||
from util.platforms import seed_platforms
|
||||
|
||||
seed_platforms(clean_db)
|
||||
profile = tmp_path / "prof"
|
||||
aid = insert_account(
|
||||
clean_db,
|
||||
platform_key="sohu",
|
||||
@@ -45,7 +105,9 @@ class TestCmdOpenDirectBrowser:
|
||||
auth_strategy="password_auto",
|
||||
)
|
||||
clean_db.commit()
|
||||
return aid
|
||||
|
||||
def _patch_launch(self, monkeypatch, browser_service, tmp_path):
|
||||
fake_exe = str(tmp_path / "chrome.exe")
|
||||
monkeypatch.setattr(
|
||||
browser_service,
|
||||
@@ -64,6 +126,14 @@ class TestCmdOpenDirectBrowser:
|
||||
return FakeProc()
|
||||
|
||||
monkeypatch.setattr(browser_service.subprocess, "Popen", fake_popen)
|
||||
return fake_exe, spawned
|
||||
|
||||
def test_cmd_open_launches_browser_exe(self, clean_db, tmp_path, capsys, monkeypatch):
|
||||
from service import browser_service
|
||||
|
||||
profile = tmp_path / "prof"
|
||||
aid = self._seed_account(clean_db, tmp_path, profile)
|
||||
fake_exe, spawned = self._patch_launch(monkeypatch, browser_service, tmp_path)
|
||||
|
||||
browser_service.cmd_open(str(aid))
|
||||
out = capsys.readouterr().out.strip()
|
||||
@@ -88,6 +158,30 @@ class TestCmdOpenDirectBrowser:
|
||||
assert "open_child_runner" not in joined
|
||||
assert "python" not in joined.lower()
|
||||
|
||||
def test_cmd_open_skips_url_when_modern_sessions_exist(
|
||||
self, clean_db, tmp_path, capsys, monkeypatch
|
||||
):
|
||||
"""Modern Chrome Sessions/ must restore via --restore-last-session, no homepage URL."""
|
||||
from service import browser_service
|
||||
|
||||
profile = tmp_path / "prof"
|
||||
sessions = profile / "Default" / "Sessions"
|
||||
sessions.mkdir(parents=True)
|
||||
(sessions / "Session_13434010951759956").write_bytes(b"sess")
|
||||
aid = self._seed_account(clean_db, tmp_path, profile)
|
||||
_fake_exe, spawned = self._patch_launch(monkeypatch, browser_service, tmp_path)
|
||||
|
||||
browser_service.cmd_open(str(aid))
|
||||
out = capsys.readouterr().out.strip()
|
||||
payload = json.loads(out.splitlines()[-1])
|
||||
|
||||
assert payload["success"] is True
|
||||
assert payload["data"]["has_session"] is True
|
||||
assert payload["data"]["restore_last_session"] is True
|
||||
assert "https://example.com" not in spawned["cmd"]
|
||||
assert "--restore-last-session" in spawned["cmd"]
|
||||
assert spawned["cmd"][-1] == "--restore-last-session" or spawned["cmd"][-1].startswith("--")
|
||||
|
||||
|
||||
class TestHumanChromeLaunchArgs:
|
||||
def test_flags_then_url(self, tmp_path):
|
||||
@@ -98,9 +192,19 @@ class TestHumanChromeLaunchArgs:
|
||||
assert args[0].startswith("--user-data-dir=")
|
||||
for flag in HUMAN_CHROME_FLAGS:
|
||||
assert flag in args
|
||||
assert "--restore-last-session" not in args
|
||||
assert any(a.startswith("--remote-debugging-port=") for a in args)
|
||||
assert args[-1] == "https://chat.deepseek.com"
|
||||
assert "--enable-automation" not in args
|
||||
|
||||
def test_restore_session_flag_without_url(self, tmp_path):
|
||||
from service.browser_service import human_chrome_launch_args
|
||||
|
||||
args = human_chrome_launch_args(str(tmp_path / "prof"), None, restore_session=True)
|
||||
assert "--restore-last-session" in args
|
||||
assert any(a.startswith("--remote-debugging-port=") for a in args)
|
||||
assert not any(a.startswith("http") for a in args)
|
||||
|
||||
def test_shortcut_arguments_quote_profile_and_include_url(self, tmp_path):
|
||||
from service.browser_service import human_chrome_shortcut_arguments
|
||||
|
||||
@@ -110,8 +214,25 @@ class TestHumanChromeLaunchArgs:
|
||||
assert '--user-data-dir="' in text
|
||||
assert "--start-maximized" in text
|
||||
assert "--no-first-run" in text
|
||||
assert "--restore-last-session" not in text
|
||||
assert "--remote-debugging-port=" in text
|
||||
assert text.endswith("https://example.com")
|
||||
|
||||
def test_shortcut_restore_session(self, tmp_path):
|
||||
from service.browser_service import human_chrome_shortcut_arguments
|
||||
|
||||
text = human_chrome_shortcut_arguments(str(tmp_path / "p"), None, restore_session=True)
|
||||
assert "--restore-last-session" in text
|
||||
assert "--remote-debugging-port=" in text
|
||||
assert "http" not in text
|
||||
|
||||
def test_cdp_port_stable_for_profile(self, tmp_path):
|
||||
from service.browser_service import cdp_port_for_profile
|
||||
|
||||
p = str(tmp_path / "prof")
|
||||
assert cdp_port_for_profile(p) == cdp_port_for_profile(p)
|
||||
assert 9330 <= cdp_port_for_profile(p) < 9390
|
||||
|
||||
|
||||
class TestResolveChromiumChannel:
|
||||
"""resolve_chromium_channel returns a channel string when browsers exist."""
|
||||
|
||||
@@ -144,6 +144,67 @@ class TestLeaseRelease:
|
||||
assert result["success"] is False
|
||||
assert result["error"]["code"] == "ERROR:LEASE_NOT_FOUND"
|
||||
|
||||
def test_force_release_by_id(self, clean_db):
|
||||
"""force-release by lease row id frees the account for pick-web."""
|
||||
from db.accounts_repo import acquire_lease, find_account_ids, release_lease_by_id
|
||||
from service.account_service import cmd_account_add_web, cmd_lease_force_release
|
||||
import io, sys
|
||||
|
||||
cmd_account_add_web(
|
||||
"maersk", "force-release@maersk.com", "email", "FR", "t1", "production", "booking",
|
||||
None, None, None, None,
|
||||
)
|
||||
ids = find_account_ids("maersk")
|
||||
acc_id = ids[0]
|
||||
lease = acquire_lease(
|
||||
account_id=acc_id,
|
||||
lease_token="f1e2d3c4b5a697887766554433221100",
|
||||
holder="stuck-holder",
|
||||
purpose="download",
|
||||
ttl_sec=900,
|
||||
)
|
||||
assert find_account_ids("maersk") == []
|
||||
|
||||
released = release_lease_by_id(int(lease["id"]))
|
||||
assert released is not None
|
||||
assert released["status"] == "released"
|
||||
assert acc_id in find_account_ids("maersk")
|
||||
|
||||
# Re-acquire and exercise CLI command output shape
|
||||
lease2 = acquire_lease(
|
||||
account_id=acc_id,
|
||||
lease_token="a0b1c2d3e4f5061728394a5b6c7d8e9f",
|
||||
holder="stuck-2",
|
||||
purpose="download",
|
||||
ttl_sec=900,
|
||||
)
|
||||
buf = io.StringIO()
|
||||
old = sys.stdout
|
||||
sys.stdout = buf
|
||||
try:
|
||||
cmd_lease_force_release(int(lease2["id"]))
|
||||
finally:
|
||||
sys.stdout = old
|
||||
line = buf.getvalue().strip().splitlines()[-1]
|
||||
result = json.loads(line)
|
||||
assert result.get("success") is True
|
||||
assert (result.get("data") or {}).get("status") == "released"
|
||||
|
||||
def test_force_release_inactive_fails(self, clean_db):
|
||||
from service.account_service import cmd_lease_force_release
|
||||
import io, sys
|
||||
|
||||
captured = io.StringIO()
|
||||
sys.stdout = captured
|
||||
try:
|
||||
cmd_lease_force_release(999999)
|
||||
finally:
|
||||
sys.stdout = sys.__stdout__
|
||||
|
||||
result = json.loads(captured.getvalue())
|
||||
assert result["success"] is False
|
||||
assert result["error"]["code"] == "ERROR:LEASE_NOT_FOUND"
|
||||
|
||||
|
||||
class TestLeaseCleanup:
|
||||
"""lease cleanup / expired lease handling."""
|
||||
|
||||
@@ -78,7 +78,22 @@ class TestRowOpenActions(unittest.TestCase):
|
||||
self.assertEqual(copy.get("placements"), ["row"])
|
||||
self.assertEqual(copy.get("interaction"), "direct")
|
||||
self.assertFalse(copy.get("replaces"))
|
||||
steps = copy.get("steps") or []
|
||||
|
||||
def test_lease_force_release_row_action(self) -> None:
|
||||
action = _by_id(_load_actions(), "lease-force-release")
|
||||
self.assertEqual(action.get("label"), "强制释放租约")
|
||||
self.assertEqual(action.get("placements"), ["row"])
|
||||
self.assertEqual(action.get("interaction"), "confirm")
|
||||
self.assertEqual(action.get("executionProfile"), "sync")
|
||||
bind = action.get("bind") or {}
|
||||
self.assertEqual(bind.get("tables"), ["account_leases"])
|
||||
self.assertEqual(bind.get("inputMapping"), {"leaseId": "$row.$pk"})
|
||||
self.assertEqual(bind.get("visibleWhen"), {"status": "active"})
|
||||
self.assertEqual(
|
||||
(action.get("entrypoint") or {}).get("args"),
|
||||
["force-release", "--id", "{{leaseId}}"],
|
||||
)
|
||||
steps = action.get("steps") or []
|
||||
self.assertTrue(any(s.get("do") == "reloadTable" for s in steps))
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user