From 0a2d700e852290144b331c371854eef16b56f098 Mon Sep 17 00:00:00 2001 From: taisuii <93462725+taisuii@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:17:10 +0800 Subject: [PATCH 01/20] =?UTF-8?q?feat:=20=E9=9D=A2=E6=9D=BF=E8=AE=BE?= =?UTF-8?q?=E5=A4=87=E7=AE=A1=E7=90=86=E4=B8=8E=E6=B3=A8=E5=85=A5=E8=8C=83?= =?UTF-8?q?=E5=9B=B4=E5=85=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit connections.json 持久化 selected 与每设备 session_token(0600 不变); panel 增加 /api/devices(列表/添加/删除/切换/存 token)与 /api/apps、 /api/injection-scope、/api/apps/relaunch 中转,token 跟随选中设备; 零设备也可启动面板。页面在会话弹层加设备区(在线/配对/切换/增删), 新增注入页:分组应用列表、搜索、注入开关、运行中改动标待重启并提供 重启并应用。 --- src/idh/cli.py | 172 ++++++++++++++++++++++++++++++++++++---- src/idh/config.py | 65 +++++++++++++-- src/idh/panel-device.js | 2 + src/idh/panel.html | 104 +++++++++++++++++++++++- tests/test_config.py | 28 ++++++- 5 files changed, 347 insertions(+), 24 deletions(-) diff --git a/src/idh/cli.py b/src/idh/cli.py index 86d75be..9262fd3 100755 --- a/src/idh/cli.py +++ b/src/idh/cli.py @@ -21,8 +21,11 @@ clear_endpoints, config_path, load_saved_endpoints, + load_selected, remove_endpoint, save_endpoint, + save_endpoint_token, + save_selected, ) from .gateway import ( GatewayServer, @@ -799,6 +802,11 @@ def _run_auto_update(args: argparse.Namespace) -> None: _PANEL_SESSION_ROUTE = re.compile(r"/api/sessions(?:/[A-Za-z0-9_-]{1,64}(?:/events)?)?") _PANEL_SETTINGS_ROUTE = "/api/session-settings" _PANEL_SETTINGS_MAX_BYTES = 4096 +# 设备侧注入接口(GET 读 / POST 写)与本机设备注册表 +_PANEL_DEVICE_READ = {"/api/apps", "/api/injection-scope"} +_PANEL_DEVICE_WRITE = {"/api/injection-scope", "/api/apps/relaunch"} +_PANEL_DEVICES_ROUTE = "/api/devices" +_BUNDLE_ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,254}") def _panel_request( @@ -824,10 +832,9 @@ def _run_panel(args: argparse.Namespace) -> int: endpoints = _manual_endpoints(args.endpoint, include_saved=not args.no_saved) try: endpoint = _resolve_device(endpoints, None, command="panel") - except SystemExit as exc: - print(str(exc), file=sys.stderr) - return 1 - if endpoint.kind != "device": + except SystemExit: + endpoint = None # 零设备启动:面板照常起,由页面里的设备入口添加 + if endpoint is not None and endpoint.kind != "device": print("idh: panel serves a device connection", file=sys.stderr) return 2 host, _, port_text = args.bind.rpartition(":") @@ -839,12 +846,45 @@ def _run_panel(args: argparse.Namespace) -> int: except ValueError: print("idh: --bind must use 127.0.0.1 or localhost and a valid port", file=sys.stderr) return 2 + saved_selected = load_selected() + if saved_selected: + for saved in load_saved_endpoints(): + if saved.mcp_url.casefold() == saved_selected.casefold() and saved.kind == "device": + endpoint = saved + break + current = {"endpoint": endpoint} + + def device_token(ep: AppEndpoint) -> str: + saved = ep.properties.get("session_token") or "" + return saved or os.environ.get("IDH_DEVICE_SESSION_TOKEN", "").strip() + + def device_records() -> dict: + saved = [item for item in load_saved_endpoints() if item.kind == "device"] + probed = _probed_endpoints(saved) + selected = current["endpoint"].mcp_url + return { + "devices": [ + { + "id": item.mcp_url, + "address": item.base_url, + "kind": item.kind, + "online": item.properties.get("status") == "online", + "selected": item.mcp_url == selected, + "paired": bool(device_token(item)), + } + for item in probed + ], + "selected": selected, + } + try: - code, health = _panel_request(endpoint, "/health") - if code != 200 or not isinstance(health, dict) or health.get("service") != "idhjd": - raise UsageError("idh: panel serves a device connection") + if current["endpoint"] is not None: + code, health = _panel_request(current["endpoint"], "/health") + if code != 200 or not isinstance(health, dict) or health.get("service") != "idhjd": + raise UsageError("idh: panel serves a device connection") panel_files = files("idh") - metadata = f''.encode() + device_url = current["endpoint"].base_url if current["endpoint"] else "" + metadata = f''.encode() page = panel_files.joinpath("panel.html").read_bytes().replace( b"", metadata ) @@ -897,11 +937,69 @@ def relay_settings(self, body: bytes | None = None) -> None: return self.write_json(code, data if isinstance(data, dict) else {"error": "settings_unavailable"}) + def device_action(self, body: bytes) -> None: + try: + request = json.loads(body) + except (UnicodeDecodeError, json.JSONDecodeError): + request = None + if not isinstance(request, dict): + self.write_json(400, {"error": "invalid_device_request"}) + return + action = request.get("action") + if action == "add": + try: + endpoint = AppEndpoint.from_url(str(request.get("address") or "")) + except ValueError: + self.write_json(400, {"error": "invalid_address"}) + return + probed = probe_endpoint(endpoint, timeout=3) + if probed.properties.get("status") == "online" and probed.kind != "device": + self.write_json(400, {"error": "not_a_device"}) + return + save_endpoint(probed) + self.write_json(200, device_records()) + return + target = str(request.get("id") or "") + if action == "select": + for saved in load_saved_endpoints(): + if saved.kind == "device" and saved.mcp_url.casefold() == target.casefold(): + save_selected(saved.mcp_url) + current["endpoint"] = saved + self.write_json(200, device_records()) + return + self.write_json(404, {"error": "unknown_device"}) + return + if action == "remove": + try: + removed = remove_endpoint(target) + except ValueError: + removed = False + if not removed: + self.write_json(404, {"error": "unknown_device"}) + return + if current["endpoint"] and current["endpoint"].mcp_url.casefold() == target.casefold(): + save_selected(next((e.mcp_url for e in load_saved_endpoints() if e.kind == "device"), "")) + current["endpoint"] = next((e for e in load_saved_endpoints() if e.kind == "device"), None) + self.write_json(200, device_records()) + return + if action == "token": + token = str(request.get("token") or "").strip() + if not token or not token.isascii() or any(ch.isspace() for ch in token): + self.write_json(400, {"error": "invalid_token"}) + return + if not save_endpoint_token(target, token): + self.write_json(404, {"error": "unknown_device"}) + return + self.write_json(200, device_records()) + return + self.write_json(400, {"error": "invalid_device_request"}) + def do_POST(self) -> None: if not self.valid_host(): self.send_error(400) return - if self.path != _PANEL_SETTINGS_ROUTE: + allowed = {_PANEL_SETTINGS_ROUTE, _PANEL_DEVICES_ROUTE} | _PANEL_DEVICE_WRITE + if self.path not in allowed: self.send_error(404) return if self.headers.get_all("Origin") != [f"http://{self.headers['Host']}"]: @@ -925,7 +1023,45 @@ def do_POST(self) -> None: if len(body) != length: self.write_json(400, {"error": "incomplete_settings"}) return - self.relay_settings(body) + if self.path == _PANEL_SETTINGS_ROUTE: + self.relay_settings(body) + return + if self.path == _PANEL_DEVICES_ROUTE: + self.device_action(body) + return + endpoint = current["endpoint"] + token = device_token(endpoint) if endpoint else "" + if not endpoint or not token: + self.write_json(401, {"error": "session_pairing_required"}) + return + try: + request = json.loads(body) + except (UnicodeDecodeError, json.JSONDecodeError): + request = None + if not isinstance(request, dict): + self.write_json(400, {"error": "invalid_request"}) + return + if self.path == "/api/apps/relaunch": + bundle = str(request.get("bundleId") or "") + if not _BUNDLE_ID.fullmatch(bundle) or bundle.startswith("com.apple."): + self.write_json(400, {"error": "invalid_bundle_id"}) + return + else: + ids = [request.get(key) for key in ("add", "remove")] + if any(not isinstance(value, list) or len(value) > 256 or + any(not _BUNDLE_ID.fullmatch(str(item)) for item in value) + for value in ids): + self.write_json(400, {"error": "invalid_bundle_id"}) + return + try: + code, data = _panel_request(endpoint, self.path, token, body=body) + except (HTTPException, OSError, ValueError, UsageError): + self.write_json(502, {"error": "device_unavailable"}) + return + if code not in {200, 400, 401, 403, 404, 409, 500}: + self.write_json(502, {"error": "device_unavailable"}) + return + self.write_json(code, data if isinstance(data, dict) else {"error": "device_unavailable"}) def do_GET(self) -> None: if not self.valid_host(): @@ -934,6 +1070,9 @@ def do_GET(self) -> None: if self.path == _PANEL_SETTINGS_ROUTE: self.relay_settings() return + if self.path == _PANEL_DEVICES_ROUTE: + self.write_json(200, device_records()) + return try: target = urlsplit(self.path) except ValueError: @@ -950,15 +1089,20 @@ def do_GET(self) -> None: kind = "text/html; charset=utf-8" elif not target.query and target.path in assets: body, kind = assets[target.path] - elif session_route or self.path == "/health": + elif session_route or self.path == "/health" or ( + not target.query and target.path in _PANEL_DEVICE_READ + ): + if current["endpoint"] is None: + self.send_error(502) + return token = "" - if session_route: - token = os.environ.get("IDH_DEVICE_SESSION_TOKEN", "").strip() + if session_route or target.path in _PANEL_DEVICE_READ: + token = device_token(current["endpoint"]) if not token: self.send_error(401) return try: - code, data = _panel_request(endpoint, self.path, token) + code, data = _panel_request(current["endpoint"], self.path, token) except (HTTPException, OSError, ValueError, UsageError): self.send_error(502) return diff --git a/src/idh/config.py b/src/idh/config.py index 8905f75..28e1419 100755 --- a/src/idh/config.py +++ b/src/idh/config.py @@ -56,9 +56,11 @@ def load_saved_endpoints(path: Path | None = None) -> list[AppEndpoint]: kind = item.get("kind") if kind is not None and kind not in _KINDS: raise ValueError(f"connection config has an unknown kind: {target}") - loaded.append( - AppEndpoint.from_url(url).with_kind(kind if isinstance(kind, str) else None) - ) + endpoint = AppEndpoint.from_url(url).with_kind(kind if isinstance(kind, str) else None) + token = item.get("session_token") + if isinstance(token, str) and token: + endpoint = endpoint.with_properties({"session_token": token}) + loaded.append(endpoint) return loaded except ValueError as exc: if str(exc).startswith("connection config"): @@ -111,19 +113,68 @@ def clear_endpoints(path: Path | None = None) -> int: return len(existing) -def _write_endpoints(endpoints: Iterable[AppEndpoint], target: Path) -> None: +def load_selected(path: Path | None = None) -> str | None: + target = path or config_path() + try: + data = json.loads(target.read_text(encoding="utf-8")) + except (OSError, UnicodeError, json.JSONDecodeError): + return None + selected = data.get("selected") if isinstance(data, dict) else None + return selected if isinstance(selected, str) and selected else None + + +def save_selected(value: str, path: Path | None = None) -> None: + target = path or config_path() + _write_endpoints(load_saved_endpoints(target), target, selected=value) + + +def save_endpoint_token(value: str, token: str, path: Path | None = None) -> bool: + target = path or config_path() + canonical = AppEndpoint.from_url(value).mcp_url.casefold() + endpoints = load_saved_endpoints(target) + updated = False + items: list[AppEndpoint] = [] + for item in endpoints: + if item.mcp_url.casefold() == canonical: + item = item.with_properties({"session_token": token}) + updated = True + items.append(item) + if not updated: + return False + _write_endpoints(items, target) + return True + + +def _write_endpoints( + endpoints: Iterable[AppEndpoint], target: Path, *, selected: str | None = None +) -> None: target.parent.mkdir(parents=True, exist_ok=True) + if selected is None and target.exists(): + # 其它写路径不改当前选中,读旧文件保留 + try: + data = json.loads(target.read_text(encoding="utf-8")) + if isinstance(data, dict) and isinstance(data.get("selected"), str): + selected = data["selected"] + except (OSError, UnicodeError, json.JSONDecodeError): + pass items = sorted(endpoints, key=lambda item: item.mcp_url.casefold()) - if any(item.kind for item in items): - payload = { + if any(item.kind or item.properties.get("session_token") for item in items): + payload: dict[str, object] = { "version": CONFIG_VERSION_KIND, "endpoints": [ - {"url": item.mcp_url, **({"kind": item.kind} if item.kind else {})} + { + "url": item.mcp_url, + **({"kind": item.kind} if item.kind else {}), + **({"session_token": item.properties["session_token"]} + if item.properties.get("session_token") else {}), + } for item in items ], } else: payload = {"version": CONFIG_VERSION, "endpoints": [item.mcp_url for item in items]} + if selected: + payload["selected"] = selected fd, temporary = tempfile.mkstemp(prefix=f".{target.name}.", dir=target.parent, text=True) try: with os.fdopen(fd, "w", encoding="utf-8") as handle: diff --git a/src/idh/panel-device.js b/src/idh/panel-device.js index 07e02c2..e0d8140 100644 --- a/src/idh/panel-device.js +++ b/src/idh/panel-device.js @@ -256,6 +256,8 @@ const {pathname, searchParams} = new URL(url, location.origin); const selection = Number(searchParams.get("cat") ?? -1); const method = options.method || "GET"; + // 设备管理与注入范围:由本机面板服务直接处理/中转,不走会话适配 + if (/^\/api\/(apps|injection-scope|devices)(\/|$)/.test(pathname)) return realFetch(url, options); try { if (method === "GET" && pathname === "/api/settings/export") return await deviceSettings(); if (method === "POST" && pathname === "/api/settings/import") return await deviceSettings(options.body); diff --git a/src/idh/panel.html b/src/idh/panel.html index 1e03692..e833bc2 100644 --- a/src/idh/panel.html +++ b/src/idh/panel.html @@ -86,6 +86,10 @@ .dropdown-item[aria-checked=true],.dropdown-item[aria-selected=true] { background:var(--active); color:var(--blue) } .dropdown-item span:first-child { min-width:0; overflow-wrap:anywhere } .dropdown-sub { display:block; color:var(--muted); font-size:11px; margin-top:2px } + .device-add { display:flex; gap:6px; padding:4px 9px 9px } + .device-add input { flex:1; min-width:0; font:inherit; font-size:12px; padding:5px 8px; border:1px solid var(--line); border-radius:5px; background:var(--bg); color:var(--ink) } + .device-remove { color:var(--muted); padding:2px 7px; border-radius:4px; cursor:pointer } + .device-remove:hover { background:var(--surface-3); color:var(--ink) } .dropdown-divider { height:1px; background:var(--line); margin:5px 6px } .proc-details { display:grid; grid-template-columns:auto minmax(0,1fr); gap:6px 12px; margin:0; padding:4px 10px 10px; font-size:11.5px } .proc-details dt { color:var(--muted) } @@ -303,6 +307,12 @@ +
+

注入范围

+
+
+ +
+ + +
应用Bundle ID状态注入
+
@@ -465,7 +485,8 @@ ["crypto","加解密","code",[0,1,2,3]], ["sys","系统","box",[4,5]], ["net","网络","terminal",[6]], ["keychain","Keychain","info",[7]], ["other","其他","list",[8]], ["files","文件","box",null], - ["symbols","符号","code",null], ["dump","Dump","download",null] + ["symbols","符号","code",null], ["dump","Dump","download",null], + ["inject","注入","play",null] ]; const fields = [ ["maxRecords","单会话摘要条数","条",1,2000,1,"setMaxEntries"], @@ -740,7 +761,8 @@ $("toolbar").hidden=!eventTab; $("workarea").hidden=!eventTab; $("toolWorkspace").hidden=eventTab; - for(const [tab,id] of Object.entries({files:"fileWorkspace",symbols:"symbolWorkspace",dump:"dumpWorkspace"})) $(id).hidden=state.tab!==tab; + for(const [tab,id] of Object.entries({files:"fileWorkspace",symbols:"symbolWorkspace",dump:"dumpWorkspace",inject:"injectWorkspace"})) $(id).hidden=state.tab!==tab; + if(state.tab==="inject") loadInject(); if(!eventTab) { resetByteOwner(); currentFiltered=[];shownRows=[]; @@ -1243,6 +1265,84 @@ } }); + // ---- 设备管理 + 注入范围 ---- + const post=(body)=>fetch("/api/devices",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(body)}).then((r)=>r.json()); + let deviceRows=[]; + function renderDevices() { + $("idh-devices").innerHTML=deviceRows.length?deviceRows.map((d)=>{ + const sub=(d.online?"在线":"离线")+(d.paired?"":" · 未配对"); + return ''; + }).join(""):''; + } + async function loadDevices() { + try{const data=await (await fetch("/api/devices")).json();deviceRows=data.devices||[];}catch{deviceRows=[];} + renderDevices(); + } + $("processBtn").addEventListener("click",loadDevices); + $("idh-devices").addEventListener("click",async(event)=>{ + const remove=event.target.closest("[data-remove]"); + if(remove){event.stopPropagation();await post({action:"remove",id:remove.dataset.remove});loadDevices();return;} + const row=event.target.closest("[data-device]"); + if(row && !row.getAttribute("aria-selected").includes("true")){ + const data=await post({action:"select",id:row.dataset.device}); + if(data.error){loadDevices();return;} + location.reload(); + } + }); + $("deviceAddBtn").addEventListener("click",async()=>{ + const address=$("deviceAddr").value.trim(); + if(!address)return; + const data=await post({action:"add",address}); + $("deviceAddr").value=data.error?"":""; + loadDevices(); + }); + $("deviceAddr").addEventListener("keydown",(event)=>{if(event.key==="Enter")$("deviceAddBtn").click();}); + + let injectData=null, injectAt=0, injectPending=new Set(); + function injectRow(app,scope) { + const inScope=scope.includes(app.bundleId), sys=app.kind==="system"||app.bundleId.startsWith("com.apple."); + const pending=injectPending.has(app.bundleId); + return ''+esc(app.name)+''+(app.running?' 运行中':"")+(pending?' 待重启':"")+''+ + ''+esc(app.bundleId)+''+esc(app.kind==="user"?"已装":app.kind==="jb"?"越狱":"系统")+''+ + (sys?'不可注入': + ''+ + (pending?' ':""))+''; + } + function renderInject() { + if(!injectData){$("injectRows").innerHTML='正在读取…';return;} + if(injectData.error){$("injectError").hidden=false;$("injectError").textContent="注入范围读取失败:"+injectData.error;$("injectRows").innerHTML="";return;} + $("injectError").hidden=true; + const q=($("injectQ").value||"").trim().toLowerCase(), scope=injectData.scope||[]; + const apps=(injectData.apps||[]).filter((a)=>!q||(a.name+" "+a.bundleId).toLowerCase().includes(q)); + $("injectRows").innerHTML=apps.length?apps.map((a)=>injectRow(a,scope)).join(""):'没有匹配的应用'; + } + async function loadInject(force) { + if(!force && Date.now()-injectAt<3000)return; + injectAt=Date.now(); + try{injectData=await (await fetch("/api/apps")).json();}catch{injectData={error:"device_unavailable"};} + renderInject(); + } + $("injectRefresh").addEventListener("click",()=>loadInject(true)); + $("injectQ").addEventListener("input",renderInject); + $("injectRows").addEventListener("change",async(event)=>{ + const box=event.target.closest("[data-inject]");if(!box)return; + box.disabled=true; + const id=box.dataset.inject, action=box.checked?"add":"remove"; + const data=await (await fetch("/api/injection-scope",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({[action]:[id]})})).json(); + if(data.error){box.disabled=false;box.checked=!box.checked;return;} + const app=(injectData?.apps||[]).find((a)=>a.bundleId===id); + if(app&&app.running)injectPending.add(id); + injectData.scope=data.scope||injectData.scope; + renderInject(); + }); + $("injectRows").addEventListener("click",async(event)=>{ + const btn=event.target.closest("[data-relaunch]");if(!btn)return; + btn.disabled=true; + await fetch("/api/apps/relaunch",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({bundleId:btn.dataset.relaunch})}); + injectPending.delete(btn.dataset.relaunch); + setTimeout(()=>loadInject(true),1500); + }); + buildTabs();setWidth(view.width);setMenu("");render(true);pageReady=true; refresh(true); if(prefs.advancedFilters)setMenu("filterMenu"); diff --git a/tests/test_config.py b/tests/test_config.py index 7851246..8b57c59 100755 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -5,7 +5,15 @@ import pytest -from idh.config import clear_endpoints, load_saved_endpoints, remove_endpoint, save_endpoint +from idh.config import ( + clear_endpoints, + load_saved_endpoints, + load_selected, + remove_endpoint, + save_endpoint, + save_endpoint_token, + save_selected, +) from idh.models import AppEndpoint @@ -59,6 +67,24 @@ def test_same_address_updates_kind_and_keeps_old_files(tmp_path) -> None: assert load_saved_endpoints(path)[0].kind == "device" +def test_selected_and_session_token_round_trip(tmp_path) -> None: + path = tmp_path / "connections.json" + save_endpoint(AppEndpoint.from_url("192.168.1.10:8088").with_kind("device"), path) + save_endpoint(AppEndpoint.from_url("192.168.1.11:8088").with_kind("device"), path) + + save_selected("http://192.168.1.11:8088/api/mcp", path) + assert load_selected(path) == "http://192.168.1.11:8088/api/mcp" + # 无关写(增删端点)不清掉选中 + save_endpoint(AppEndpoint.from_url("192.168.1.12:8088").with_kind("device"), path) + assert load_selected(path) == "http://192.168.1.11:8088/api/mcp" + + assert save_endpoint_token("192.168.1.11:8088", "tok-abc", path) is True + assert save_endpoint_token("192.168.1.99:8088", "tok-abc", path) is False + loaded = {item.mcp_url: item for item in load_saved_endpoints(path)} + assert loaded["http://192.168.1.11:8088/api/mcp"].properties["session_token"] == "tok-abc" + assert "session_token" not in loaded["http://192.168.1.10:8088/api/mcp"].properties + + def test_invalid_saved_config_is_reported(tmp_path) -> None: path = tmp_path / "connections.json" path.write_text("not-json", encoding="utf-8") From 0b3d04ec388d8aca1ab33b47e75b6292c7a09248 Mon Sep 17 00:00:00 2001 From: taisuii <93462725+taisuii@users.noreply.github.com> Date: Tue, 24 Nov 2026 00:12:20 +0800 Subject: [PATCH 02/20] =?UTF-8?q?refactor:=20=E5=AF=B9=E9=BD=90=20Frida=20?= =?UTF-8?q?=E7=9B=B4=E8=BF=9E=E6=A8=A1=E5=9E=8B=EF=BC=8C=E7=A7=BB=E9=99=A4?= =?UTF-8?q?=E8=AE=BE=E5=A4=87=E9=85=8D=E5=AF=B9=20token=20=E8=A6=81?= =?UTF-8?q?=E6=B1=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 设备端点直连无需 token,LAN 地址不再被 127.0.0.1 限制拦截 - 删除 IDH_DEVICE_SESSION_TOKEN/IDH_PROCESS_TOKEN/IDH_DEVICE_SETTINGS_TOKEN 处理与 token 持久化 - 面板移除配对状态展示与凭证说明,转发器不再注入 Authorization - 测试改为无鉴权 daemon fixture,断言握手与调用均无 Authorization 头 --- src/idh/cli.py | 99 +++++---------------------- src/idh/config.py | 24 +------ src/idh/panel-device.js | 5 +- src/idh/panel.html | 4 +- tests/test_config.py | 9 +-- tests/test_device_select.py | 132 +++++++++--------------------------- 6 files changed, 57 insertions(+), 216 deletions(-) diff --git a/src/idh/cli.py b/src/idh/cli.py index 9262fd3..bc610dd 100755 --- a/src/idh/cli.py +++ b/src/idh/cli.py @@ -24,7 +24,6 @@ load_selected, remove_endpoint, save_endpoint, - save_endpoint_token, save_selected, ) from .gateway import ( @@ -74,10 +73,6 @@ def _probed_endpoints(endpoints: Sequence[AppEndpoint]) -> list[AppEndpoint]: return list(pool.map(probe_endpoint, endpoints)) -_DEVICE_READ_TOOLS = {"list_sessions", "get_session", "read_session_events"} -_DEVICE_PROCESS_TOOLS = {"get_process_identity"} - - def _endpoint_label(endpoint: AppEndpoint) -> str: kind = endpoint.kind or "unrecognized" name = "idhjd" if endpoint.kind == "device" else endpoint.app_name @@ -127,18 +122,10 @@ def _resolve_device( ) -def _device_client(endpoint: AppEndpoint, tool_name: str | None = None) -> MCPHTTPClient: - if endpoint.primary_address != "127.0.0.1" or endpoint.mcp_url != endpoint.base_url + "/api/mcp": - raise UsageError("idh: a device credential is only sent to a 127.0.0.1 forward") - variable = ( - "IDH_DEVICE_SESSION_TOKEN" - if tool_name is None or tool_name in _DEVICE_READ_TOOLS - else "IDH_PROCESS_TOKEN" - ) - token = os.environ.get(variable, "").strip() - if not token or not token.isascii() or any(character.isspace() for character in token): - raise UsageError(f"idh: set {variable} before calling the device") - return MCPHTTPClient(endpoint, bearer_token=token) +def _device_client(endpoint: AppEndpoint) -> MCPHTTPClient: + if endpoint.mcp_url != endpoint.base_url + "/api/mcp": + raise UsageError("idh: the device endpoint does not expose a session MCP URL") + return MCPHTTPClient(endpoint) def _serve_device_session(endpoint: AppEndpoint) -> int: @@ -154,13 +141,10 @@ def handle(message): params = message.get("params") if isinstance(message, dict) else None name = params.get("name") if isinstance(params, dict) else None try: - chosen = client - if method == "tools/call" and isinstance(name, str) and name not in _DEVICE_READ_TOOLS: - chosen = _device_client(endpoint, name) - reply = chosen.send(message) + reply = client.send(message) if method == "initialize" and isinstance(reply, dict) and "error" not in reply: if reply.get("result", {}).get("serverInfo", {}).get("name") != "idhjd": - raise MCPTransportError("expected the paired device session service") + raise MCPTransportError("expected the device session service") return reply except (MCPTransportError, UsageError) as error: if identity is None: @@ -223,7 +207,7 @@ def build_parser() -> argparse.ArgumentParser: mcp = subparsers.add_parser("mcp", help="start the stdio MCP gateway") mcp.add_argument("--target", help="transparent proxy to one app; omit for the aggregate gateway") - mcp.add_argument("--device-session", action="store_true", help="connect to the paired device session service over a loopback forward") + mcp.add_argument("--device-session", action="store_true", help="connect to the device session service over a loopback forward") _add_endpoint_options(mcp) call = subparsers.add_parser("call", help="call an MCP tool on a device (defaults to the only online device)") @@ -402,25 +386,6 @@ def _run_tools(args: argparse.Namespace) -> int: if not isinstance(result, dict) or not isinstance(result.get("tools"), list): print("idh: invalid tools/list response", file=sys.stderr) return 1 - if endpoint.kind == "device": - result = { - **result, - "tools": [tool for tool in result["tools"] if tool.get("name") in _DEVICE_READ_TOOLS] - + [ - { - "name": "get_process_identity", - "description": "Read one live process. Requires IDH_PROCESS_TOKEN.", - "inputSchema": { - "type": "object", - "required": ["bundleId"], - "properties": { - "bundleId": {"type": "string"}, - "processGeneration": {"type": "string"}, - }, - }, - } - ], - } print(json.dumps(result, ensure_ascii=False, indent=2)) return 0 except UsageError as exc: @@ -510,7 +475,7 @@ def _run_call(args: argparse.Namespace) -> int: return 2 try: client = ( - _device_client(endpoint, args.tool_name) + _device_client(endpoint) if endpoint.kind == "device" else MCPHTTPClient(endpoint) ) @@ -810,16 +775,12 @@ def _run_auto_update(args: argparse.Namespace) -> None: def _panel_request( - endpoint: AppEndpoint, path: str, token: str = "", *, body: bytes | None = None + endpoint: AppEndpoint, path: str, *, body: bytes | None = None ) -> tuple[int, object]: - if endpoint.primary_address != "127.0.0.1": - raise UsageError("idh: the computer page only talks to a 127.0.0.1 forward") headers = {"Accept": "application/json"} - if token: - headers["Authorization"] = f"Bearer {token}" if body is not None: headers["Content-Type"] = "application/json" - with contextlib.closing(HTTPConnection("127.0.0.1", endpoint.port, timeout=3)) as connection: + with contextlib.closing(HTTPConnection(endpoint.primary_address, endpoint.port, timeout=3)) as connection: connection.request("GET" if body is None else "POST", path, body=body, headers=headers) response = connection.getresponse() payload = response.read() if response.status == 200 or path == _PANEL_SETTINGS_ROUTE else b"" @@ -854,10 +815,6 @@ def _run_panel(args: argparse.Namespace) -> int: break current = {"endpoint": endpoint} - def device_token(ep: AppEndpoint) -> str: - saved = ep.properties.get("session_token") or "" - return saved or os.environ.get("IDH_DEVICE_SESSION_TOKEN", "").strip() - def device_records() -> dict: saved = [item for item in load_saved_endpoints() if item.kind == "device"] probed = _probed_endpoints(saved) @@ -870,7 +827,6 @@ def device_records() -> dict: "kind": item.kind, "online": item.properties.get("status") == "online", "selected": item.mcp_url == selected, - "paired": bool(device_token(item)), } for item in probed ], @@ -921,14 +877,12 @@ def write_json(self, code: int, data: object) -> None: self.write_body(code, json.dumps(data).encode(), "application/json") def relay_settings(self, body: bytes | None = None) -> None: - token = os.environ.get("IDH_DEVICE_SETTINGS_TOKEN", "").strip() - if not token and body is None: - token = os.environ.get("IDH_DEVICE_SESSION_TOKEN", "").strip() - if not token: - self.write_json(401, {"error": "settings_pairing_required"}) + endpoint = current["endpoint"] + if not endpoint: + self.write_json(502, {"error": "device_unavailable"}) return try: - code, data = _panel_request(endpoint, _PANEL_SETTINGS_ROUTE, token, body=body) + code, data = _panel_request(endpoint, _PANEL_SETTINGS_ROUTE, body=body) except (HTTPException, OSError, ValueError, UsageError): self.write_json(502, {"error": "device_unavailable"}) return @@ -982,16 +936,6 @@ def device_action(self, body: bytes) -> None: current["endpoint"] = next((e for e in load_saved_endpoints() if e.kind == "device"), None) self.write_json(200, device_records()) return - if action == "token": - token = str(request.get("token") or "").strip() - if not token or not token.isascii() or any(ch.isspace() for ch in token): - self.write_json(400, {"error": "invalid_token"}) - return - if not save_endpoint_token(target, token): - self.write_json(404, {"error": "unknown_device"}) - return - self.write_json(200, device_records()) - return self.write_json(400, {"error": "invalid_device_request"}) def do_POST(self) -> None: @@ -1030,9 +974,8 @@ def do_POST(self) -> None: self.device_action(body) return endpoint = current["endpoint"] - token = device_token(endpoint) if endpoint else "" - if not endpoint or not token: - self.write_json(401, {"error": "session_pairing_required"}) + if not endpoint: + self.write_json(502, {"error": "device_unavailable"}) return try: request = json.loads(body) @@ -1054,7 +997,7 @@ def do_POST(self) -> None: self.write_json(400, {"error": "invalid_bundle_id"}) return try: - code, data = _panel_request(endpoint, self.path, token, body=body) + code, data = _panel_request(endpoint, self.path, body=body) except (HTTPException, OSError, ValueError, UsageError): self.write_json(502, {"error": "device_unavailable"}) return @@ -1095,14 +1038,8 @@ def do_GET(self) -> None: if current["endpoint"] is None: self.send_error(502) return - token = "" - if session_route or target.path in _PANEL_DEVICE_READ: - token = device_token(current["endpoint"]) - if not token: - self.send_error(401) - return try: - code, data = _panel_request(current["endpoint"], self.path, token) + code, data = _panel_request(current["endpoint"], self.path) except (HTTPException, OSError, ValueError, UsageError): self.send_error(502) return diff --git a/src/idh/config.py b/src/idh/config.py index 28e1419..c2efc4b 100755 --- a/src/idh/config.py +++ b/src/idh/config.py @@ -57,9 +57,6 @@ def load_saved_endpoints(path: Path | None = None) -> list[AppEndpoint]: if kind is not None and kind not in _KINDS: raise ValueError(f"connection config has an unknown kind: {target}") endpoint = AppEndpoint.from_url(url).with_kind(kind if isinstance(kind, str) else None) - token = item.get("session_token") - if isinstance(token, str) and token: - endpoint = endpoint.with_properties({"session_token": token}) loaded.append(endpoint) return loaded except ValueError as exc: @@ -128,23 +125,6 @@ def save_selected(value: str, path: Path | None = None) -> None: _write_endpoints(load_saved_endpoints(target), target, selected=value) -def save_endpoint_token(value: str, token: str, path: Path | None = None) -> bool: - target = path or config_path() - canonical = AppEndpoint.from_url(value).mcp_url.casefold() - endpoints = load_saved_endpoints(target) - updated = False - items: list[AppEndpoint] = [] - for item in endpoints: - if item.mcp_url.casefold() == canonical: - item = item.with_properties({"session_token": token}) - updated = True - items.append(item) - if not updated: - return False - _write_endpoints(items, target) - return True - - def _write_endpoints( endpoints: Iterable[AppEndpoint], target: Path, *, selected: str | None = None ) -> None: @@ -158,15 +138,13 @@ def _write_endpoints( except (OSError, UnicodeError, json.JSONDecodeError): pass items = sorted(endpoints, key=lambda item: item.mcp_url.casefold()) - if any(item.kind or item.properties.get("session_token") for item in items): + if any(item.kind for item in items): payload: dict[str, object] = { "version": CONFIG_VERSION_KIND, "endpoints": [ { "url": item.mcp_url, **({"kind": item.kind} if item.kind else {}), - **({"session_token": item.properties["session_token"]} - if item.properties.get("session_token") else {}), } for item in items ], diff --git a/src/idh/panel-device.js b/src/idh/panel-device.js index e0d8140..10e27a9 100644 --- a/src/idh/panel-device.js +++ b/src/idh/panel-device.js @@ -145,8 +145,7 @@ if (!sessions.some((session) => session.sessionId === selected)) changeSelection(sessions[0]?.sessionId || ""); selectOptions(sessions); const notice = document.getElementById("idh-session-notice"); - notice.textContent = history.status === 401 ? "请在手机 Manager 获取有效的设备会话只读凭证。" - : history.ok ? "" : "设备在线,会话暂时无法读取。"; + notice.textContent = history.ok ? "" : "设备在线,会话暂时无法读取。"; notice.hidden = !notice.textContent; catalog = {time: Date.now(), device, sessions}; return catalog; @@ -243,7 +242,7 @@ const data = await result.json(); if (result.ok) return response(data); const messages = { - settings_pairing_required: "请在手机 Manager 复制设备设置凭证并传给电脑面板。", + settings_pairing_required: "设备设置暂不可用。", revision_conflict: "设备配置已被修改。请重新载入后再应用。", invalid_settings: "设备会话限额需要整数,支持 1–2000 条、512–2097152 字节和 1–300 秒。", settings_storage_error: "设备无法读取或保存设置。", diff --git a/src/idh/panel.html b/src/idh/panel.html index e833bc2..9c8dfa8 100644 --- a/src/idh/panel.html +++ b/src/idh/panel.html @@ -461,7 +461,7 @@

MCP 连接

-

在手机 Manager 复制设备会话只读凭证,传给客户端进程的 IDH_DEVICE_SESSION_TOKEN。

+

面板地址即设备地址,USB 转发与局域网直连均可。


     

@@ -1270,7 +1270,7 @@ let deviceRows=[]; function renderDevices() { $("idh-devices").innerHTML=deviceRows.length?deviceRows.map((d)=>{ - const sub=(d.online?"在线":"离线")+(d.paired?"":" · 未配对"); + const sub=d.online?"在线":"离线"; return ''; }).join(""):''; } diff --git a/tests/test_config.py b/tests/test_config.py index 8b57c59..cd76a80 100755 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -11,7 +11,6 @@ load_selected, remove_endpoint, save_endpoint, - save_endpoint_token, save_selected, ) from idh.models import AppEndpoint @@ -67,7 +66,7 @@ def test_same_address_updates_kind_and_keeps_old_files(tmp_path) -> None: assert load_saved_endpoints(path)[0].kind == "device" -def test_selected_and_session_token_round_trip(tmp_path) -> None: +def test_selected_round_trip(tmp_path) -> None: path = tmp_path / "connections.json" save_endpoint(AppEndpoint.from_url("192.168.1.10:8088").with_kind("device"), path) save_endpoint(AppEndpoint.from_url("192.168.1.11:8088").with_kind("device"), path) @@ -78,12 +77,6 @@ def test_selected_and_session_token_round_trip(tmp_path) -> None: save_endpoint(AppEndpoint.from_url("192.168.1.12:8088").with_kind("device"), path) assert load_selected(path) == "http://192.168.1.11:8088/api/mcp" - assert save_endpoint_token("192.168.1.11:8088", "tok-abc", path) is True - assert save_endpoint_token("192.168.1.99:8088", "tok-abc", path) is False - loaded = {item.mcp_url: item for item in load_saved_endpoints(path)} - assert loaded["http://192.168.1.11:8088/api/mcp"].properties["session_token"] == "tok-abc" - assert "session_token" not in loaded["http://192.168.1.10:8088/api/mcp"].properties - def test_invalid_saved_config_is_reported(tmp_path) -> None: path = tmp_path / "connections.json" diff --git a/tests/test_device_select.py b/tests/test_device_select.py index 24dc5d4..0e8d149 100644 --- a/tests/test_device_select.py +++ b/tests/test_device_select.py @@ -24,17 +24,11 @@ class DeviceHandler(BaseHTTPRequestHandler): def do_GET(self) -> None: path, _, query = self.path.partition("?") if path == "/api/session-settings": - if self.headers.get("Authorization") not in {"Bearer panel-key", "Bearer settings-key"}: - self._send(401, b'{"error":"settings_pairing_required"}') - else: - self._send(200, json.dumps({ - "ok": True, "revision": self.revision, "deviceSession": self.limits, - }).encode()) + self._send(200, json.dumps({ + "ok": True, "revision": self.revision, "deviceSession": self.limits, + }).encode()) return if path == "/api/sessions" or path.startswith("/api/sessions/"): - if self.headers.get("Authorization") != "Bearer panel-key": - self._send(401, b"") - return session = {"sessionId": PANEL_SESSION_ID, "bundleId": "com.example.fixture", "count": 40} if path == "/api/sessions": payload = {"ok": True, "sessions": [session]} @@ -58,9 +52,7 @@ def do_POST(self) -> None: message = json.loads(self.rfile.read(length) or b"{}") if self.path == "/api/session-settings": self.settings_posts.append(message) - if self.headers.get("Authorization") != "Bearer settings-key": - self._send(401, b'{"error":"settings_pairing_required"}') - elif message["revision"] != self.revision: + if message["revision"] != self.revision: self._send(409, b'{"error":"revision_conflict"}') else: DeviceHandler.limits = {**self.limits, **message["deviceSession"]} @@ -127,37 +119,34 @@ def device_url() -> str: thread.join() -def test_empty_device_still_reads_authorized_history( - device_url: str, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +def test_empty_device_still_reads_history( + device_url: str, capsys: pytest.CaptureFixture[str] ) -> None: - monkeypatch.setenv("IDH_DEVICE_SESSION_TOKEN", "secret") code = main( ["call", "list_sessions", "--endpoint", device_url, "--no-saved", "--json"] ) assert code == 0, capsys.readouterr().err output = json.loads(capsys.readouterr().out) assert output["structuredContent"]["sessions"][0]["sessionId"] == "saved" - assert DeviceHandler.authorization[0] == "Bearer secret" + assert DeviceHandler.authorization and set(DeviceHandler.authorization) == {None} -def test_revoked_pairing_is_not_an_empty_history( - device_url: str, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +def test_device_error_is_not_an_empty_history( + device_url: str, capsys: pytest.CaptureFixture[str] ) -> None: DeviceHandler.status_code = 401 - monkeypatch.setenv("IDH_DEVICE_SESSION_TOKEN", "secret") code = main(["call", "list_sessions", "--endpoint", device_url, "--no-saved", "--json"]) assert code == 1 assert "401" in capsys.readouterr().err -def test_device_tools_keep_only_session_reads( - device_url: str, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +def test_device_tools_returns_device_list( + device_url: str, capsys: pytest.CaptureFixture[str] ) -> None: - monkeypatch.setenv("IDH_DEVICE_SESSION_TOKEN", "secret") code = main(["tools", "--endpoint", device_url, "--no-saved", "--json"]) assert code == 0, capsys.readouterr().err names = [tool["name"] for tool in json.loads(capsys.readouterr().out)["tools"]] - assert names == ["list_sessions", "get_process_identity"] + assert names == ["list_sessions", "disassemble"] def test_status_lists_a_device_with_no_apps(device_url: str, capsys: pytest.CaptureFixture[str]) -> None: @@ -176,7 +165,6 @@ def test_two_devices_require_an_address( thread = threading.Thread(target=extra.serve_forever, daemon=True) thread.start() other = f"http://127.0.0.1:{extra.server_port}" - monkeypatch.setenv("IDH_DEVICE_SESSION_TOKEN", "secret") try: code = main( ["call", "list_sessions", "--endpoint", device_url, "--endpoint", other, "--no-saved"] @@ -189,70 +177,26 @@ def test_two_devices_require_an_address( thread.join() -def test_process_identity_uses_a_separate_token( - device_url: str, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +def test_device_calls_send_no_credential( + device_url: str, capsys: pytest.CaptureFixture[str] ) -> None: - monkeypatch.setenv("IDH_DEVICE_SESSION_TOKEN", "session-token") - monkeypatch.setenv("IDH_PROCESS_TOKEN", "process-token") - code = main( - [ - "call", - "get_process_identity", - "--endpoint", - device_url, - "--no-saved", - "--json", - "--arguments", - '{"bundleId": "com.example.app"}', - ] - ) - assert code == 0, capsys.readouterr().err - assert set(DeviceHandler.authorization) == {"Bearer process-token"} - - DeviceHandler.authorization = [] - code = main(["call", "list_sessions", "--endpoint", device_url, "--no-saved", "--json"]) - assert code == 0, capsys.readouterr().err - assert set(DeviceHandler.authorization) == {"Bearer session-token"} - - -def test_session_token_is_not_sent_for_process_identity( - device_url: str, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] -) -> None: - monkeypatch.setenv("IDH_DEVICE_SESSION_TOKEN", "session-token") - monkeypatch.delenv("IDH_PROCESS_TOKEN", raising=False) - code = main( - ["call", "get_process_identity", "--endpoint", device_url, "--no-saved", "--json"] - ) - assert code == 2 - assert "IDH_PROCESS_TOKEN" in capsys.readouterr().err - assert DeviceHandler.authorization == [] - - -def test_forwarded_tool_uses_the_process_token( - device_url: str, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] -) -> None: - monkeypatch.setenv("IDH_PROCESS_TOKEN", "process-token") - code = main( - [ - "call", - "disassemble", - "--endpoint", - device_url, - "--no-saved", - "--json", - "--arguments", - '{"bundleId": "com.example.app", "address": "0x1"}', - ] - ) - assert code == 0, capsys.readouterr().err - assert set(DeviceHandler.authorization) == {"Bearer process-token"} + for tool, arguments in ( + ("get_process_identity", '{"bundleId": "com.example.app"}'), + ("list_sessions", None), + ("disassemble", '{"bundleId": "com.example.app", "address": "0x1"}'), + ): + DeviceHandler.authorization = [] + command = ["call", tool, "--endpoint", device_url, "--no-saved", "--json"] + if arguments is not None: + command += ["--arguments", arguments] + code = main(command) + assert code == 0, capsys.readouterr().err + assert set(DeviceHandler.authorization) == {None} def test_panel_reads_history_independently_of_online_apps( device_url: str, monkeypatch: pytest.MonkeyPatch, ) -> None: - monkeypatch.setenv("IDH_DEVICE_SESSION_TOKEN", "panel-key") - monkeypatch.delenv("IDH_DEVICE_SETTINGS_TOKEN", raising=False) panel_servers: Queue[ThreadingHTTPServer] = Queue() serve_forever = ThreadingHTTPServer.serve_forever @@ -271,7 +215,6 @@ def publish_server(server: ThreadingHTTPServer) -> None: page = response.read().decode() assert "id='idh-session'" in page and "id='tabbar'" in page assert "class='splitter'" in page and 'class="hdr-raven"' in page - assert "panel-key" not in page with urlopen(base + "/panel-device.js", timeout=3) as response: assert b"IDHDevicePanel" in response.read() with urlopen(base + "/wechat-follow.png", timeout=3) as response: @@ -291,27 +234,17 @@ def publish_server(server: ThreadingHTTPServer) -> None: with pytest.raises(HTTPError) as error: urlopen(base + path, timeout=3) assert error.value.code == 404 - monkeypatch.setenv("IDH_DEVICE_SESSION_TOKEN", "revoked") - for address in (base + "/api/sessions", detail, detail + "/events"): - with pytest.raises(HTTPError) as error: - urlopen(address, timeout=3) - assert error.value.code == 401 with urlopen(base + "/health", timeout=3) as response: assert json.load(response)["ok"] is True with pytest.raises(HTTPError) as error: urlopen(Request(base + "/api/sessions", headers={"Host": "unknown.example"}), timeout=3) assert error.value.code == 400 settings = base + "/api/session-settings" - monkeypatch.setenv("IDH_DEVICE_SESSION_TOKEN", "panel-key") with urlopen(settings, timeout=3) as response: config = json.load(response) assert config["deviceSession"] == DeviceHandler.limits data = json.dumps({"revision": config["revision"], "deviceSession": {"maxRecords": 8}}).encode() headers = {"Content-Type": "application/json", "Origin": base} - with pytest.raises(HTTPError) as error: - urlopen(Request(settings, data=data, headers=headers), timeout=3) - assert error.value.code == 401 and DeviceHandler.settings_posts == [] - monkeypatch.setenv("IDH_DEVICE_SETTINGS_TOKEN", "settings-key") with pytest.raises(HTTPError) as error: urlopen(Request(settings, data=data, headers={**headers, "Origin": "http://unknown.example"}), timeout=3) assert error.value.code == 403 and DeviceHandler.settings_posts == [] @@ -327,7 +260,7 @@ def publish_server(server: ThreadingHTTPServer) -> None: thread.join(timeout=5) -def test_panel_refuses_a_lan_address( +def test_panel_accepts_a_lan_address( monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] ) -> None: def online(endpoint, timeout=1.0): @@ -335,20 +268,21 @@ def online(endpoint, timeout=1.0): monkeypatch.setattr("idh.cli.probe_endpoint", online) code = main(["panel", "--endpoint", "http://10.0.0.8:8088", "--no-saved"]) + # 不可达是传输错误,不再被「只允许 127.0.0.1 转发」拦下 assert code == 2 - assert "127.0.0.1" in capsys.readouterr().err + assert "127.0.0.1" not in capsys.readouterr().err -def test_device_credential_is_not_sent_to_a_lan_address( +def test_lan_address_is_used_directly( monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] ) -> None: def online(endpoint, timeout=1.0): return endpoint.with_kind("device").with_properties({"status": "online", "app_count": "0"}) monkeypatch.setattr("idh.cli.probe_endpoint", online) - monkeypatch.setenv("IDH_DEVICE_SESSION_TOKEN", "secret") code = main( ["call", "10.0.0.8:8088", "list_sessions", "--endpoint", "http://10.0.0.8:8088", "--no-saved"] ) - assert code == 2 - assert "127.0.0.1" in capsys.readouterr().err + # 不可达是传输错误,不再被「只允许 127.0.0.1 转发」拦下 + assert code == 1 + assert "127.0.0.1" not in capsys.readouterr().err From fb94bf2fa26f5b3aed3cbee3a44bc79812e9c6ad Mon Sep 17 00:00:00 2001 From: taisuii <93462725+taisuii@users.noreply.github.com> Date: Tue, 24 Nov 2026 00:28:39 +0800 Subject: [PATCH 03/20] =?UTF-8?q?feat:=20usbmuxd=20=E5=AE=A2=E6=88=B7?= =?UTF-8?q?=E7=AB=AF=E4=B8=8E=20USB=20=E8=AE=BE=E5=A4=87=E6=8E=A5=E5=85=A5?= =?UTF-8?q?=EF=BC=88frida=20-U=20=E7=AD=89=E4=BB=B7=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 usbmux.py:v1 plist 协议列设备 + Connect 隧道,无需第三方库; 默认探测 /var/run/usbmuxd(macOS/Linux)与 127.0.0.1:27015(Windows), IDH_USBMUXD 可指向远端 usbmuxd - USB 设备经本地回环转发器暴露为普通 endpoint,已有 probe/保存/选中/面板 转发路径全部复用;resolve_endpoint 在各连接点重写为活跃转发端口 - connect 接受 usb / usb:;devices 与面板设备列表展示已插未存 USB 设备 - 面板 USB 设备一键添加;README 更新为传输层信任模型 - 顺带修复 Windows GBK 控制台输出 ✓/✗ 崩溃(stdout/stderr 转 UTF-8) --- README.md | 17 ++-- src/idh/cli.py | 68 +++++++++++-- src/idh/panel.html | 14 ++- src/idh/usbmux.py | 223 +++++++++++++++++++++++++++++++++++++++++++ tests/test_usbmux.py | 178 ++++++++++++++++++++++++++++++++++ 5 files changed, 480 insertions(+), 20 deletions(-) create mode 100644 src/idh/usbmux.py create mode 100644 tests/test_usbmux.py diff --git a/README.md b/README.md index 5976394..c1a8c4f 100755 --- a/README.md +++ b/README.md @@ -196,20 +196,21 @@ idh mcp --target 1 --endpoint http://127.0.0.1:8088 ### 越狱版设备会话 -在 IOSDecryptHub Manager 中启用设备会话模式并复制只读凭证。通过已授权的调试通道把设备的 `127.0.0.1:8088` 转发到 PC 本机,将凭证设置为 `IDH_DEVICE_SESSION_TOKEN`。`mcp`、`call`、`tools` 认出 `device` 后共用这一条连接。配对凭证只发给 `127.0.0.1`。 +`idhjd` 只绑设备回环 `127.0.0.1:8088`,没有自定义认证——与 frida-server 同一模型,信任来自传输层: -使用 `idh panel` 打开电脑端原版工作台。要编辑「设置 → 配置 JSON」和「日志」中的会话限额,再从 Manager 复制独立的设备设置凭证,并传入启动面板的 `IDH_DEVICE_SETTINGS_TOKEN`。只读凭证不能保存配置。写入持续保存在设备上,从下一场会话起生效。 +- **USB**:`idh connect usb`(或 `usb:`)经 usbmuxd 直连,插线即授权,等同 `frida -U`。`IDH_USBMUXD` 可指向其他机器的 usbmuxd(`host:port` 或 unix socket 路径,例如经 SSH 转发的 macOS `/var/run/usbmuxd`)。 +- **SSH 转发**:`ssh -L 8088:127.0.0.1:8088 root@` 后用 `idh connect 127.0.0.1:8088`。 +- **局域网**:设备上由 root 创建 `/private/var/db/idhjd-v1/listen-remote` 并重启 idhjd 后绑 `0.0.0.0`,等同 `frida-server -l`;之后 `idh connect :8088`。默认不开。 ```bash -idh mcp --endpoint http://127.0.0.1:8088 -idh call list_sessions --endpoint http://127.0.0.1:8088 +idh connect usb +idh mcp --endpoint usb +idh call list_sessions --endpoint usb: ``` -`idh mcp --device-session --endpoint http://127.0.0.1:8088` 仍可用。旧包没有 `/health` 时用这个别名。多条连接时用地址或连接 ID 指定。App 仍用 `--target `。 +`idh mcp --device-session --endpoint ` 仍可用作别名。多条连接时用地址或连接 ID 指定。App 仍用 `--target `。 -目标 App 退出后,上述三个只读工具仍能读已保存摘要。关闭会话模式会撤销会话配对,之后读取失败。服务重启或重新配对后,更新客户端使用的凭证。 - -`get_process_identity` 不使用这把会话凭证。它读取某个在线进程,凭证放在 `IDH_PROCESS_TOKEN`,同样只发到 `127.0.0.1`。同一个 App 有多个进程时,参数里带上 `processGeneration`。 +目标 App 退出后,只读工具仍能读已保存摘要。关闭会话模式不影响连接本身。 ## 连接状态 diff --git a/src/idh/cli.py b/src/idh/cli.py index bc610dd..fdc991e 100755 --- a/src/idh/cli.py +++ b/src/idh/cli.py @@ -45,6 +45,7 @@ ) from .settings import load_settings, update_settings from .status import status +from .usbmux import UsbMuxError, resolve_endpoint, usb_endpoint, usbmux_devices PROBE_TIMEOUT = 3.0 @@ -57,7 +58,10 @@ def _manual_endpoints(values: Sequence[str], *, include_saved: bool = True) -> l endpoints = list(load_saved_endpoints()) if include_saved else [] seen = {endpoint.mcp_url.casefold() for endpoint in endpoints} for value in values: - manual = AppEndpoint.from_url(value) + if value == "usb" or value.startswith("usb:"): + manual = _pick_usb_endpoint(value[4:] or None) + else: + manual = AppEndpoint.from_url(value) key = manual.mcp_url.casefold() if key in seen: continue @@ -66,11 +70,31 @@ def _manual_endpoints(values: Sequence[str], *, include_saved: bool = True) -> l return endpoints +def _pick_usb_endpoint(udid: str | None = None) -> AppEndpoint: + """frida -U 等价入口:usb 或 usb:。单设备免选,多设备按 udid 选。""" + try: + devices = usbmux_devices() + except UsbMuxError as exc: + raise ValueError(f"cannot reach usbmuxd: {exc}") from exc + if udid: + matches = [device for device in devices if device["udid"].casefold() == udid.casefold()] + if not matches: + raise ValueError(f"usb device not attached: {udid}") + elif len(devices) == 1: + matches = devices + elif not devices: + raise ValueError("no USB devices attached") + else: + lines = "\n".join(f" {device['udid']}" for device in devices) + raise ValueError(f"multiple USB devices attached; use usb:\n{lines}") + return usb_endpoint(matches[0]["udid"]) + + def _probed_endpoints(endpoints: Sequence[AppEndpoint]) -> list[AppEndpoint]: if not endpoints: return [] with ThreadPoolExecutor(max_workers=min(8, len(endpoints))) as pool: - return list(pool.map(probe_endpoint, endpoints)) + return list(pool.map(probe_endpoint, (resolve_endpoint(e) for e in endpoints))) def _endpoint_label(endpoint: AppEndpoint) -> str: @@ -123,6 +147,7 @@ def _resolve_device( def _device_client(endpoint: AppEndpoint) -> MCPHTTPClient: + endpoint = resolve_endpoint(endpoint) if endpoint.mcp_url != endpoint.base_url + "/api/mcp": raise UsageError("idh: the device endpoint does not expose a session MCP URL") return MCPHTTPClient(endpoint) @@ -182,7 +207,7 @@ def build_parser() -> argparse.ArgumentParser: subparsers = parser.add_subparsers(dest="command") connect = subparsers.add_parser("connect", help="save and connect a device address") - connect.add_argument("endpoint", nargs="?", help="device address, e.g. 192.168.100.65:8088") + connect.add_argument("endpoint", nargs="?", help="device address (192.168.100.65:8088), usb, or usb:") connect.add_argument("--timeout", type=float, default=PROBE_TIMEOUT, help="HTTP probe timeout in seconds") connect.add_argument("--force", action="store_true", help="save the address even when the device is unreachable") connect.add_argument("--json", action="store_true", help="output JSON") @@ -300,11 +325,14 @@ def _run_connect(args: argparse.Namespace) -> int: _print_inventory(data) return 0 try: - endpoint = AppEndpoint.from_url(args.endpoint) + if args.endpoint == "usb" or args.endpoint.startswith("usb:"): + endpoint = _pick_usb_endpoint(args.endpoint[4:] or None) + else: + endpoint = AppEndpoint.from_url(args.endpoint) except ValueError as exc: print(f"idh: {exc}", file=sys.stderr) return 2 - probed = probe_endpoint(endpoint, timeout=max(0.1, args.timeout)) + probed = probe_endpoint(resolve_endpoint(endpoint), timeout=max(0.1, args.timeout)) online = probed.properties.get("status") == "online" if not online and not args.force: print( @@ -359,13 +387,27 @@ def _run_disconnect(args: argparse.Namespace) -> int: return 0 +def _usb_available(endpoints: Sequence[AppEndpoint]) -> list[dict]: + saved = {endpoint.properties.get("usb_udid") for endpoint in endpoints} + try: + devices = usbmux_devices(timeout=1.0) + except UsbMuxError: + return [] + return [device for device in devices if device["udid"] not in saved] + + def _run_devices(args: argparse.Namespace) -> int: endpoints = _manual_endpoints(args.endpoint, include_saved=not args.no_saved) data = inventory(endpoints) + available = _usb_available(endpoints) if args.json: + if available: + data["usb_available"] = available print(json.dumps(data, ensure_ascii=False, indent=2)) else: _print_inventory(data) + for device in available: + print(f" [usb] {device['udid']} (connect: idh connect usb:{device['udid']})") return 0 @@ -777,6 +819,7 @@ def _run_auto_update(args: argparse.Namespace) -> None: def _panel_request( endpoint: AppEndpoint, path: str, *, body: bytes | None = None ) -> tuple[int, object]: + endpoint = resolve_endpoint(endpoint) headers = {"Accept": "application/json"} if body is not None: headers["Content-Type"] = "application/json" @@ -825,11 +868,13 @@ def device_records() -> dict: "id": item.mcp_url, "address": item.base_url, "kind": item.kind, + "transport": item.properties.get("transport"), "online": item.properties.get("status") == "online", "selected": item.mcp_url == selected, } for item in probed ], + "usb": [device["udid"] for device in _usb_available(saved)], "selected": selected, } @@ -901,12 +946,16 @@ def device_action(self, body: bytes) -> None: return action = request.get("action") if action == "add": + udid = request.get("usb") try: - endpoint = AppEndpoint.from_url(str(request.get("address") or "")) + if udid: + endpoint = _pick_usb_endpoint(str(udid)) + else: + endpoint = AppEndpoint.from_url(str(request.get("address") or "")) except ValueError: self.write_json(400, {"error": "invalid_address"}) return - probed = probe_endpoint(endpoint, timeout=3) + probed = probe_endpoint(resolve_endpoint(endpoint), timeout=3) if probed.properties.get("status") == "online" and probed.kind != "device": self.write_json(400, {"error": "not_a_device"}) return @@ -1071,6 +1120,11 @@ def log_message(self, *_args: object) -> None: def main(argv: Sequence[str] | None = None) -> int: + for stream in (sys.stdout, sys.stderr): + try: + stream.reconfigure(encoding="utf-8", errors="replace") + except (AttributeError, OSError): + pass parser = build_parser() args = parser.parse_args(_normalize_argv(sys.argv[1:] if argv is None else argv)) try: diff --git a/src/idh/panel.html b/src/idh/panel.html index 9c8dfa8..15f03d0 100644 --- a/src/idh/panel.html +++ b/src/idh/panel.html @@ -1267,21 +1267,25 @@ // ---- 设备管理 + 注入范围 ---- const post=(body)=>fetch("/api/devices",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(body)}).then((r)=>r.json()); - let deviceRows=[]; + let deviceRows=[],usbRows=[]; function renderDevices() { - $("idh-devices").innerHTML=deviceRows.length?deviceRows.map((d)=>{ - const sub=d.online?"在线":"离线"; + const saved=deviceRows.map((d)=>{ + const sub=(d.transport==="usb"?"USB · ":"")+(d.online?"在线":"离线"); return ''; - }).join(""):''; + }); + const usb=usbRows.map((udid)=>''); + $("idh-devices").innerHTML=(saved.length||usb.length)?saved.concat(usb).join(""):''; } async function loadDevices() { - try{const data=await (await fetch("/api/devices")).json();deviceRows=data.devices||[];}catch{deviceRows=[];} + try{const data=await (await fetch("/api/devices")).json();deviceRows=data.devices||[];usbRows=data.usb||[];}catch{deviceRows=[];usbRows=[];} renderDevices(); } $("processBtn").addEventListener("click",loadDevices); $("idh-devices").addEventListener("click",async(event)=>{ const remove=event.target.closest("[data-remove]"); if(remove){event.stopPropagation();await post({action:"remove",id:remove.dataset.remove});loadDevices();return;} + const usbRow=event.target.closest("[data-usb]"); + if(usbRow){await post({action:"add",usb:usbRow.dataset.usb});loadDevices();return;} const row=event.target.closest("[data-device]"); if(row && !row.getAttribute("aria-selected").includes("true")){ const data=await post({action:"select",id:row.dataset.device}); diff --git a/src/idh/usbmux.py b/src/idh/usbmux.py new file mode 100644 index 0000000..cfc6a8e --- /dev/null +++ b/src/idh/usbmux.py @@ -0,0 +1,223 @@ +"""usbmuxd client: list USB-attached devices and forward loopback ports. + +Implements the v1 usbmuxd protocol (binary plist over the mux socket) so USB +devices appear as ordinary ``http://127.0.0.1:`` endpoints — the same +shape frida's ``-U`` produces. No third-party dependency; works with Apple's +mobile-device service on Windows (TCP 27015) and macOS usbmuxd +(/var/run/usbmuxd). ``IDH_USBMUXD`` can point at ``host:port`` or a unix socket +path, e.g. an SSH-forwarded usbmuxd on another machine. +""" + +from __future__ import annotations + +import hashlib +import os +import plistlib +import socket +import struct +import threading +from dataclasses import replace + +from .models import AppEndpoint + +IDH_DEVICE_PORT = 8088 + + +class UsbMuxError(OSError): + pass + + +def _usbmuxd_address() -> str | tuple[str, int]: + override = os.environ.get("IDH_USBMUXD", "").strip() + if override: + if ":" in override and not override.startswith("/"): + host, _, port = override.rpartition(":") + return host or "127.0.0.1", int(port) + return override + if os.path.exists("/var/run/usbmuxd"): + return "/var/run/usbmuxd" + return "127.0.0.1", 27015 + + +def _open(timeout: float) -> socket.socket: + address = _usbmuxd_address() + if isinstance(address, str): + sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + sock.settimeout(timeout) + sock.connect(address) + return sock + return socket.create_connection(address, timeout=timeout) + + +def _exchange(sock: socket.socket, payload: dict) -> dict: + body = plistlib.dumps(payload, fmt=plistlib.FMT_BINARY) + sock.sendall(struct.pack(" list[dict]: + """Return USB-attached devices as {udid, device_id, connection_type}.""" + try: + sock = _open(timeout) + except OSError as exc: + raise UsbMuxError(f"usbmuxd unavailable: {exc}") from exc + with sock: + hello = { + "MessageType": "Listen", + "ClientVersionString": "idh", + "ProgName": "idh", + "kLibUSBMuxVersion": 3, + } + result = _exchange(sock, hello) + if result.get("Number") != 0: + raise UsbMuxError(f"usbmuxd listen failed: {result}") + result = _exchange(sock, {**hello, "MessageType": "ListDevices"}) + devices = [] + for entry in result.get("DeviceList") or []: + props = entry.get("Properties") or {} + udid = props.get("SerialNumber") + if udid: + devices.append( + { + "udid": udid, + "device_id": entry.get("DeviceID"), + "connection_type": props.get("ConnectionType", "USB"), + "product_id": props.get("ProductID"), + } + ) + return devices + + +def _device_id(udid: str, timeout: float) -> int: + for device in usbmux_devices(timeout): + if device["udid"] == udid: + return int(device["device_id"]) + raise UsbMuxError(f"usb device detached: {udid}") + + +def _connect(device_id: int, device_port: int, timeout: float) -> socket.socket: + sock = _open(timeout) + try: + result = _exchange( + sock, + { + "MessageType": "Connect", + "ClientVersionString": "idh", + "ProgName": "idh", + "kLibUSBMuxVersion": 3, + "DeviceID": device_id, + "PortNumber": socket.htons(device_port), + }, + ) + if result.get("Number") != 0: + raise UsbMuxError(f"usbmuxd connect refused: {result}") + return sock + except Exception: + sock.close() + raise + + +def _pump(client: socket.socket, udid: str) -> None: + try: + remote = _connect(_device_id(udid, 2.0), IDH_DEVICE_PORT, 2.0) + except OSError: + client.close() + return + remote.settimeout(None) + client.settimeout(None) + + def forward(source: socket.socket, target: socket.socket) -> None: + try: + while True: + data = source.recv(65536) + if not data: + break + target.sendall(data) + except OSError: + pass + finally: + for sock in (source, target): + try: + sock.shutdown(socket.SHUT_RDWR) + except OSError: + pass + try: + sock.close() + except OSError: + pass + + threading.Thread(target=forward, args=(client, remote), daemon=True).start() + threading.Thread(target=forward, args=(remote, client), daemon=True).start() + + +_forwarders: dict[str, int] = {} +_forwarders_lock = threading.Lock() + + +def _forward_port(udid: str) -> int: + return 18400 + int.from_bytes(hashlib.sha256(udid.encode()).digest()[:2], "big") % 400 + + +def ensure_usb_forwarder(udid: str, device_port: int = IDH_DEVICE_PORT) -> int: + """Bind a loopback forwarder for a USB device; return its local port.""" + with _forwarders_lock: + if udid in _forwarders: + return _forwarders[udid] + port = _forward_port(udid) + for _ in range(200): + listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + try: + listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + listener.bind(("127.0.0.1", port)) + listener.listen(8) + except OSError: + listener.close() + port += 1 + continue + break + else: + raise UsbMuxError("no loopback port available for usb forwarder") + + def serve() -> None: + while True: + try: + client, _ = listener.accept() + except OSError: + return + threading.Thread(target=_pump, args=(client, udid), daemon=True).start() + + threading.Thread(target=serve, daemon=True).start() + _forwarders[udid] = port + return port + + +def resolve_endpoint(endpoint: AppEndpoint) -> AppEndpoint: + """Rewrite a usb-transport endpoint to its live loopback forwarder URL.""" + udid = endpoint.properties.get("usb_udid") + if not udid: + return endpoint + port = ensure_usb_forwarder(str(udid)) + if port == endpoint.port: + return endpoint + return replace(endpoint, addresses=("127.0.0.1",), server="127.0.0.1", port=port) + + +def usb_endpoint(udid: str, timeout: float = 2.0) -> AppEndpoint: + """Build an endpoint for a USB device id (starting its forwarder).""" + port = ensure_usb_forwarder(udid) + return AppEndpoint.from_url(f"http://127.0.0.1:{port}").with_properties( + {"transport": "usb", "usb_udid": udid} + ) diff --git a/tests/test_usbmux.py b/tests/test_usbmux.py new file mode 100644 index 0000000..d1458df --- /dev/null +++ b/tests/test_usbmux.py @@ -0,0 +1,178 @@ +from __future__ import annotations + +import os +import plistlib +import socket +import struct +import threading + +import pytest + +from idh import usbmux +from idh.cli import _pick_usb_endpoint +from idh.models import AppEndpoint + + +class FakeUsbMuxd: + """Minimal usbmuxd v1 peer: Listen handshake, ListDevices, Connect→echo.""" + + def __init__(self, devices: list[dict]): + self.devices = devices + self.connect_requests: list[dict] = [] + self.listener = socket.socket() + self.listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + self.listener.bind(("127.0.0.1", 0)) + self.listener.listen(8) + self.port = self.listener.getsockname()[1] + self.thread = threading.Thread(target=self._serve, daemon=True) + self.thread.start() + + def close(self) -> None: + self.listener.close() + + def _serve(self) -> None: + while True: + try: + client, _ = self.listener.accept() + except OSError: + return + threading.Thread(target=self._session, args=(client,), daemon=True).start() + + def _session(self, client: socket.socket) -> None: + def recv() -> dict: + header = b"" + while len(header) < 16: + chunk = client.recv(16 - len(header)) + if not chunk: + raise OSError("closed") + header += chunk + length, _v, _m, _t = struct.unpack(" None: + body = plistlib.dumps(payload, fmt=plistlib.FMT_BINARY) + client.sendall(struct.pack(" Date: Tue, 24 Nov 2026 00:31:23 +0800 Subject: [PATCH 04/20] =?UTF-8?q?fix:=20resolve=20USB=20endpoint=20=D0=B2?= =?UTF-8?q?=D0=BD=D1=83=D1=82=D1=80=D0=B8=20http=5Fmcp=20=E2=80=94=20?= =?UTF-8?q?=D0=BE=D0=B4=D0=BD=D0=B0=20=D1=82=D0=BE=D1=87=D0=BA=D0=B0=20?= =?UTF-8?q?=D0=B4=D0=BB=D1=8F=20=D0=B2=D1=81=D0=B5=D1=85=20=D0=BF=D0=BE?= =?UTF-8?q?=D1=82=D1=80=D0=B5=D0=B1=D0=B8=D1=82=D0=B5=D0=BB=D0=B5=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit probe_endpoint и MCPHTTPClient сами вызывают resolve_endpoint, поэтому gateway/tools/call/status покрыты без отдельных вызовов. Help connect упоминает usb. --- src/idh/http_mcp.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/idh/http_mcp.py b/src/idh/http_mcp.py index 0c82355..55bb600 100755 --- a/src/idh/http_mcp.py +++ b/src/idh/http_mcp.py @@ -8,6 +8,7 @@ from . import __version__ from .models import AppEndpoint +from .usbmux import resolve_endpoint class MCPTransportError(RuntimeError): @@ -23,7 +24,7 @@ class MCPHTTPClient: def __init__( self, endpoint: AppEndpoint, *, timeout: float = 15.0, bearer_token: str | None = None ) -> None: - self.endpoint = endpoint + self.endpoint = resolve_endpoint(endpoint) self.timeout = timeout self.session_id: str | None = None self.initialized = False @@ -108,6 +109,7 @@ def _get_json(url: str, timeout: float) -> Any | None: def probe_endpoint(endpoint: AppEndpoint, *, timeout: float = 1.0) -> AppEndpoint: + endpoint = resolve_endpoint(endpoint) health = _get_json(f"{endpoint.base_url}/health", timeout) apps = health.get("apps") if isinstance(health, dict) else None if ( From 7a2e37e86d4e7470385c5fd92e289f689f75c9d3 Mon Sep 17 00:00:00 2001 From: taisuii <93462725+taisuii@users.noreply.github.com> Date: Tue, 24 Nov 2026 01:53:29 +0800 Subject: [PATCH 05/20] =?UTF-8?q?feat:=20=E9=9D=A2=E6=9D=BF=E6=95=B0?= =?UTF-8?q?=E6=8D=AE=E6=8C=89=20App=20=E7=BB=84=E7=BB=87=E2=80=94=E2=80=94?= =?UTF-8?q?=E5=BA=94=E7=94=A8=E9=80=89=E6=8B=A9=E5=99=A8=E6=9B=BF=E4=BB=A3?= =?UTF-8?q?=E4=BC=9A=E8=AF=9D=E9=80=89=E6=8B=A9=E5=99=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 会话按 bundleId 归并为应用条目,下拉显示「N 个会话 · M 条」 - 事件读取走 /api/apps//events,seq 归一为应用级连续序号 - 中转放行 /api/apps//events 路由 - 面板文案从「设备会话」改为「应用记录/切换应用」 --- src/idh/cli.py | 4 +- src/idh/panel-device.js | 82 ++++++++++++++++++++++++++++------------- src/idh/panel.html | 26 +++++++------ 3 files changed, 73 insertions(+), 39 deletions(-) diff --git a/src/idh/cli.py b/src/idh/cli.py index fdc991e..7c3c6f0 100755 --- a/src/idh/cli.py +++ b/src/idh/cli.py @@ -807,6 +807,7 @@ def _run_auto_update(args: argparse.Namespace) -> None: _PANEL_SESSION_ROUTE = re.compile(r"/api/sessions(?:/[A-Za-z0-9_-]{1,64}(?:/events)?)?") +_PANEL_APP_EVENTS_ROUTE = re.compile(r"/api/apps/[A-Za-z0-9][A-Za-z0-9._-]{0,254}/events") _PANEL_SETTINGS_ROUTE = "/api/session-settings" _PANEL_SETTINGS_MAX_BYTES = 4096 # 设备侧注入接口(GET 读 / POST 写)与本机设备注册表 @@ -1076,12 +1077,13 @@ def do_GET(self) -> None: session_route = _PANEL_SESSION_ROUTE.fullmatch(target.path) and ( not target.query or target.path.endswith("/events") ) + app_events_route = _PANEL_APP_EVENTS_ROUTE.fullmatch(target.path) if not target.query and target.path in {"/", "/index.html"}: body = page kind = "text/html; charset=utf-8" elif not target.query and target.path in assets: body, kind = assets[target.path] - elif session_route or self.path == "/health" or ( + elif session_route or app_events_route or self.path == "/health" or ( not target.query and target.path in _PANEL_DEVICE_READ ): if current["endpoint"] is None: diff --git a/src/idh/panel-device.js b/src/idh/panel-device.js index 10e27a9..b75cbeb 100644 --- a/src/idh/panel-device.js +++ b/src/idh/panel-device.js @@ -103,22 +103,44 @@ return epoch > 0 && epoch <= 8640000000000000 ? format.format(epoch) : ""; } + // 数据按 App 组织:会话按 bundleId 归并为一个应用条目。 + // 条目保留 session 形状(sessionId=bundleId),复用现有下拉渲染。 + function appsFrom(sessions) { + const map = new Map(); + for (const s of sessions) { + let app = map.get(s.bundleId); + if (!app) { + app = {sessionId: s.bundleId, bundleId: s.bundleId, createdAtMs: s.createdAtMs, + status: s.status, count: 0, sessions: 0}; + map.set(s.bundleId, app); + } + app.count += s.count; + app.sessions += 1; + if (s.createdAtMs > app.createdAtMs) { + app.createdAtMs = s.createdAtMs; + app.status = s.status; + } + } + return [...map.values()]; + } + function selectOptions(sessions) { + const apps = appsFrom(sessions); if (controls?.sessionOptions) { - controls.sessionOptions(sessions, selected); + controls.sessionOptions(apps, selected); return; } const menu = document.getElementById("idh-session"); - const options = sessions.map((session) => [session.sessionId, [ - session.bundleId, formatted(session.createdAtMs), stateLabels[session.status], session.count + " 条" + const options = apps.map((app) => [app.bundleId, [ + app.bundleId, formatted(app.createdAtMs), stateLabels[app.status], app.count + " 条" ].filter(Boolean).join(" · ")]); - if (!options.length) options.push(["", "没有可读取的会话"]); + if (!options.length) options.push(["", "没有可读取的应用记录"]); if (JSON.stringify(options) !== menu.dataset.options) { menu.replaceChildren(...options.map(([value, label]) => new Option(label, value))); menu.dataset.options = JSON.stringify(options); } menu.value = selected; - menu.disabled = !sessions.length; + menu.disabled = !apps.length; } function changeSelection(id) { @@ -142,7 +164,7 @@ if (!health.ok) throw new Error("设备连接不可用"); const device = await health.json(); const sessions = history.ok ? (await history.json()).sessions : []; - if (!sessions.some((session) => session.sessionId === selected)) changeSelection(sessions[0]?.sessionId || ""); + if (!sessions.some((session) => session.bundleId === selected)) changeSelection(sessions[0]?.bundleId || ""); selectOptions(sessions); const notice = document.getElementById("idh-session-notice"); notice.textContent = history.ok ? "" : "设备在线,会话暂时无法读取。"; @@ -157,40 +179,48 @@ } } - async function readEvents(session) { + // 读所选 App 的连续时间线:跨会话按 appSeq 升序翻页,最后倒序成最新在前 + async function readEvents(app, expected) { const result = []; - const path = "/api/sessions/" + encodeURIComponent(session.sessionId) + "/events"; - const through = session.lastSeq; + const path = "/api/apps/" + encodeURIComponent(app.bundleId) + "/events"; let cursor = 0; - for (let index = 0; result.length < session.count && index < 20; ++index) { - const page = await realFetch(path + "?limit=100&after_seq=" + cursor); - if (!page.ok) throw new Error("设备会话摘要暂时无法读取"); + for (let index = 0; result.length < expected && index < 80; ++index) { + const page = await realFetch(path + "?limit=500&after=" + cursor); + if (!page.ok) throw new Error("设备摘要暂时无法读取"); const data = await page.json(); for (const event of data.events) { - if (event.seq <= cursor) throw new Error("设备摘要序号重复或倒退"); - if (event.seq > through) break; - result.push(event); - cursor = event.seq; + if (event.appSeq <= cursor) throw new Error("设备摘要序号重复或倒退"); + // seq 归一为应用级连续序号:下游排序/选择/详情/搜索按应用时间线工作 + result.push({...event, seq: event.appSeq}); + cursor = event.appSeq; } - if (!data.events.length || !data.hasMore || cursor >= through) break; + if (!data.hasMore) break; } - if (result.length !== session.count || cursor !== through) throw new Error("已保存摘要与会话快照不一致,请刷新"); + if (result.length !== expected) throw new Error("已保存摘要与应用快照不一致,请刷新"); return result.reverse(); } async function snapshot() { const {device, sessions} = await inspectDevice(); - const session = sessions.find((item) => item.sessionId === selected); - if (!session) return {device, session: null, events: []}; - const key = [session.sessionId, session.count, session.lastSeq].join("/"); + const appSessions = sessions.filter((item) => item.bundleId === selected); + if (!appSessions.length) return {device, session: null, events: []}; + const latest = appSessions[0]; + const expected = appSessions.reduce((sum, item) => sum + item.count, 0); + const live = device.apps.find((app) => app.bundleId === selected); + const key = [selected, expected, latest.lastSeq].join("/"); if (loaded?.key !== key) { - const pending = readEvents(session); + const pending = readEvents(latest, expected); loaded = {key, pending}; pending.catch(() => { if (loaded?.pending === pending) loaded = null; }); } const events = await loaded.pending; + // session 保留最新会话的形状:既有渲染(进程代、状态、计数)继续可用, + // 计数与序号提升为应用级(跨会话汇总),并附加会话数。 + const session = {...latest, count: expected, lastSeq: events[0]?.appSeq ?? 0, + sessions: appSessions.length, + processGeneration: live?.processGeneration ?? latest.processGeneration}; return {device, session, events}; } @@ -212,7 +242,7 @@ ["记录更新", event.update ? "是" : ""] ].filter(([, value]) => value !== undefined && value !== "").map(([label, value]) => label + " " + value).join("\n"); return { - seq: event.seq, category: event.category, categoryName: classes[event.category], + seq: event.appSeq ?? event.seq, category: event.category, categoryName: classes[event.category], algorithm: labels[event.category] + "事件", operation: phases[event.phase] || "摘要", timestamp: formatted(event.timeMs), detail, preview: "" }; @@ -276,7 +306,7 @@ const data = await snapshot(); if (pathname !== "/api/logs") { const seq = Number(pathname.split("/").pop()); - const event = data.events.find((item) => item.seq === seq); + const event = data.events.find((item) => (item.appSeq ?? item.seq) === seq); return event ? response(asLog(event)) : response({error: "unknown_event"}, 404); } const since = Number(searchParams.get("since") || 0); @@ -319,7 +349,7 @@ const url = URL.createObjectURL(blob); const link = document.createElement("a"); link.href = url; - link.download = diagnose ? "idhjd-device-diagnostics.json" : "idh-session-" + session.sessionId + ".json"; + link.download = diagnose ? "idhjd-device-diagnostics.json" : "idh-app-" + session.bundleId + ".json"; link.click(); setTimeout(() => URL.revokeObjectURL(url), 1000); } catch { @@ -377,7 +407,7 @@ return Object.freeze({ snapshot, choose(id) { - if (!catalog?.sessions.some((session) => session.sessionId === id)) return false; + if (!catalog?.sessions.some((session) => session.bundleId === id)) return false; changeSelection(id); return true; } diff --git a/src/idh/panel.html b/src/idh/panel.html index 15f03d0..92e3bb4 100644 --- a/src/idh/panel.html +++ b/src/idh/panel.html @@ -302,8 +302,8 @@
- - -
+ +
@@ -350,7 +350,7 @@
- - +
+ +
@@ -411,6 +439,20 @@
+ +
+ ? +
+ 未选择 + + +
+ +
+ +
+
+

设备诊断日志

当前设备与所选会话的状态快照
@@ -531,7 +573,7 @@ const highWater = () => state.session?.lastSeq ?? 0; let currentFiltered = [], shownRows = [], currentMenu = ""; let requestSerial = 0, inFlight = false, pageReady = false; - let sessionOptionsKey = ""; + let sheet = null, toastTimer; function toast(text) { @@ -565,7 +607,7 @@ toast("已下载 "+filename); } - const menus = {processPopover:"processBtn",filterMenu:"filterToggleBtn",toolbarMenu:"toolbarMoreBtn"}; + const menus = {deviceMenu:"deviceBtn",filterMenu:"filterToggleBtn",toolbarMenu:"toolbarMoreBtn"}; function setMenu(id,focus=false) { const old=currentMenu; currentMenu=id; @@ -586,35 +628,59 @@ document.addEventListener("click",(e)=>{ if(currentMenu && !e.target.closest("#"+currentMenu+",#"+menus[currentMenu])) setMenu(""); }); - function sessionOptions(sessions,selected) { + // 应用选择对话框:记录 App 在前,已安装无记录的 App 列在后(对齐 ADH 应用选择器) + let appCatalog = {apps:[], installed:[], selected:""}; + function appRows(query) { + const q=(query||"").trim().toLowerCase(); + const match=a=>!q||(a.bundleId+" "+(a.name||"")).toLowerCase().includes(q); + const face=a=>''+esc((a.name||a.bundleId||"?").slice(0,1).toUpperCase())+''; + const stateOf=a=>a.kind==="record" + ? (a.running?"运行中":sessionStatus[a.status]||"会话") + : (a.running?"运行中":""); + const row=a=>''; + const recorded=appCatalog.apps.filter(match); + const recordedIds=new Set(recorded.map(a=>a.bundleId)); + const installed=appCatalog.installed.filter(a=>!recordedIds.has(a.bundleId)&&match(a)); + return (recorded.length?'
记录
'+recorded.map(row).join(""):"")+ + (installed.length?'
已安装
'+installed.map(row).join(""):"")|| + '

没有可读取的应用

'; + } + function paintAppDialog() { + const info=appCatalog.apps.find((s)=>s.bundleId===appCatalog.selected); + const installedInfo=appCatalog.installed.find((a)=>a.bundleId===appCatalog.selected); + const name=info?.name||installedInfo?.name||appCatalog.selected; + $("appFaceLetter").textContent=(name||installedInfo?.name||appCatalog.selected||"?").slice(0,1).toUpperCase()||"?"; + $("appDialogName").textContent=name||"未选择"; + $("appDialogPkg").textContent=appCatalog.selected||""; + $("appDialogState").textContent=info + ? (info.running?"运行中":sessionStatus[info.status]||"会话")+" · "+info.count+" 条 · "+fmt(longTime,info.createdAtMs) + : appCatalog.selected?"没有此应用的记录":""; + const query=$("appSearch").value; + $("appChoices").innerHTML=appRows(query); + } + function sessionOptions(sessions,selected,installed) { + appCatalog={apps:sessions,installed:installed||[],selected}; const info=sessions.find((s)=>s.sessionId===selected); - $("session-title").textContent=info?.bundleId || "应用记录"; + $("session-title").textContent=info?.name||info?.bundleId || "应用记录"; $("session-meta").textContent=info ? [sessionStatus[info.status] || "会话",fmt(longTime,info.createdAtMs), (info.sessions>1?info.sessions+" 个会话 · ":"")+info.count+" 条"].join(" · ") : "暂无可读取的应用记录"; - const key=JSON.stringify(sessions.map((s)=>[s.sessionId,s.bundleId,s.status,s.count,s.createdAtMs]))+selected; - if(key===sessionOptionsKey) return; - sessionOptionsKey=key; - const focused=$("idh-session").contains(document.activeElement)?document.activeElement.dataset.session:""; - $("idh-session").innerHTML=sessions.length?sessions.map((s)=>{ - const selectedRow=s.sessionId===selected; - return ''; - }).join(""):''; - if(focused && currentMenu==="processPopover") all("[data-session]",$("idh-session")).find((el)=>el.dataset.session===focused)?.focus(); + paintAppDialog(); } - $("idh-session").addEventListener("click",(event)=>{ - const option=event.target.closest("[data-session]"); - if(option && source.choose(option.dataset.session)) setMenu("",true); + $("processBtn").addEventListener("click",()=>{ + setMenu(""); + paintAppDialog(); + $("appDialog").showModal(); + $("appSearch").focus(); }); - $("idh-session").addEventListener("keydown",(event)=>{ - if(!["ArrowDown","ArrowUp","Home","End"].includes(event.key)) return; - const options=all("[data-session]",$("idh-session")), current=options.indexOf(document.activeElement); - if(!options.length) return; - event.preventDefault(); - const index=event.key==="Home"?0:event.key==="End"?options.length-1: - Math.max(0,Math.min(options.length-1,current+(event.key==="ArrowDown"?1:-1))); - options[index].focus(); + $("appDialogClose").addEventListener("click",()=>$("appDialog").close()); + $("appSearch").addEventListener("input",()=>{$("appChoices").innerHTML=appRows($("appSearch").value);}); + $("appChoices").addEventListener("click",(event)=>{ + const option=event.target.closest("[data-app]"); + if(option && source.choose(option.dataset.app)) $("appDialog").close(); }); const source=panel.workspace({ sessionOptions, @@ -998,7 +1064,7 @@ if(scope!=="session"&&!categories){toast("请先选择事件板块");return;} const events=(scope==="filtered"?currentFiltered:scope==="board"?state.events.filter((event)=>categories.includes(event.category)):state.events).map(cleanEvent); const suffix=scope==="board"?"-"+state.tab:scope==="filtered"?"-filtered":""; - download("idh-session-"+state.session.sessionId+suffix+".json",json({session:state.session,events})); + download("idh-app-"+state.session.bundleId+suffix+".json",json({session:state.session,events})); } let pendingClear=null; function askClearDisplay() { @@ -1277,12 +1343,15 @@ }); const usb=usbRows.map((udid)=>''); $("idh-devices").innerHTML=(saved.length||usb.length)?saved.concat(usb).join(""):''; + const current=deviceRows.find((d)=>d.selected); + $("deviceTitle").textContent=current?current.address:"未连接"; + $("deviceLink").textContent=current?((current.transport==="usb"?"USB":"LAN")+" · "+(current.online?"在线":"离线")):""; } async function loadDevices() { try{const data=await (await fetch("/api/devices")).json();deviceRows=data.devices||[];usbRows=data.usb||[];}catch{deviceRows=[];usbRows=[];} renderDevices(); } - $("processBtn").addEventListener("click",loadDevices); + $("deviceBtn").addEventListener("click",loadDevices); $("idh-devices").addEventListener("click",async(event)=>{ const remove=event.target.closest("[data-remove]"); if(remove){event.stopPropagation();await post({action:"remove",id:remove.dataset.remove});loadDevices();return;} diff --git a/tests/test_device_select.py b/tests/test_device_select.py index 0e8d149..07fe780 100644 --- a/tests/test_device_select.py +++ b/tests/test_device_select.py @@ -213,7 +213,7 @@ def publish_server(server: ThreadingHTTPServer) -> None: try: with urlopen(base + "/", timeout=3) as response: page = response.read().decode() - assert "id='idh-session'" in page and "id='tabbar'" in page + assert "id='appChoices'" in page and "id='tabbar'" in page assert "class='splitter'" in page and 'class="hdr-raven"' in page with urlopen(base + "/panel-device.js", timeout=3) as response: assert b"IDHDevicePanel" in response.read() From 6d0271927c49c1024825f4d00de67a80a497900b Mon Sep 17 00:00:00 2001 From: taisuii <93462725+taisuii@users.noreply.github.com> Date: Tue, 24 Nov 2026 10:16:36 +0800 Subject: [PATCH 07/20] =?UTF-8?q?feat:=20=E5=BA=94=E7=94=A8=E5=AF=B9?= =?UTF-8?q?=E8=AF=9D=E6=A1=86=E8=A1=8C=E5=86=85=E6=B3=A8=E5=85=A5=E5=8B=BE?= =?UTF-8?q?=E9=80=89=E2=80=94=E2=80=94=E5=8B=BE=E9=80=89=E5=8D=B3=E5=86=99?= =?UTF-8?q?=E6=B3=A8=E5=85=A5=E8=8C=83=E5=9B=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 记录/已安装每行前置复选框,change 即 POST /api/injection-scope 生效 - 与注入范围表共享 injectData/injectPending:运行中应用勾选后标「重启生效」按钮,点击 relaunch - 系统应用与 com.apple.* 出占位槽不可勾选;勾选/重启点击不触发应用切换 - 打开对话框即拉取 /api/apps 刷新范围;行改 div 以容纳交互控件,保留 Enter 选择 --- src/idh/panel.html | 55 ++++++++++++++++++++++++++++++++++++---------- 1 file changed, 44 insertions(+), 11 deletions(-) diff --git a/src/idh/panel.html b/src/idh/panel.html index dfac9bc..65b2053 100644 --- a/src/idh/panel.html +++ b/src/idh/panel.html @@ -111,6 +111,10 @@ .app-item:hover,.app-item.active { background:var(--surface-3) } .app-item .app-face { width:32px; height:32px } .app-item .app-letter { width:32px; height:32px; border-radius:7px; font-size:13px } + .app-check { width:16px; height:16px; margin:0; flex:none; accent-color:#007aff } + .app-check:disabled { opacity:.4 } + .app-check-slot { width:16px; flex:none } + .app-mini { margin-left:8px; flex:none } .app-copy { display:flex; flex-direction:column; min-width:0; flex:1 } .app-name { overflow:hidden; color:var(--ink); font-size:13px; font-weight:600; text-overflow:ellipsis; white-space:nowrap } .app-pkg { overflow:hidden; color:var(--muted); font:10px/1.3 ui-monospace,SFMono-Regular,Consolas,monospace; text-overflow:ellipsis; white-space:nowrap } @@ -637,9 +641,16 @@ const stateOf=a=>a.kind==="record" ? (a.running?"运行中":sessionStatus[a.status]||"会话") : (a.running?"运行中":""); - const row=a=>''; + ''+esc(stateOf(a))+(a.count?' · '+a.count+' 条':"")+''+ + (injectPending.has(a.bundleId)?'':"")+'
'; const recorded=appCatalog.apps.filter(match); const recordedIds=new Set(recorded.map(a=>a.bundleId)); const installed=appCatalog.installed.filter(a=>!recordedIds.has(a.bundleId)&&match(a)); @@ -675,10 +686,23 @@ paintAppDialog(); $("appDialog").showModal(); $("appSearch").focus(); + loadInject().then(paintAppDialog); }); $("appDialogClose").addEventListener("click",()=>$("appDialog").close()); $("appSearch").addEventListener("input",()=>{$("appChoices").innerHTML=appRows($("appSearch").value);}); + $("appChoices").addEventListener("change",(event)=>{ + const box=event.target.closest("[data-inject]"); + if(box)void toggleScope(box.dataset.inject,box.checked).then(paintAppDialog); + }); $("appChoices").addEventListener("click",(event)=>{ + if(event.target.closest("[data-inject]"))return; + const relaunch=event.target.closest("[data-relaunch]"); + if(relaunch){void relaunchBundle(relaunch.dataset.relaunch).then(paintAppDialog);return;} + const option=event.target.closest("[data-app]"); + if(option && source.choose(option.dataset.app)) $("appDialog").close(); + }); + $("appChoices").addEventListener("keydown",(event)=>{ + if(event.key!=="Enter"||event.target.closest("[data-inject],[data-relaunch]"))return; const option=event.target.closest("[data-app]"); if(option && source.choose(option.dataset.app)) $("appDialog").close(); }); @@ -1399,23 +1423,32 @@ } $("injectRefresh").addEventListener("click",()=>loadInject(true)); $("injectQ").addEventListener("input",renderInject); + async function toggleScope(id,on){ + let data; + try{data=await (await fetch("/api/injection-scope",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({[on?"add":"remove"]:[id]})})).json();} + catch{toast("注入范围更新失败");return false;} + if(data.error){toast("注入范围更新失败");return false;} + const app=(injectData?.apps||[]).find((a)=>a.bundleId===id); + if(app&&app.running)injectPending.add(id);else injectPending.delete(id); + injectData.scope=data.scope||injectData.scope; + return true; + } + async function relaunchBundle(id){ + await fetch("/api/apps/relaunch",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({bundleId:id})}); + injectPending.delete(id); + setTimeout(()=>loadInject(true),1500); + } $("injectRows").addEventListener("change",async(event)=>{ const box=event.target.closest("[data-inject]");if(!box)return; box.disabled=true; - const id=box.dataset.inject, action=box.checked?"add":"remove"; - const data=await (await fetch("/api/injection-scope",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({[action]:[id]})})).json(); - if(data.error){box.disabled=false;box.checked=!box.checked;return;} - const app=(injectData?.apps||[]).find((a)=>a.bundleId===id); - if(app&&app.running)injectPending.add(id); - injectData.scope=data.scope||injectData.scope; + await toggleScope(box.dataset.inject,box.checked); renderInject(); }); $("injectRows").addEventListener("click",async(event)=>{ const btn=event.target.closest("[data-relaunch]");if(!btn)return; btn.disabled=true; - await fetch("/api/apps/relaunch",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({bundleId:btn.dataset.relaunch})}); - injectPending.delete(btn.dataset.relaunch); - setTimeout(()=>loadInject(true),1500); + await relaunchBundle(btn.dataset.relaunch); + renderInject(); }); buildTabs();setWidth(view.width);setMenu("");render(true);pageReady=true; From 9763bc628f62121c0c453d60bd50cc4cec9de5bd Mon Sep 17 00:00:00 2001 From: taisuii <93462725+taisuii@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:43:15 +0800 Subject: [PATCH 08/20] =?UTF-8?q?feat:=20=E5=BA=94=E7=94=A8=E5=AF=B9?= =?UTF-8?q?=E8=AF=9D=E6=A1=86=E6=98=BE=E7=A4=BA=E7=9C=9F=E5=AE=9E=E5=9B=BE?= =?UTF-8?q?=E6=A0=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - /api/apps//icon 经面板二进制中转(image/png),不再 JSON 包装 - 行图标位与对话框头换 ,加载失败自动回退字母 - 切设备/切应用时头图标按 selected 刷新,缓存命中直接显 --- src/idh/cli.py | 23 +++++++++++++++++++++++ src/idh/panel.html | 12 ++++++++++-- 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/src/idh/cli.py b/src/idh/cli.py index 7c3c6f0..215c78b 100755 --- a/src/idh/cli.py +++ b/src/idh/cli.py @@ -808,6 +808,7 @@ def _run_auto_update(args: argparse.Namespace) -> None: _PANEL_SESSION_ROUTE = re.compile(r"/api/sessions(?:/[A-Za-z0-9_-]{1,64}(?:/events)?)?") _PANEL_APP_EVENTS_ROUTE = re.compile(r"/api/apps/[A-Za-z0-9][A-Za-z0-9._-]{0,254}/events") +_PANEL_APP_ICON_ROUTE = re.compile(r"/api/apps/[A-Za-z0-9][A-Za-z0-9._-]{0,254}/icon") _PANEL_SETTINGS_ROUTE = "/api/session-settings" _PANEL_SETTINGS_MAX_BYTES = 4096 # 设备侧注入接口(GET 读 / POST 写)与本机设备注册表 @@ -831,6 +832,14 @@ def _panel_request( return response.status, json.loads(payload) if payload else None +def _panel_blob(endpoint: AppEndpoint, path: str) -> tuple[int, bytes]: + endpoint = resolve_endpoint(endpoint) + with contextlib.closing(HTTPConnection(endpoint.primary_address, endpoint.port, timeout=3)) as connection: + connection.request("GET", path, headers={"Accept": "image/png"}) + response = connection.getresponse() + return response.status, response.read() if response.status == 200 else b"" + + def _run_panel(args: argparse.Namespace) -> int: from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer @@ -1083,6 +1092,20 @@ def do_GET(self) -> None: kind = "text/html; charset=utf-8" elif not target.query and target.path in assets: body, kind = assets[target.path] + elif not target.query and _PANEL_APP_ICON_ROUTE.fullmatch(target.path): + if current["endpoint"] is None: + self.send_error(502) + return + try: + code, blob = _panel_blob(current["endpoint"], self.path) + except (HTTPException, OSError, ValueError, UsageError): + self.send_error(502) + return + if code != 200 or not blob: + self.send_error(404) + return + self.write_body(200, blob, "image/png") + return elif session_route or app_events_route or self.path == "/health" or ( not target.query and target.path in _PANEL_DEVICE_READ ): diff --git a/src/idh/panel.html b/src/idh/panel.html index 65b2053..7900686 100644 --- a/src/idh/panel.html +++ b/src/idh/panel.html @@ -115,6 +115,8 @@ .app-check:disabled { opacity:.4 } .app-check-slot { width:16px; flex:none } .app-mini { margin-left:8px; flex:none } + .app-ico-img { position:absolute; inset:0; width:100%; height:100%; object-fit:cover; border-radius:9px } + .app-item .app-ico-img { border-radius:7px } .app-copy { display:flex; flex-direction:column; min-width:0; flex:1 } .app-name { overflow:hidden; color:var(--ink); font-size:13px; font-weight:600; text-overflow:ellipsis; white-space:nowrap } .app-pkg { overflow:hidden; color:var(--muted); font:10px/1.3 ui-monospace,SFMono-Regular,Consolas,monospace; text-overflow:ellipsis; white-space:nowrap } @@ -445,7 +447,7 @@
- ? + ?
未选择 @@ -637,7 +639,7 @@ function appRows(query) { const q=(query||"").trim().toLowerCase(); const match=a=>!q||(a.bundleId+" "+(a.name||"")).toLowerCase().includes(q); - const face=a=>''+esc((a.name||a.bundleId||"?").slice(0,1).toUpperCase())+''; + const face=a=>''+esc((a.name||a.bundleId||"?").slice(0,1).toUpperCase())+''; const stateOf=a=>a.kind==="record" ? (a.running?"运行中":sessionStatus[a.status]||"会话") : (a.running?"运行中":""); @@ -663,6 +665,12 @@ const installedInfo=appCatalog.installed.find((a)=>a.bundleId===appCatalog.selected); const name=info?.name||installedInfo?.name||appCatalog.selected; $("appFaceLetter").textContent=(name||installedInfo?.name||appCatalog.selected||"?").slice(0,1).toUpperCase()||"?"; + const faceImg=$("appFaceImg"); + faceImg.hidden=true; + if(appCatalog.selected){ + faceImg.src="/api/apps/"+encodeURIComponent(appCatalog.selected)+"/icon"; + if(faceImg.complete&&faceImg.naturalWidth)faceImg.hidden=false; + } $("appDialogName").textContent=name||"未选择"; $("appDialogPkg").textContent=appCatalog.selected||""; $("appDialogState").textContent=info From 070e0c2d18b876265fa3c4d5f637f9c09cb8315d Mon Sep 17 00:00:00 2001 From: taisuii <93462725+taisuii@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:48:05 +0800 Subject: [PATCH 09/20] =?UTF-8?q?fix:=20=E9=9D=A2=E6=9D=BF=E5=AE=9E?= =?UTF-8?q?=E6=B5=8B=E4=BF=AE=E5=A4=8D=E2=80=94=E2=80=94=E6=89=8B=E5=8A=A8?= =?UTF-8?q?=E7=AB=AF=E7=82=B9=E8=AE=BE=E5=A4=87=E5=8C=96=E3=80=81scope=20?= =?UTF-8?q?=E5=86=99=E6=A0=A1=E9=AA=8C=E3=80=81=E9=87=8D=E7=BB=98=E4=B8=8E?= =?UTF-8?q?=E7=8A=B6=E6=80=81=E4=B8=80=E8=87=B4=E6=80=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - device_pool:--endpoint 手动设备并入设备列表与 select,多设备在线时面板取第一台而非拒绝启动 - POST /api/injection-scope 缺省 add/remove 键不再误判 400(行内勾选此前全部失败) - /api/devices 空指针修复;探测超时 1s→3s 防转发链路易判离线 - 设备按钮在线态改用会话实际连通状态,不再用菜单打开瞬间的探测快照 - appChoices/injectRows 加 HTML 签名,内容不变跳过重绘,保住滚动与勾选交互 - 应用对话框与注入表把可注入应用排在系统应用之前;设备按钮启动即填充 --- src/idh/cli.py | 35 ++++++++++++++++++++++++----------- src/idh/panel.html | 34 +++++++++++++++++++++++++--------- 2 files changed, 49 insertions(+), 20 deletions(-) diff --git a/src/idh/cli.py b/src/idh/cli.py index 215c78b..8a95c4e 100755 --- a/src/idh/cli.py +++ b/src/idh/cli.py @@ -90,11 +90,11 @@ def _pick_usb_endpoint(udid: str | None = None) -> AppEndpoint: return usb_endpoint(matches[0]["udid"]) -def _probed_endpoints(endpoints: Sequence[AppEndpoint]) -> list[AppEndpoint]: +def _probed_endpoints(endpoints: Sequence[AppEndpoint], *, timeout: float = 1.0) -> list[AppEndpoint]: if not endpoints: return [] with ThreadPoolExecutor(max_workers=min(8, len(endpoints))) as pool: - return list(pool.map(probe_endpoint, (resolve_endpoint(e) for e in endpoints))) + return list(pool.map(lambda e: probe_endpoint(resolve_endpoint(e), timeout=timeout), endpoints)) def _endpoint_label(endpoint: AppEndpoint) -> str: @@ -847,7 +847,12 @@ def _run_panel(args: argparse.Namespace) -> int: try: endpoint = _resolve_device(endpoints, None, command="panel") except SystemExit: - endpoint = None # 零设备启动:面板照常起,由页面里的设备入口添加 + # 多设备在线不报错退出:取第一台在线设备,页面里可切换 + endpoint = next( + (e for e in _probed_endpoints(endpoints) + if e.kind == "device" and e.properties.get("status") == "online"), + None, + ) # 零设备时为 None:面板照常起,由页面里的设备入口添加 if endpoint is not None and endpoint.kind != "device": print("idh: panel serves a device connection", file=sys.stderr) return 2 @@ -868,10 +873,17 @@ def _run_panel(args: argparse.Namespace) -> int: break current = {"endpoint": endpoint} + def device_pool() -> list[AppEndpoint]: + merged = {e.mcp_url.casefold(): e for e in endpoints} + for entry in load_saved_endpoints(): + if entry.kind == "device": + merged[entry.mcp_url.casefold()] = entry + return list(merged.values()) + def device_records() -> dict: - saved = [item for item in load_saved_endpoints() if item.kind == "device"] - probed = _probed_endpoints(saved) - selected = current["endpoint"].mcp_url + saved = device_pool() + probed = [item for item in _probed_endpoints(saved, timeout=3.0) if item.kind != "app"] + selected = current["endpoint"].mcp_url if current["endpoint"] else "" return { "devices": [ { @@ -974,10 +986,11 @@ def device_action(self, body: bytes) -> None: return target = str(request.get("id") or "") if action == "select": - for saved in load_saved_endpoints(): - if saved.kind == "device" and saved.mcp_url.casefold() == target.casefold(): - save_selected(saved.mcp_url) - current["endpoint"] = saved + for entry in device_pool(): + if entry.mcp_url.casefold() == target.casefold(): + if any(e.mcp_url.casefold() == target.casefold() for e in load_saved_endpoints()): + save_selected(entry.mcp_url) + current["endpoint"] = entry self.write_json(200, device_records()) return self.write_json(404, {"error": "unknown_device"}) @@ -1049,7 +1062,7 @@ def do_POST(self) -> None: self.write_json(400, {"error": "invalid_bundle_id"}) return else: - ids = [request.get(key) for key in ("add", "remove")] + ids = [request.get(key, []) for key in ("add", "remove")] if any(not isinstance(value, list) or len(value) > 256 or any(not _BUNDLE_ID.fullmatch(str(item)) for item in value) for value in ids): diff --git a/src/idh/panel.html b/src/idh/panel.html index 7900686..9e4f5fb 100644 --- a/src/idh/panel.html +++ b/src/idh/panel.html @@ -635,7 +635,7 @@ if(currentMenu && !e.target.closest("#"+currentMenu+",#"+menus[currentMenu])) setMenu(""); }); // 应用选择对话框:记录 App 在前,已安装无记录的 App 列在后(对齐 ADH 应用选择器) - let appCatalog = {apps:[], installed:[], selected:""}; + let appCatalog = {apps:[], installed:[], selected:""}, lastRowsHtml=""; function appRows(query) { const q=(query||"").trim().toLowerCase(); const match=a=>!q||(a.bundleId+" "+(a.name||"")).toLowerCase().includes(q); @@ -655,7 +655,8 @@ (injectPending.has(a.bundleId)?'':"")+'
'; const recorded=appCatalog.apps.filter(match); const recordedIds=new Set(recorded.map(a=>a.bundleId)); - const installed=appCatalog.installed.filter(a=>!recordedIds.has(a.bundleId)&&match(a)); + const installed=appCatalog.installed.filter(a=>!recordedIds.has(a.bundleId)&&match(a)) + .sort((a,b)=>(injectable(a)?0:1)-(injectable(b)?0:1)||String(a.name||a.bundleId).localeCompare(String(b.name||b.bundleId),"zh-Hans-CN")); return (recorded.length?'
记录
'+recorded.map(row).join(""):"")+ (installed.length?'
已安装
'+installed.map(row).join(""):"")|| '

没有可读取的应用

'; @@ -677,7 +678,8 @@ ? (info.running?"运行中":sessionStatus[info.status]||"会话")+" · "+info.count+" 条 · "+fmt(longTime,info.createdAtMs) : appCatalog.selected?"没有此应用的记录":""; const query=$("appSearch").value; - $("appChoices").innerHTML=appRows(query); + const html=appRows(query); + if(html!==lastRowsHtml){$("appChoices").innerHTML=html;lastRowsHtml=html;} } function sessionOptions(sessions,selected,installed) { appCatalog={apps:sessions,installed:installed||[],selected}; @@ -697,7 +699,7 @@ loadInject().then(paintAppDialog); }); $("appDialogClose").addEventListener("click",()=>$("appDialog").close()); - $("appSearch").addEventListener("input",()=>{$("appChoices").innerHTML=appRows($("appSearch").value);}); + $("appSearch").addEventListener("input",paintAppDialog); $("appChoices").addEventListener("change",(event)=>{ const box=event.target.closest("[data-inject]"); if(box)void toggleScope(box.dataset.inject,box.checked).then(paintAppDialog); @@ -812,6 +814,7 @@ const boardDisplay=displayState(), paused=boardDisplay.pauseAt!==null, cleared=boardDisplay.clearThrough!==null; $("footerMode").textContent=paused?"本板块已暂停":cleared?"本板块显示已清空":mode==="ended"?"历史会话 · 只读": mode?(sessionStatus[mode]||"设备会话"):online?"暂无会话":"正在连接"; + paintDeviceChip(); $("footerDot").className="status-dot"+(paused||cleared?" warn":mode==="observing"?" ok":""); $("footerSort").textContent=state.sort==="asc"?"按时间正序":"按时间倒序"; $("count").innerHTML=''+currentFiltered.length+' / '+state.events.length+' 条'; @@ -1370,20 +1373,27 @@ let deviceRows=[],usbRows=[]; function renderDevices() { const saved=deviceRows.map((d)=>{ - const sub=(d.transport==="usb"?"USB · ":"")+(d.online?"在线":"离线"); + const online=d.selected?state.network==="online":d.online; + const sub=(d.transport==="usb"?"USB":"LAN")+" · "+(online?"在线":"离线"); return ''; }); const usb=usbRows.map((udid)=>''); $("idh-devices").innerHTML=(saved.length||usb.length)?saved.concat(usb).join(""):''; + paintDeviceChip(); + } + // 选中设备的在线态以会话请求的实际连通为准,菜单里的探测标记只做行内展示 + function paintDeviceChip() { const current=deviceRows.find((d)=>d.selected); $("deviceTitle").textContent=current?current.address:"未连接"; - $("deviceLink").textContent=current?((current.transport==="usb"?"USB":"LAN")+" · "+(current.online?"在线":"离线")):""; + $("deviceLink").textContent=current?((current.transport==="usb"?"USB":"LAN")+" · "+ + (state.network==="online"?"在线":state.network==="offline"?"离线":"连接中")):""; } async function loadDevices() { try{const data=await (await fetch("/api/devices")).json();deviceRows=data.devices||[];usbRows=data.usb||[];}catch{deviceRows=[];usbRows=[];} renderDevices(); } $("deviceBtn").addEventListener("click",loadDevices); + loadDevices(); $("idh-devices").addEventListener("click",async(event)=>{ const remove=event.target.closest("[data-remove]"); if(remove){event.stopPropagation();await post({action:"remove",id:remove.dataset.remove});loadDevices();return;} @@ -1405,7 +1415,7 @@ }); $("deviceAddr").addEventListener("keydown",(event)=>{if(event.key==="Enter")$("deviceAddBtn").click();}); - let injectData=null, injectAt=0, injectPending=new Set(); + let injectData=null, injectAt=0, injectPending=new Set(), lastInjectHtml=""; function injectRow(app,scope) { const inScope=scope.includes(app.bundleId), sys=app.kind==="system"||app.bundleId.startsWith("com.apple."); const pending=injectPending.has(app.bundleId); @@ -1420,8 +1430,14 @@ if(injectData.error){$("injectError").hidden=false;$("injectError").textContent="注入范围读取失败:"+injectData.error;$("injectRows").innerHTML="";return;} $("injectError").hidden=true; const q=($("injectQ").value||"").trim().toLowerCase(), scope=injectData.scope||[]; - const apps=(injectData.apps||[]).filter((a)=>!q||(a.name+" "+a.bundleId).toLowerCase().includes(q)); - $("injectRows").innerHTML=apps.length?apps.map((a)=>injectRow(a,scope)).join(""):'没有匹配的应用'; + const apps=(injectData.apps||[]).filter((a)=>!q||(a.name+" "+a.bundleId).toLowerCase().includes(q)) + .sort((a,b)=>{ + const sa=a.kind==="system"||a.bundleId.startsWith("com.apple.")?1:0; + const sb=b.kind==="system"||b.bundleId.startsWith("com.apple.")?1:0; + return sa-sb||String(a.name).localeCompare(String(b.name),"zh-Hans-CN"); + }); + const html=apps.length?apps.map((a)=>injectRow(a,scope)).join(""):'没有匹配的应用'; + if(html!==lastInjectHtml){$("injectRows").innerHTML=html;lastInjectHtml=html;} } async function loadInject(force) { if(!force && Date.now()-injectAt<3000)return; From 4990bc240a95b633fa4d5e8866413332d384ce9b Mon Sep 17 00:00:00 2001 From: taisuii <93462725+taisuii@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:54:03 +0800 Subject: [PATCH 10/20] =?UTF-8?q?fix:=20=E5=BA=94=E7=94=A8=E5=AF=B9?= =?UTF-8?q?=E8=AF=9D=E6=A1=86=E8=A7=82=E6=84=9F=E2=80=94=E2=80=94=E5=BA=95?= =?UTF-8?q?=E6=A0=8F=E6=94=B6=E6=88=90=E4=B8=80=E8=A1=8C=E6=91=98=E8=A6=81?= =?UTF-8?q?=E3=80=81=E6=89=93=E5=BC=80=E5=9B=9E=E9=A1=B6=E9=83=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 底部进程详情由 6 行 dt/dd 表格改为一行摘要(状态·PID·会话数·条数), 不再吃掉列表三分之一高度 - 打开对话框时 appChoices 回滚到顶部,不再停留上次的滚动位置 --- src/idh/panel.html | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/src/idh/panel.html b/src/idh/panel.html index 9e4f5fb..8d63da4 100644 --- a/src/idh/panel.html +++ b/src/idh/panel.html @@ -123,7 +123,7 @@ .app-state { flex:none; color:var(--muted); font-size:10px } .app-state.on { color:var(--green) } .app-empty { padding:10px 12px; color:var(--muted); font-size:12px } - .app-dialog-foot { max-height:132px; overflow:auto; border-top:1px solid var(--line-soft) } + .app-dialog-foot { padding:8px 16px 10px; border-top:1px solid var(--line-soft); font-size:11px; color:var(--muted); white-space:nowrap; overflow:hidden; text-overflow:ellipsis } .proc-details { display:grid; grid-template-columns:auto minmax(0,1fr); gap:6px 12px; margin:0; padding:4px 10px 10px; font-size:11.5px } .proc-details dt { color:var(--muted) } .proc-details dd { margin:0; overflow-wrap:anywhere } @@ -457,7 +457,7 @@
-
+
@@ -695,6 +695,7 @@ setMenu(""); paintAppDialog(); $("appDialog").showModal(); + $("appChoices").scrollTop=0; $("appSearch").focus(); loadInject().then(paintAppDialog); }); @@ -794,13 +795,11 @@ const stale=state.network==="offline"; const label=active?(stale?"上次登记为在线":"在线,已登记"): session?.status==="ended"?"历史会话,未见对应进程在线":session?"未见登记":"无在线进程"; - const pairs=[["状态",label], - ["App",active?.bundleId??session?.bundleId??"—"], - [active?"当前 PID":"会话 PID",active?.pid??session?.pid??"—"], - ["进程代",active?.processGeneration??session?.processGeneration??"—"]]; - if(session)pairs.push(["会话数",String(session.sessions??1)],["最新会话",session.sessionId], - ["已提交",String(session.count)+" 条"],["最新序号",session.lastSeq??"—"]); - $("procinfo").innerHTML=pairs.map(([label,value])=>'
'+esc(label)+'
'+esc(value)+'
').join(""); + const foot=[label, + "PID "+(active?.pid??session?.pid??"—"), + session?String(session.sessions??1)+" 个会话":null, + session?String(session.count)+" 条":null].filter(Boolean).join(" · "); + $("procinfo").textContent=foot; $("dumpApp").textContent=session?.bundleId??"无当前应用"; } function renderIndicators() { From 01763acb9220f2f0519924ad9ed51bc7512d1416 Mon Sep 17 00:00:00 2001 From: taisuii <93462725+taisuii@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:00:46 +0800 Subject: [PATCH 11/20] =?UTF-8?q?fix:=20=E5=BA=94=E7=94=A8=E5=AF=B9?= =?UTF-8?q?=E8=AF=9D=E6=A1=86=E5=8F=AF=E9=80=89=E5=B7=B2=E5=AE=89=E8=A3=85?= =?UTF-8?q?=E6=97=A0=E8=AE=B0=E5=BD=95=E5=BA=94=E7=94=A8=EF=BC=9B=E8=AE=BE?= =?UTF-8?q?=E5=A4=87=E8=8F=9C=E5=8D=95=E9=80=89=E4=B8=AD=E8=A1=8C=E7=8A=B6?= =?UTF-8?q?=E6=80=81=E5=AE=9E=E6=97=B6=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - choose 此前只认有记录的 bundleId,点已安装应用行无反应、对话框不关; inspectDevice 每轮还会把选中强制拉回第一个有记录的 App - 无记录应用选中后标题取已安装名称,meta 显示暂无此应用的记录 - 设备菜单选中行的在线态随 paintDeviceChip 实时刷新,不再冻结打开瞬间状态 - 底栏摘要不再为无进程应用输出 PID — --- src/idh/panel-device.js | 9 +++++++-- src/idh/panel.html | 12 ++++++++---- 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/src/idh/panel-device.js b/src/idh/panel-device.js index 09cc85a..6286c81 100644 --- a/src/idh/panel-device.js +++ b/src/idh/panel-device.js @@ -155,7 +155,10 @@ const device = await health.json(); const sessions = history.ok ? (await history.json()).sessions : []; const installed = installedRes.ok ? (await installedRes.json()).apps || [] : []; - if (!sessions.some((session) => session.bundleId === selected)) changeSelection(sessions[0]?.bundleId || ""); + const known = selected + && (sessions.some((session) => session.bundleId === selected) + || installed.some((app) => app.bundleId === selected)); + if (!known) changeSelection(sessions[0]?.bundleId || installed[0]?.bundleId || ""); selectOptions(sessions, installed); const notice = document.getElementById("idh-session-notice"); notice.textContent = history.ok ? "" : "设备在线,会话暂时无法读取。"; @@ -397,7 +400,9 @@ return Object.freeze({ snapshot, choose(id) { - if (!catalog?.sessions.some((session) => session.bundleId === id)) return false; + const known = catalog?.sessions.some((session) => session.bundleId === id) + || catalog?.installed?.some((app) => app.bundleId === id); + if (!known) return false; changeSelection(id); return true; } diff --git a/src/idh/panel.html b/src/idh/panel.html index 8d63da4..11969b9 100644 --- a/src/idh/panel.html +++ b/src/idh/panel.html @@ -684,11 +684,12 @@ function sessionOptions(sessions,selected,installed) { appCatalog={apps:sessions,installed:installed||[],selected}; const info=sessions.find((s)=>s.sessionId===selected); - $("session-title").textContent=info?.name||info?.bundleId || "应用记录"; + const instName=appCatalog.installed.find((a)=>a.bundleId===selected)?.name; + $("session-title").textContent=info?.name||instName||info?.bundleId||selected || "应用记录"; $("session-meta").textContent=info ? [sessionStatus[info.status] || "会话",fmt(longTime,info.createdAtMs), (info.sessions>1?info.sessions+" 个会话 · ":"")+info.count+" 条"].join(" · ") - : "暂无可读取的应用记录"; + : "暂无此应用的记录"; paintAppDialog(); } $("processBtn").addEventListener("click",()=>{ @@ -796,7 +797,7 @@ const label=active?(stale?"上次登记为在线":"在线,已登记"): session?.status==="ended"?"历史会话,未见对应进程在线":session?"未见登记":"无在线进程"; const foot=[label, - "PID "+(active?.pid??session?.pid??"—"), + (active?.pid||session?.pid)?"PID "+(active?.pid??session?.pid):null, session?String(session.sessions??1)+" 个会话":null, session?String(session.count)+" 条":null].filter(Boolean).join(" · "); $("procinfo").textContent=foot; @@ -1384,8 +1385,11 @@ function paintDeviceChip() { const current=deviceRows.find((d)=>d.selected); $("deviceTitle").textContent=current?current.address:"未连接"; - $("deviceLink").textContent=current?((current.transport==="usb"?"USB":"LAN")+" · "+ + const link=current?((current.transport==="usb"?"USB":"LAN")+" · "+ (state.network==="online"?"在线":state.network==="offline"?"离线":"连接中")):""; + $("deviceLink").textContent=link; + const row=$("idh-devices")?.querySelector('.dropdown-item[aria-selected="true"] .dropdown-sub'); + if(row&&link)row.textContent=link; } async function loadDevices() { try{const data=await (await fetch("/api/devices")).json();deviceRows=data.devices||[];usbRows=data.usb||[];}catch{deviceRows=[];usbRows=[];} From 180de02e690157e82c8921fa601719eb48a28bba Mon Sep 17 00:00:00 2001 From: taisuii <93462725+taisuii@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:03:22 +0800 Subject: [PATCH 12/20] =?UTF-8?q?fix:=20=E6=A8=A1=E6=80=81=E6=A1=86?= =?UTF-8?q?=E7=82=B9=E9=81=AE=E7=BD=A9=E5=85=B3=E9=97=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 应用对话框等全部 dialog 增加遮罩点击关闭(坐标在框外即关), 此前只能靠 × 或选中行,用户点空白处无法退出 --- src/idh/panel.html | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/idh/panel.html b/src/idh/panel.html index 11969b9..01deba3 100644 --- a/src/idh/panel.html +++ b/src/idh/panel.html @@ -701,6 +701,13 @@ loadInject().then(paintAppDialog); }); $("appDialogClose").addEventListener("click",()=>$("appDialog").close()); + // 模态框统一行为:点遮罩关闭(Escape 由原生 dialog 处理) + for(const dlg of document.querySelectorAll("dialog")){ + dlg.addEventListener("click",(event)=>{ + const r=dlg.getBoundingClientRect(); + if(event.clientXr.right||event.clientYr.bottom)dlg.close(); + }); + } $("appSearch").addEventListener("input",paintAppDialog); $("appChoices").addEventListener("change",(event)=>{ const box=event.target.closest("[data-inject]"); From 1b261a807b40a53ab288ab24cc15adc6a1d0d493 Mon Sep 17 00:00:00 2001 From: taisuii <93462725+taisuii@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:56:56 +0800 Subject: [PATCH 13/20] =?UTF-8?q?refactor:=20=E9=9D=A2=E6=9D=BF=E6=94=B9?= =?UTF-8?q?=E7=94=A8=20Vue=203=20+=20TypeScript=20=E9=87=8D=E5=86=99?= =?UTF-8?q?=EF=BC=8C=E5=AF=B9=E9=BD=90=20ADH=20=E5=89=8D=E7=AB=AF=E6=A0=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit panel/ 为新前端源码(Vite + vite-plugin-singlefile 产出单文件 src/idh/panel.html);panel-device.js 适配层并入 store.ts 后移除。 功能保持:事件板块、应用对话框(侧栏分组/注入勾选)、设备菜单、 注入范围页、设置页(限额/偏好/配置 JSON)、诊断、MCP、字节预览、 暂停清空、导出、分栏拖动与快捷键。 --- panel/.gitignore | 2 + panel/index.html | 14 + panel/package-lock.json | 1414 ++++++++++++++++++++++ panel/package.json | 1 + panel/src/App.vue | 162 +++ panel/src/api.ts | 48 + panel/src/components/AppDialog.vue | 122 ++ panel/src/components/DeviceMenu.vue | 81 ++ panel/src/components/DiagDialog.vue | 38 + panel/src/components/EventBoard.vue | 269 +++++ panel/src/components/EventDetail.vue | 168 +++ panel/src/components/InjectPanel.vue | 55 + panel/src/components/McpDialog.vue | 23 + panel/src/components/SettingsPanel.vue | 213 ++++ panel/src/components/ToolStub.vue | 37 + panel/src/components/WechatDialog.vue | 17 + panel/src/icons.ts | 33 + panel/src/main.ts | 5 + panel/src/model.ts | 123 ++ panel/src/store.ts | 301 +++++ panel/src/style.css | 987 +++++++++++++++ panel/tsconfig.json | 13 + panel/vite.config.ts | 25 + pyproject.toml | 2 +- src/idh/cli.py | 1 - src/idh/panel-device.js | 413 ------- src/idh/panel.html | 1529 +----------------------- tests/test_device_select.py | 9 +- 28 files changed, 4190 insertions(+), 1915 deletions(-) create mode 100644 panel/.gitignore create mode 100644 panel/index.html create mode 100644 panel/package-lock.json create mode 100644 panel/package.json create mode 100644 panel/src/App.vue create mode 100644 panel/src/api.ts create mode 100644 panel/src/components/AppDialog.vue create mode 100644 panel/src/components/DeviceMenu.vue create mode 100644 panel/src/components/DiagDialog.vue create mode 100644 panel/src/components/EventBoard.vue create mode 100644 panel/src/components/EventDetail.vue create mode 100644 panel/src/components/InjectPanel.vue create mode 100644 panel/src/components/McpDialog.vue create mode 100644 panel/src/components/SettingsPanel.vue create mode 100644 panel/src/components/ToolStub.vue create mode 100644 panel/src/components/WechatDialog.vue create mode 100644 panel/src/icons.ts create mode 100644 panel/src/main.ts create mode 100644 panel/src/model.ts create mode 100644 panel/src/store.ts create mode 100644 panel/src/style.css create mode 100644 panel/tsconfig.json create mode 100644 panel/vite.config.ts delete mode 100644 src/idh/panel-device.js diff --git a/panel/.gitignore b/panel/.gitignore new file mode 100644 index 0000000..f06235c --- /dev/null +++ b/panel/.gitignore @@ -0,0 +1,2 @@ +node_modules +dist diff --git a/panel/index.html b/panel/index.html new file mode 100644 index 0000000..31bb892 --- /dev/null +++ b/panel/index.html @@ -0,0 +1,14 @@ + + + + + + + + IOSDecryptHub + + +
+ + + diff --git a/panel/package-lock.json b/panel/package-lock.json new file mode 100644 index 0000000..f279d5f --- /dev/null +++ b/panel/package-lock.json @@ -0,0 +1,1414 @@ +{ + "name": "idh-panel", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "idh-panel", + "version": "0.1.0", + "dependencies": { + "vue": "3.5" + }, + "devDependencies": { + "@vitejs/plugin-vue": "^5.2.4", + "typescript": "5.7", + "vite": "^6.4.6", + "vite-plugin-singlefile": "^2.3.4" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.29.15", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.15.tgz", + "integrity": "sha512-C2FuapQ2Kh1OnVHAoLi5rD3GBJ8COb9Q609T6HEpLqaBAo560PDP5OxBE5dCI/h951MBO/+bCUYU5SZ+8ZlV+w==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", + "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.29.15", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.15.tgz", + "integrity": "sha512-RpKWyisHoP81twtSCgmE02iU0RnPcq1DN5bBEbpUePrjA9Q3wXhufnCJrrayPpoZieqFh3zyZQqwtSK0gGccRA==", + "license": "MIT", + "dependencies": { + "@babel/types": "^7.29.15" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/types": { + "version": "7.29.15", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.15.tgz", + "integrity": "sha512-/XKpKDakL//LZ66bq1XsZOswuqeI5MZqPLDu18o3XdkU1fNJ7bdPtzgnc4ZNS+bBGHV0FJG8jjb8SwcC3nNVQQ==", + "license": "MIT", + "dependencies": { + "@babel/helper-string-parser": "^7.29.15", + "@babel/helper-validator-identifier": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz", + "integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz", + "integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz", + "integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz", + "integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz", + "integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz", + "integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz", + "integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz", + "integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz", + "integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz", + "integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz", + "integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz", + "integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz", + "integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz", + "integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz", + "integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz", + "integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz", + "integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz", + "integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz", + "integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz", + "integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz", + "integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz", + "integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz", + "integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz", + "integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz", + "integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz", + "integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "license": "MIT" + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.68.8", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.68.8.tgz", + "integrity": "sha512-7l9FdeCGjhmMTVePgndK4t9u5tLR+VuTTMoyc0PscqZDdYjS07ZsQ0vQYsWsODu/ZZYPG7WVJwbUZ77n1hVT+w==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.68.8", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.68.8.tgz", + "integrity": "sha512-kXkkIiJujBjArHwEToz99BQqIqibn4xdV6SjsoaxuZzvLUCVEzoHQ1Lp62m7xOhpLRpWpCtxL2ZUy/ADKuz9/g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-x64": { + "version": "4.68.8", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-x64/-/rollup-android-x64-4.68.8.tgz", + "integrity": "sha512-KYoBygnHs3zUOLR0z7SaqhMnUrSF9pbuTOJT/uHK3PrgCXdv/xaMubZD8jCpg6NTo46deasLgZRq38xFTyu8uw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.68.8", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.68.8.tgz", + "integrity": "sha512-YmBUNjgm5bsjOByO+H1TFbuGZe+ZnHcYtPXYj9+L1cwTu/BG8zjuUzO2PH9KwS85P0UH+WJDSb+mQ2hqjp5uBQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.68.8", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.68.8.tgz", + "integrity": "sha512-XMX5ybuOmkwiM13KJtsBxakZ69pyaR9thRYU2fMejhaB0VuzLMIkIc+9TBsu2rv34eEf6XaSMOaLOyEgHGWHTQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.68.8", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.68.8.tgz", + "integrity": "sha512-WuBXScWJDaqPJKwVrotUe1sM9DHWMN937C23RClt0MVHVt7A1rBy285ZfZTLccPEVMxmGJMt2jvdHMOI33lrKA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.68.8", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.68.8.tgz", + "integrity": "sha512-kegwGqP3rMenEMaKo8OzMBb5WvLW2h2jrQ3iKuYptTTF8C/yuxz+hinjBPrtYuIPLJDwxHc/hv2e4u5pmrqo9A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.68.8", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.68.8.tgz", + "integrity": "sha512-Qct0oLM1zGNbvqs1udQnuchg+Q9uHbkMcQqCfs3M7foNn7HvEkUypfFn9o5fklimUI5OF3A2nMknd4/vrEyeVg==", + "cpu": [ + "arm" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.68.8", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.68.8.tgz", + "integrity": "sha512-xTH5vD+lW/5MU3kL/Op8RSSG/O9fxUQZuJcSBmmBeYem9uXYvCq6PDHx/oDSNeyLD/p4pGujG2PVI0R8MjAhSw==", + "cpu": [ + "arm" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.68.8", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.68.8.tgz", + "integrity": "sha512-lPPStmynSHvwWpSrAsuemPFB+EWFObXjwz44EK4Hph47U6SBAk1Kehq5MkI7i8EYVjrXddaAV7YkJH8mX8QSZQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.68.8", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.68.8.tgz", + "integrity": "sha512-kZkvIYAihM6l6M+giSUHayDDf/JL+TYR5bYWiAX7/jUFWvMkMmysA4GV2F0HOsXQNEyctW3x1xLjww1GqW7Q1w==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.68.8", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.68.8.tgz", + "integrity": "sha512-XZKLEIY977OJr6zUtK6nlQcLXme34c8HqVp3+WmKQxKVN6Nj+b9qE3ZHWIDHXznHJsGl2AsaMOgB0GL0fkZGUg==", + "cpu": [ + "loong64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-musl": { + "version": "4.68.8", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.68.8.tgz", + "integrity": "sha512-+sN+Fj6F9suk8SkL6boIfXDmj9iJwSKPCTeCy8/pfTOHuzNX+duhTb9uyj6154oVK8Odl5zgL4DXRZzXjsRKcw==", + "cpu": [ + "loong64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.68.8", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.68.8.tgz", + "integrity": "sha512-EBCu3uDFaGwSodUl+XR8yubvVFUkSo6QK9YAIOV1vljqntzTF2/mXLM6utgLaSGf/8oM+qEe8Ai0Jd4+tyMoIQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-musl": { + "version": "4.68.8", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.68.8.tgz", + "integrity": "sha512-hRC0jWdsLBckCijx2wiUfk7zW1SqEW47yMsCNoDGmQfoqq0AjW+9UYZqxg3LTmG76PyHNdNGBSuspB3CqrhGIA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.68.8", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.68.8.tgz", + "integrity": "sha512-OZKrTRWyGnLITUTipbeXDdtb2dxQPyFk/Fbw9qER8pIvd2Ja9hHELkY0Fv5p9yYYkimqtzVhApKKXGv0cWGQGw==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.68.8", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.68.8.tgz", + "integrity": "sha512-HmhSRSQ+dOeOntPfmYux4rCpOQLtsGbcGLQu4nm8ig3tuVqe/bKfDHorg36LKAqYq4X/nwFr79ImtaFHHsn4ug==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.68.8", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.68.8.tgz", + "integrity": "sha512-wk1Ci1hsMREaBELoKPSnzRAh1oUULI+8kfb2F5vVmTD2IcfR9AKMskCusizZhIAvojOtPZihPj4OdKy6ifZwhQ==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.68.8", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.68.8.tgz", + "integrity": "sha512-mDufoUJ6fnKZnCyjV3sGEDvXQQkM6j1UmINHheGX4Emau3TZWJzX3sCVmbzkNB+W2G84BiFQdDCcF09lv0i0VA==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.68.8", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.68.8.tgz", + "integrity": "sha512-7EGVL9rYRYQZe3UC8JQzfBN9rxk484Rfs4u/yGWumTYKUdJt6tmdP+0Y3qHvAvzJCQ+JQM5rSqZbVyrJARlGpA==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-openbsd-x64": { + "version": "4.68.8", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.68.8.tgz", + "integrity": "sha512-Umklz+QSGwKWQVlVrsMJrwFx1oNRYHgrxSGiZM8pJCMpzWnMDMinDhPILf0BvRXfA1QOArsDcs+AE7Jd6dQxvA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ] + }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.68.8", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.68.8.tgz", + "integrity": "sha512-BlRp6uzQDK5rczAdaXQ8dlSIRFRlkDRBqpb8GGtv8iwZxQdOjoigdFU5t5dcxpnpU0caMoT9mH27MyAl4dWwKw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.68.8", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.68.8.tgz", + "integrity": "sha512-Sc8Mkf/fVfcV0hBJNDRIM82BjS4kJn2Of0jP8dgQ+TodquxtCZ/5D6FgSsY3uN5IBmNi8Zrb/OHd60IEYKaw+Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.68.8", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.68.8.tgz", + "integrity": "sha512-XPTFXclN+I+Cfu3ONWDsw+uvgSZjTJa1B2u2EvtdKlSdgNU6mrOZdgeaMkvN+2T2KPTEXn6fnRY8IODlRg3/Tg==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.68.8", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.68.8.tgz", + "integrity": "sha512-63dWiHgvpWcienfdr465lT3SIn4u3535vbDfaLKhSn0F2KJ06bbcUsewDGJZUPZCbJ67qESrPDhb85UnWdb5ew==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.68.8", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.68.8.tgz", + "integrity": "sha512-/W1LBsMeQAdiCuH3Z2gkRspl3mlxL+butknhq4vXjmxO45vuT08BqhehxDoE4YS+m6s9lhpq6M9/PjTEAg8PYw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@types/estree": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.10.tgz", + "integrity": "sha512-lTyOMnOcmRBzdCv6/4zUZCrEhV0xrqQiUZBZtVcbmLHBXKLnN8q89v/wKRF/Q0HbwVsqbIG3o5HDoFl9sduM+g==", + "dev": true, + "license": "MIT" + }, + "node_modules/@vitejs/plugin-vue": { + "version": "5.2.4", + "resolved": "https://registry.npmjs.org/@vitejs/plugin-vue/-/plugin-vue-5.2.4.tgz", + "integrity": "sha512-7Yx/SXSOcQq5HiiV3orevHUFn+pmMB4cgbEkDYgnkUWb0WfeQ/wa2yFv6D5ICiCQOVpjA7vYDXrC7AGO8yjDHA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.0.0 || >=20.0.0" + }, + "peerDependencies": { + "vite": "^5.0.0 || ^6.0.0", + "vue": "^3.2.25" + } + }, + "node_modules/@vue/compiler-core": { + "version": "3.5.46", + "resolved": "https://registry.npmjs.org/@vue/compiler-core/-/compiler-core-3.5.46.tgz", + "integrity": "sha512-yb+N8/mgBcoeqCJPVyJI/D3OphLrSMXnB3ZQUNmRLU/1fsMW4bFfdJWNi9oIj7+EA3ULKKkP7b/VCpcYQYeiuQ==", + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.29.12", + "@vue/shared": "3.5.46", + "entities": "^7.0.1", + "estree-walker": "^2.0.2", + "source-map-js": "^1.2.3" + } + }, + "node_modules/@vue/compiler-dom": { + "version": "3.5.46", + "resolved": "https://registry.npmjs.org/@vue/compiler-dom/-/compiler-dom-3.5.46.tgz", + "integrity": "sha512-Bj3lCSw3DQnDRDxw115XqdLDd0+18Nftlgd8OXSGG+ud74hxJIE17eYrM+VWgQrTMsvJbLh9Hzf2MkwAzru36Q==", + "license": "MIT", + "dependencies": { + "@vue/compiler-core": "3.5.46", + "@vue/shared": "3.5.46" + } + }, + "node_modules/@vue/compiler-sfc": { + "version": "3.5.46", + "resolved": "https://registry.npmjs.org/@vue/compiler-sfc/-/compiler-sfc-3.5.46.tgz", + "integrity": "sha512-hjUvMxGh+QIgegwksfp6BRBYleE/a8veZHvTR6sa+o+bM4HU+WnrUZlhN0X+pDcsl8Lhwmbu72xPvLMk3XUwog==", + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.29.12", + "@vue/compiler-core": "3.5.46", + "@vue/compiler-dom": "3.5.46", + "@vue/compiler-ssr": "3.5.46", + "@vue/shared": "3.5.46", + "estree-walker": "^2.0.2", + "magic-string": "^0.30.21", + "postcss": "^8.5.32", + "source-map-js": "^1.2.3" + } + }, + "node_modules/@vue/compiler-ssr": { + "version": "3.5.46", + "resolved": "https://registry.npmjs.org/@vue/compiler-ssr/-/compiler-ssr-3.5.46.tgz", + "integrity": "sha512-qebChL3aP0m1k+TlSf+fZWvOwAf3flBCi5o+n01ykR3DX4mTIWheFltmoiQ12+z66/4cGeXqbB2P7sPWkGhQNQ==", + "license": "MIT", + "dependencies": { + "@vue/compiler-dom": "3.5.46", + "@vue/shared": "3.5.46" + } + }, + "node_modules/@vue/reactivity": { + "version": "3.5.46", + "resolved": "https://registry.npmjs.org/@vue/reactivity/-/reactivity-3.5.46.tgz", + "integrity": "sha512-+FHtYTvGxgFoX3oRs7soz6JHizGv50Q26WJN6PWtXuTLXRfkfUpDUTRuoTA/kiZVVt8NMeMpsPQLh9h++ReUjQ==", + "license": "MIT", + "dependencies": { + "@vue/shared": "3.5.46" + } + }, + "node_modules/@vue/runtime-core": { + "version": "3.5.46", + "resolved": "https://registry.npmjs.org/@vue/runtime-core/-/runtime-core-3.5.46.tgz", + "integrity": "sha512-eJUzKAUaHAmtnys/l9qduPzUnBrYMkmsCU7TN+vbSOSpm8kcETT7nacKxIO4MBej/XiOraVzq+lSeZv7o1//jQ==", + "license": "MIT", + "dependencies": { + "@vue/reactivity": "3.5.46", + "@vue/shared": "3.5.46" + } + }, + "node_modules/@vue/runtime-dom": { + "version": "3.5.46", + "resolved": "https://registry.npmjs.org/@vue/runtime-dom/-/runtime-dom-3.5.46.tgz", + "integrity": "sha512-6L7lbBvXTYBFFjIt25a0pgdpmn3Ns8RqUnNVibRzF4bgyiWJvqOhKEV5MXYWKlCttZE3aGeJN8mveo+6IrIKXA==", + "license": "MIT", + "dependencies": { + "@vue/reactivity": "3.5.46", + "@vue/runtime-core": "3.5.46", + "@vue/shared": "3.5.46", + "csstype": "^3.2.4" + } + }, + "node_modules/@vue/server-renderer": { + "version": "3.5.46", + "resolved": "https://registry.npmjs.org/@vue/server-renderer/-/server-renderer-3.5.46.tgz", + "integrity": "sha512-4mc0YWREc6OZ5pDCigvKPDzIUV+aciiH92yvyTS6xaHHxW/80rMceQQn11pYe7OEEBt2YQgYWR9zF8QF30GJUQ==", + "license": "MIT", + "dependencies": { + "@vue/compiler-ssr": "3.5.46", + "@vue/runtime-dom": "3.5.46", + "@vue/shared": "3.5.46" + } + }, + "node_modules/@vue/shared": { + "version": "3.5.46", + "resolved": "https://registry.npmjs.org/@vue/shared/-/shared-3.5.46.tgz", + "integrity": "sha512-P1WePbdzHrcIciWtmY2Im9EFhdakd3rZxYqvalOa3SfoxtF35Q8Uhmj1tKn6bWP4utcOpN8ao6BoJUItq0Uf+g==", + "license": "MIT" + }, + "node_modules/csstype": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.4.tgz", + "integrity": "sha512-PoKaoPzQapnEoqUSnHx1u6W6ku8CVEgKsnpmmzU3m1nwkidpPBQ8V/Zq2+bWNrsOKoKLwTGdbx6xF7BXP1zLVQ==", + "license": "MIT" + }, + "node_modules/entities": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz", + "integrity": "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/esbuild": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz", + "integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.25.12", + "@esbuild/android-arm": "0.25.12", + "@esbuild/android-arm64": "0.25.12", + "@esbuild/android-x64": "0.25.12", + "@esbuild/darwin-arm64": "0.25.12", + "@esbuild/darwin-x64": "0.25.12", + "@esbuild/freebsd-arm64": "0.25.12", + "@esbuild/freebsd-x64": "0.25.12", + "@esbuild/linux-arm": "0.25.12", + "@esbuild/linux-arm64": "0.25.12", + "@esbuild/linux-ia32": "0.25.12", + "@esbuild/linux-loong64": "0.25.12", + "@esbuild/linux-mips64el": "0.25.12", + "@esbuild/linux-ppc64": "0.25.12", + "@esbuild/linux-riscv64": "0.25.12", + "@esbuild/linux-s390x": "0.25.12", + "@esbuild/linux-x64": "0.25.12", + "@esbuild/netbsd-arm64": "0.25.12", + "@esbuild/netbsd-x64": "0.25.12", + "@esbuild/openbsd-arm64": "0.25.12", + "@esbuild/openbsd-x64": "0.25.12", + "@esbuild/openharmony-arm64": "0.25.12", + "@esbuild/sunos-x64": "0.25.12", + "@esbuild/win32-arm64": "0.25.12", + "@esbuild/win32-ia32": "0.25.12", + "@esbuild/win32-x64": "0.25.12" + } + }, + "node_modules/estree-walker": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz", + "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==", + "license": "MIT" + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/nanoid": { + "version": "3.3.20", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", + "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/postcss": { + "version": "8.5.33", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.33.tgz", + "integrity": "sha512-RVHEU9/Pp1Fnjr/MpAJsZoADukCKhfIi15OunEYiGktIkYLkPVvC1sioWolGDS7XByMTx9m/IGbro0Js13zhnQ==", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.20", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/rollup": { + "version": "4.68.8", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.68.8.tgz", + "integrity": "sha512-IHx4DeeTGhoAPke6p1Wlg0JEQFyQoZQQjEe1iD+nhEERk7eoeHK9zyOpVJiGc54Z1MCgI96rN1tD7Ttub8XyPA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.10" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@rollup/rollup-android-arm-eabi": "4.68.8", + "@rollup/rollup-android-arm64": "4.68.8", + "@rollup/rollup-android-x64": "4.68.8", + "@rollup/rollup-darwin-arm64": "4.68.8", + "@rollup/rollup-darwin-x64": "4.68.8", + "@rollup/rollup-freebsd-arm64": "4.68.8", + "@rollup/rollup-freebsd-x64": "4.68.8", + "@rollup/rollup-linux-arm-gnueabihf": "4.68.8", + "@rollup/rollup-linux-arm-musleabihf": "4.68.8", + "@rollup/rollup-linux-arm64-gnu": "4.68.8", + "@rollup/rollup-linux-arm64-musl": "4.68.8", + "@rollup/rollup-linux-loong64-gnu": "4.68.8", + "@rollup/rollup-linux-loong64-musl": "4.68.8", + "@rollup/rollup-linux-ppc64-gnu": "4.68.8", + "@rollup/rollup-linux-ppc64-musl": "4.68.8", + "@rollup/rollup-linux-riscv64-gnu": "4.68.8", + "@rollup/rollup-linux-riscv64-musl": "4.68.8", + "@rollup/rollup-linux-s390x-gnu": "4.68.8", + "@rollup/rollup-linux-x64-gnu": "4.68.8", + "@rollup/rollup-linux-x64-musl": "4.68.8", + "@rollup/rollup-openbsd-x64": "4.68.8", + "@rollup/rollup-openharmony-arm64": "4.68.8", + "@rollup/rollup-win32-arm64-msvc": "4.68.8", + "@rollup/rollup-win32-ia32-msvc": "4.68.8", + "@rollup/rollup-win32-x64-gnu": "4.68.8", + "@rollup/rollup-win32-x64-msvc": "4.68.8", + "fsevents": "~2.3.2" + } + }, + "node_modules/source-map-js": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.4.tgz", + "integrity": "sha512-J7ZjMvHd9O1fcT/5V09QWaaSl2BbWx3F6O08spde82Namf9UB0GxRVIPiNbVsdKkoizHiSpTodo3vp2bAy91MA==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/typescript": { + "version": "5.7.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.7.3.tgz", + "integrity": "sha512-84MVSjMEHP+FQRPy3pX9sTVV/INIex71s9TL2Gm5FG/WG1SqXeKyZ0k7/blY/4FdOzI12CBy1vGc4og/eus0fw==", + "devOptional": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/vite": { + "version": "6.4.6", + "resolved": "https://registry.npmjs.org/vite/-/vite-6.4.6.tgz", + "integrity": "sha512-RtsraAwEG68idOA6iUOoIpOlcSKROnf815aIq9qHTSrDNpLoBrBa12suyfcEd8qn0xwOVQI1Yhm1GbmTjF600A==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "^0.25.0", + "fdir": "^6.4.4", + "picomatch": "^4.0.2", + "postcss": "^8.5.3", + "rollup": "^4.34.9", + "tinyglobby": "^0.2.13" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", + "jiti": ">=1.21.0", + "less": "*", + "lightningcss": "^1.21.0", + "sass": "*", + "sass-embedded": "*", + "stylus": "*", + "sugarss": "*", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/vite-plugin-singlefile": { + "version": "2.3.4", + "resolved": "https://registry.npmjs.org/vite-plugin-singlefile/-/vite-plugin-singlefile-2.3.4.tgz", + "integrity": "sha512-1FAhlTCL6KJDpSUudrVU+gspapvS+tmKCg70vwNaAU6tyXn3E/C6+NnwQIze06byhBRv7VggZ78K0h+J/Rsdrg==", + "dev": true, + "license": "MIT", + "dependencies": { + "picomatch": "^4.0.7" + }, + "engines": { + "node": ">18.0.0" + }, + "peerDependencies": { + "rollup": "^4.59.0", + "vite": "^5.4.21 || ^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "rollup": { + "optional": true + } + } + }, + "node_modules/vue": { + "version": "3.5.46", + "resolved": "https://registry.npmjs.org/vue/-/vue-3.5.46.tgz", + "integrity": "sha512-0kW5CgfjMPBqmH158049SaE1muufp+K/ZyrwvSEwrwYky6QB7zL2y8kXfruneKb9O12eh0xAJL6CVSpzb9o0Kg==", + "license": "MIT", + "dependencies": { + "@vue/compiler-dom": "3.5.46", + "@vue/compiler-sfc": "3.5.46", + "@vue/runtime-dom": "3.5.46", + "@vue/server-renderer": "3.5.46", + "@vue/shared": "3.5.46" + }, + "peerDependencies": { + "typescript": "*" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + } + } +} diff --git a/panel/package.json b/panel/package.json new file mode 100644 index 0000000..f4e4168 --- /dev/null +++ b/panel/package.json @@ -0,0 +1 @@ +{"name":"idh-panel","private":true,"version":"0.1.0","type":"module","scripts":{"dev":"vite","build":"vite build"},"dependencies":{"vue":"3.5"},"devDependencies":{"@vitejs/plugin-vue":"^5.2.4","typescript":"5.7","vite":"^6.4.6","vite-plugin-singlefile":"^2.3.4"}} diff --git a/panel/src/App.vue b/panel/src/App.vue new file mode 100644 index 0000000..4560c26 --- /dev/null +++ b/panel/src/App.vue @@ -0,0 +1,162 @@ + + + diff --git a/panel/src/api.ts b/panel/src/api.ts new file mode 100644 index 0000000..74baa9b --- /dev/null +++ b/panel/src/api.ts @@ -0,0 +1,48 @@ +// 面板 REST 层:全部走本机 idh 服务的 /api 中转,不直连设备。 +import type { DeviceRow, DeviceSession, DeviceInfo, InstalledApp, EventItem } from './model'; + +async function api(path: string, init?: RequestInit): Promise { + const r = await fetch(path, init); + const data = await r.json().catch(() => ({})); + if (!r.ok) { (data as Record).__status = r.status; } + return data as T; +} +const post = (path: string, body: unknown) => + api>(path, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }); + +export const getHealth = () => api('/health'); +export const getSessions = () => api<{ sessions?: DeviceSession[] }>('/api/sessions'); +export const getApps = () => api<{ apps?: InstalledApp[]; scope?: string[]; error?: string }>('/api/apps'); +export const getAppEvents = (bundleId: string, after = 0, limit = 500) => + api<{ events?: EventItem[]; hasMore?: boolean }>( + `/api/apps/${encodeURIComponent(bundleId)}/events?limit=${limit}&after=${after}`); +export const appIconUrl = (bundleId: string) => `/api/apps/${encodeURIComponent(bundleId)}/icon`; +export const getDevices = () => api<{ devices?: DeviceRow[]; usb?: string[] }>('/api/devices'); +export const deviceAction = (body: Record) => post('/api/devices', body); +export const getScope = () => api<{ scope?: string[]; error?: string }>('/api/injection-scope'); +export const scopeUpdate = (bundleId: string, on: boolean) => + api<{ scope?: string[]; error?: string }>('/api/injection-scope', + { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ [on ? 'add' : 'remove']: [bundleId] }) }); +export const relaunchApp = (bundleId: string) => post('/api/apps/relaunch', { bundleId }); +// 会话设置走 /api/session-settings 中转;设备错误码在此翻成可读文案(沿用旧适配层)。 +const SETTINGS_ERRORS: Record = { + settings_pairing_required: '设备设置暂不可用。', + revision_conflict: '设备配置已被修改。请重新载入后再应用。', + invalid_settings: '设备会话限额需要整数,支持 1–2000 条、512–2097152 字节和 1–300 秒。', + settings_storage_error: '设备无法读取或保存设置。', + settings_unavailable: '当前设备服务尚未提供设置接口。', +}; +interface SettingsReply { revision?: string; deviceSession?: Record; error?: string } +async function settingsRequest(body?: unknown): Promise { + const r = await fetch('/api/session-settings', body === undefined ? {} : { + method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body), + }); + const data = await r.json().catch(() => ({})) as { error?: string } & SettingsReply; + if (!r.ok || data.error) { + return { error: SETTINGS_ERRORS[data.error ?? ''] ?? '设备设置暂时无法读取或保存。' }; + } + return data; +} +export const getSettingsExport = () => settingsRequest(); +export const postSettingsImport = (body: { revision: string; deviceSession: Record }) => + settingsRequest(body); diff --git a/panel/src/components/AppDialog.vue b/panel/src/components/AppDialog.vue new file mode 100644 index 0000000..63c5048 --- /dev/null +++ b/panel/src/components/AppDialog.vue @@ -0,0 +1,122 @@ + + + diff --git a/panel/src/components/DeviceMenu.vue b/panel/src/components/DeviceMenu.vue new file mode 100644 index 0000000..ec3b73f --- /dev/null +++ b/panel/src/components/DeviceMenu.vue @@ -0,0 +1,81 @@ + + + diff --git a/panel/src/components/DiagDialog.vue b/panel/src/components/DiagDialog.vue new file mode 100644 index 0000000..1b97133 --- /dev/null +++ b/panel/src/components/DiagDialog.vue @@ -0,0 +1,38 @@ + + + diff --git a/panel/src/components/EventBoard.vue b/panel/src/components/EventBoard.vue new file mode 100644 index 0000000..8027f4c --- /dev/null +++ b/panel/src/components/EventBoard.vue @@ -0,0 +1,269 @@ + + + diff --git a/panel/src/components/EventDetail.vue b/panel/src/components/EventDetail.vue new file mode 100644 index 0000000..01ee9a1 --- /dev/null +++ b/panel/src/components/EventDetail.vue @@ -0,0 +1,168 @@ + + + diff --git a/panel/src/components/InjectPanel.vue b/panel/src/components/InjectPanel.vue new file mode 100644 index 0000000..5460658 --- /dev/null +++ b/panel/src/components/InjectPanel.vue @@ -0,0 +1,55 @@ + + + diff --git a/panel/src/components/McpDialog.vue b/panel/src/components/McpDialog.vue new file mode 100644 index 0000000..54ab1f7 --- /dev/null +++ b/panel/src/components/McpDialog.vue @@ -0,0 +1,23 @@ + + + diff --git a/panel/src/components/SettingsPanel.vue b/panel/src/components/SettingsPanel.vue new file mode 100644 index 0000000..feac892 --- /dev/null +++ b/panel/src/components/SettingsPanel.vue @@ -0,0 +1,213 @@ + + + diff --git a/panel/src/components/ToolStub.vue b/panel/src/components/ToolStub.vue new file mode 100644 index 0000000..b7e4f09 --- /dev/null +++ b/panel/src/components/ToolStub.vue @@ -0,0 +1,37 @@ + + + diff --git a/panel/src/components/WechatDialog.vue b/panel/src/components/WechatDialog.vue new file mode 100644 index 0000000..2aa726a --- /dev/null +++ b/panel/src/components/WechatDialog.vue @@ -0,0 +1,17 @@ + + + diff --git a/panel/src/icons.ts b/panel/src/icons.ts new file mode 100644 index 0000000..81c7604 --- /dev/null +++ b/panel/src/icons.ts @@ -0,0 +1,33 @@ +// 内联 SVG 图标(stroke, 20x20 viewBox 对齐 IDH 原面板 sprite)。 +export const I: Record = { + chevron: '', + search: '', + filter: '', + list: '', + box: '', + code: '', + download: '', + play: '', + pause: '', + info: '', + terminal: '', + gear: '', + more: '', + copy: '', + x: '', + check: '', + key: '', + lock: '', + cpu: '', + wifi: '', + folder: '', + dump: '', + inject: '', + refresh: '', + eye: '', + target: '', + sliders: '', + server: '', + log: '', + collapse: '', +}; diff --git a/panel/src/main.ts b/panel/src/main.ts new file mode 100644 index 0000000..8dd6bc1 --- /dev/null +++ b/panel/src/main.ts @@ -0,0 +1,5 @@ +import { createApp } from 'vue'; +import App from './App.vue'; +import './style.css'; + +createApp(App).mount('#app'); diff --git a/panel/src/model.ts b/panel/src/model.ts new file mode 100644 index 0000000..67a10b5 --- /dev/null +++ b/panel/src/model.ts @@ -0,0 +1,123 @@ +// 从 panel-device.js 移植的领域模型:类别、阶段、面板偏好、设备限额、可移植配置。 +export const CATEGORIES = ["digest", "hmac", "sym", "asym", "file", "sys", "net", "keychain", "other"] as const; +export const CATEGORY_LABELS = ["摘要", "HMAC", "对称", "非对称", "文件", "系统", "网络", "Keychain", "其他"]; +export const SUMMARY_KINDS = CATEGORIES.map((key, i) => ({ key, label: CATEGORY_LABELS[i] })); + +export const PHASES: Record = { entry: "进入", leave: "返回", complete: "完成", aborted: "中止" }; +export const KIND_LABELS: Record = { crypto: "加解密", network: "网络", observation: "观测", function: "函数" }; +export const SESSION_STATUS: Record = { waiting: "等待 Agent", observing: "观察中", closing: "确认尾部", ended: "已结束" }; + +export interface DeviceSession { bundleId: string; sessionId: string; status: string; count: number; lastSeq: number; createdAtMs: number; pid?: number; processGeneration?: string } +export interface InstalledApp { bundleId: string; name: string; running?: boolean; kind?: string } +export interface DeviceApp extends InstalledApp { processGeneration?: string; pid?: number } +export interface DeviceInfo { service?: string; version?: string; apps: DeviceApp[]; [k: string]: unknown } +export interface EventItem { + seq: number; appSeq?: number; sourceSeq?: number; timeMs: number; category: number; kind?: string; + phase?: string; update?: boolean; callId?: string; parentCallId?: string; asyncTaskId?: string; [k: string]: unknown; +} +/** 归并后的应用条目:sessionId 复用为 bundleId,count 跨会话累计。 */ +export interface AppRecord extends DeviceSession { sessions: number; name: string; running: boolean; kind: "record" } +export interface DeviceRow { id: string; address: string; transport?: string; online?: boolean; selected?: boolean } + +export const getCategory = (n?: number) => CATEGORY_LABELS[n ?? -1] ?? "其他"; +export const getPhase = (p?: string) => (p ? PHASES[p] ?? "摘要" : "摘要"); +export const titleFor = (e: EventItem) => getCategory(e.category) + "事件"; + +export const DISPLAY_CHOICES = [100, 150, 300, 500]; +export const LIMITS: Record = { + maxRecords: [1, 2000], maxBytes: [512, 2097152], recordSeconds: [1, 300], +}; +export const LIMIT_FIELDS: Array<{ key: string; label: string; unit: string }> = [ + { key: "maxRecords", label: "单会话摘要条数", unit: "条" }, + { key: "maxBytes", label: "单会话摘要大小", unit: "字节" }, + { key: "recordSeconds", label: "单会话观察时长", unit: "秒" }, +]; + +export interface PanelPrefs { + displayCap: number; autoRefresh: boolean; advancedFilters: boolean; + summaryCategories: Record; +} +export type DeviceLimits = Record; + +const PREF_KEYS = ["displayCap", "autoRefresh", "advancedFilters", "summaryCategories"]; + +function checkFields(data: unknown, allowed: string[], name: string): asserts data is Record { + if (!data || typeof data !== "object" || Array.isArray(data)) throw new Error(name + " 必须是对象"); + if (Object.keys(data as object).some((k) => !allowed.includes(k))) throw new Error(name + " 含有不支持的字段"); +} + +export function defaults(): PanelPrefs { + return { + displayCap: 150, autoRefresh: true, advancedFilters: false, + summaryCategories: Object.fromEntries(CATEGORIES.map((k) => [k, true])), + }; +} + +export function deviceLimits(patch: Record, requireAll = false): DeviceLimits { + checkFields(patch, Object.keys(LIMITS), "deviceSession"); + if (requireAll && Object.keys(patch).length !== Object.keys(LIMITS).length) + throw new Error("设备返回的会话配置不完整"); + for (const [field, value] of Object.entries(patch)) { + const [min, max] = LIMITS[field]; + if (!Number.isInteger(value) || (value as number) < min || (value as number) > max) + throw new Error(field + " 必须是 " + min + "–" + max + " 之间的整数"); + } + return { ...patch } as DeviceLimits; +} + +export function mergePanel(base: PanelPrefs, patch: Record): PanelPrefs { + checkFields(patch, PREF_KEYS, "panel"); + const next: PanelPrefs = { + displayCap: base.displayCap, autoRefresh: base.autoRefresh, + advancedFilters: base.advancedFilters, summaryCategories: { ...base.summaryCategories }, + }; + for (const key of ["autoRefresh", "advancedFilters"] as const) { + if (!Object.hasOwn(patch, key)) continue; + if (typeof patch[key] !== "boolean") throw new Error(key + " 必须是布尔值"); + next[key] = patch[key]; + } + if (Object.hasOwn(patch, "displayCap")) { + if (!DISPLAY_CHOICES.includes(patch.displayCap as number)) throw new Error("displayCap 只支持 100、150、300、500"); + next.displayCap = patch.displayCap as number; + } + if (Object.hasOwn(patch, "summaryCategories")) { + const sc = patch.summaryCategories; + checkFields(sc, [...CATEGORIES], "summaryCategories"); + for (const [key, value] of Object.entries(sc as Record)) { + if (typeof value !== "boolean") throw new Error(key + " 的摘要开关必须是布尔值"); + next.summaryCategories[key] = value; + } + } + return next; +} + +export interface ParsedProfile { + deviceSession: DeviceLimits; hasDevice: boolean; hasPanel: boolean; panel: PanelPrefs; +} +export function parseProfile(data: unknown, panel: PanelPrefs): ParsedProfile { + checkFields(data, ["version", "deviceSession", "panel"], "配置"); + const hasVersion = Object.hasOwn(data, "version"); + const hasDevice = Object.hasOwn(data, "deviceSession"); + const hasPanel = Object.hasOwn(data, "panel"); + if (hasVersion && data.version !== 1) throw new Error("不支持此配置版本"); + if ((!hasVersion && (!hasDevice || hasPanel)) || (!hasDevice && !hasPanel)) + throw new Error("配置应包含 deviceSession 或带版本号的 panel"); + const deviceSession = hasDevice ? deviceLimits(data.deviceSession as Record) : {}; + if (hasDevice && !Object.keys(deviceSession).length) throw new Error("deviceSession 没有可应用的字段"); + return { + deviceSession, hasDevice, hasPanel, + panel: mergePanel(panel, hasPanel ? (data.panel as Record) : {}), + }; +} +export function portableProfile(device: DeviceLimits, panel: PanelPrefs): string { + return JSON.stringify({ version: 1, deviceSession: deviceLimits(device, true), panel: mergePanel(defaults(), panel as unknown as Record) }, null, 2); +} + +const FIELD_NAMES = ["seq", "sourceSeq", "timeMs", "category", "kind", "phase", "update", "callId", "parentCallId", "asyncTaskId"]; +export const cleanEvent = (e: EventItem) => + Object.fromEntries(FIELD_NAMES.filter((k) => Object.hasOwn(e, k)).map((k) => [k, e[k]])); + +export const fmt = (formatter: Intl.DateTimeFormat, ms?: number) => + Number.isFinite(ms) && (ms as number) > 0 && (ms as number) <= 8640000000000000 ? formatter.format(ms as number) : "—"; +export const shortTime = new Intl.DateTimeFormat("zh-CN", { hour: "2-digit", minute: "2-digit", second: "2-digit", hour12: false }); +export const longTime = new Intl.DateTimeFormat("zh-CN", { dateStyle: "medium", timeStyle: "medium" }); diff --git a/panel/src/store.ts b/panel/src/store.ts new file mode 100644 index 0000000..d32a38c --- /dev/null +++ b/panel/src/store.ts @@ -0,0 +1,301 @@ +// 响应式数据层:panel-device.js 的 inspectDevice/readEvents/snapshot + 面板状态。 +import { reactive, computed } from 'vue'; +import * as A from './api'; +import { + type AppRecord, type DeviceInfo, type DeviceRow, type DeviceSession, type EventItem, + type InstalledApp, type PanelPrefs, defaults, mergePanel, +} from './model'; + +export interface Catalog { device: DeviceInfo; sessions: DeviceSession[]; installed: InstalledApp[] } +interface BoardDisplay { pauseAt: number | null; clearThrough: number | null } + +const PREF_KEY = 'idh_panel_preferences_v1'; +const VIEW_KEY = 'idh_workspace_view_v1'; + +function loadLocal(key: string): T | null { + try { return JSON.parse(localStorage.getItem(key) ?? '') as T; } catch { return null; } +} +export function saveLocal(key: string, value: unknown): boolean { + try { localStorage.setItem(key, JSON.stringify(value)); return true; } catch { return false; } +} + +function loadPrefs(): PanelPrefs { + try { + const old = Number(localStorage.getItem('dh_displayCap')); + const prev: Record = { advancedFilters: localStorage.getItem('dh_filters_open') === '1' }; + if ([100, 150, 300, 500].includes(old)) prev.displayCap = old; + return mergePanel(defaults(), (loadLocal>(PREF_KEY) ?? prev) as Record); + } catch { return defaults(); } +} + +export const store = reactive({ + // 设备与连接 + network: 'loading' as 'loading' | 'online' | 'offline', + device: null as DeviceInfo | null, + devices: [] as DeviceRow[], + usbRows: [] as string[], + // 应用目录 + apps: [] as AppRecord[], + installed: [] as InstalledApp[], + selected: '', + // 当前应用数据 + session: null as (DeviceSession & { sessions?: number }) | null, + events: [] as EventItem[], + sessionNotice: '', + // 板块与展示 + tab: 'crypto', + displayByBoard: new Map(), + prefs: loadPrefs(), + limit: 0, // 由 prefs.displayCap 初始化 + seq: null as number | null, + detailTab: 'data' as 'data' | 'event' | 'context' | 'raw', + // 注入范围 + injectData: null as { apps?: InstalledApp[]; scope?: string[]; error?: string } | null, + injectAt: 0, + injectPending: new Set(), + // 对话框开关 + appDialogOpen: false, + diagOpen: false, + mcpOpen: false, + settingsOpen: false, + wechatOpen: false, + settingsPage: 'capture', +}); +store.limit = store.prefs.displayCap; + +// ---- toast ---- +export const toasts = reactive<{ id: number; text: string }[]>([]); +let toastSeq = 0; +export function toast(text: string) { + const id = ++toastSeq; + toasts.push({ id, text }); + setTimeout(() => { const i = toasts.findIndex(t => t.id === id); if (i >= 0) toasts.splice(i, 1); }, 1500); +} +export async function copyText(text: string) { + if (!text) return; + try { await navigator.clipboard.writeText(text); } + catch { + const ta = document.createElement('textarea'); + (document.querySelector('dialog[open]') ?? document.body).appendChild(ta); + ta.value = text; ta.select(); + try { document.execCommand('copy'); } catch { toast('无法复制,请手动选中内容'); ta.remove(); return; } + ta.remove(); + } + toast('已复制'); +} +export function downloadText(filename: string, text: string) { + downloadBlob(filename, new Blob([text], { type: 'application/json' })); +} +export function downloadBlob(filename: string, blob: Blob) { + const url = URL.createObjectURL(blob); + const a = document.createElement('a'); + a.href = url; a.download = filename; + document.body.appendChild(a); a.click(); a.remove(); + setTimeout(() => URL.revokeObjectURL(url), 1000); + toast('已下载 ' + filename); +} + +// ---- 板块显示状态(暂停/清空,跨页签保留)---- +export function displayState(board = store.tab): BoardDisplay { + if (!store.displayByBoard.has(board)) store.displayByBoard.set(board, { pauseAt: null, clearThrough: null }); + return store.displayByBoard.get(board)!; +} + +// ---- 应用归并:会话按 bundleId 合并 + 已安装元数据 ---- +export function appsFrom(sessions: DeviceSession[], installed: InstalledApp[]): AppRecord[] { + const meta = new Map(installed.map((a) => [a.bundleId, a])); + const map = new Map(); + for (const s of sessions) { + let app = map.get(s.bundleId); + if (!app) { + const m = meta.get(s.bundleId); + app = { + sessionId: s.bundleId, bundleId: s.bundleId, createdAtMs: s.createdAtMs, + status: s.status, count: 0, sessions: 0, lastSeq: 0, + name: m?.name ?? '', running: m?.running === true, kind: 'record', + }; + map.set(s.bundleId, app); + } + app.count += s.count; + app.sessions += 1; + if (s.createdAtMs > app.createdAtMs) { app.createdAtMs = s.createdAtMs; app.status = s.status; } + } + return [...map.values()]; +} + +let catalog: Catalog | null = null; +let catalogPending: Promise | null = null; + +export async function inspectDevice(): Promise { + if (catalogPending) return catalogPending; + if (catalog && Date.now() - (catalog as { time?: number }).time! < 1100) return catalog; + catalogPending = (async () => { + const [health, history, installedRes] = await Promise.all([ + A.getHealth(), A.getSessions(), A.getApps()]); + if (!(health as unknown as { ok?: boolean }).ok && !(health as DeviceInfo).service) + throw new Error('设备连接不可用'); + const device = health; + const sessions = history.sessions ?? []; + const installed = installedRes.apps ?? []; + const known = store.selected + && (sessions.some((s) => s.bundleId === store.selected) + || installed.some((a) => a.bundleId === store.selected)); + if (!known) changeSelection(sessions[0]?.bundleId ?? installed[0]?.bundleId ?? ''); + store.apps = appsFrom(sessions, installed); + store.installed = installed; + store.sessionNotice = history.sessions ? '' : '设备在线,会话暂时无法读取。'; + catalog = { device, sessions, installed }; + (catalog as { time?: number }).time = Date.now(); + return catalog; + })(); + try { return await catalogPending; } finally { catalogPending = null; } +} + +export function changeSelection(id: string) { + if (id === store.selected) return; + const had = !!store.selected; + store.selected = id; + loaded = null; + store.displayByBoard.clear(); + store.seq = null; + store.detailTab = 'data'; + store.limit = store.prefs.displayCap; + if (had) void refresh(true); +} + +// ---- 按 App 读连续时间线:appSeq 翻页 → 归一为 seq ---- +async function readEvents(bundleId: string, expected: number): Promise { + const result: EventItem[] = []; + const path = '/api/apps/' + encodeURIComponent(bundleId) + '/events'; + let cursor = 0; + for (let index = 0; result.length < expected && index < 80; ++index) { + const page = await A.getAppEvents(bundleId, cursor); + if ((page as { __status?: number }).__status) throw new Error('设备摘要暂时无法读取'); + for (const event of page.events ?? []) { + const seq = event.appSeq ?? event.seq; + if (seq <= cursor) throw new Error('设备摘要序号重复或倒退'); + result.push({ ...event, seq, appSeq: seq }); + cursor = seq; + } + if (!page.hasMore) break; + } + void path; + if (result.length !== expected) throw new Error('已保存摘要与应用快照不一致,请刷新'); + return result.reverse(); +} + +let loaded: { key: string; pending: Promise } | null = null; +export async function snapshot(): Promise<{ device: DeviceInfo; session: typeof store.session; events: EventItem[] }> { + const { device, sessions } = await inspectDevice(); + const appSessions = sessions.filter((s) => s.bundleId === store.selected); + if (!appSessions.length) return { device, session: null, events: [] }; + const latest = appSessions[0]; + const expected = appSessions.reduce((sum, s) => sum + s.count, 0); + const live = device.apps.find((a) => a.bundleId === store.selected); + const key = [store.selected, expected, latest.lastSeq].join('/'); + if (loaded?.key !== key) { + const pending = readEvents(store.selected, expected); + loaded = { key, pending }; + pending.catch(() => { if (loaded?.pending === pending) loaded = null; }); + } + const events = await loaded.pending; + return { + device, + session: { + ...latest, count: expected, lastSeq: events[0]?.appSeq ?? events[0]?.seq ?? 0, + sessions: appSessions.length, + processGeneration: live?.processGeneration ?? latest.processGeneration, + }, + events, + }; +} + +// ---- 轮询 ---- +let inFlight = false; +export async function refresh(force = false) { + if (inFlight && !force) return; + inFlight = true; + try { + const next = await snapshot(); + const changed = store.session?.sessionId !== next.session?.sessionId; + if (changed) { + store.displayByBoard.clear(); + store.seq = null; + store.detailTab = 'data'; + store.limit = store.prefs.displayCap; + } + store.device = next.device; + store.session = next.session; + store.events = next.events; + store.network = 'online'; + } catch { + store.network = 'offline'; + } finally { + inFlight = false; + } +} + +export function chooseApp(bundleId: string): boolean { + const known = catalog?.sessions.some((s) => s.bundleId === bundleId) + || catalog?.installed?.some((a) => a.bundleId === bundleId) + || store.apps.some((a) => a.bundleId === bundleId) + || store.installed.some((a) => a.bundleId === bundleId); + if (!known) return false; + changeSelection(bundleId); + return true; +} + +// ---- 设备列表 ---- +export async function loadDevices() { + try { + const data = await A.getDevices(); + store.devices = data.devices ?? []; + store.usbRows = data.usb ?? []; + } catch { store.devices = []; store.usbRows = []; } +} +export async function deviceSelect(id: string): Promise { + const data = await A.deviceAction({ action: 'select', id }); + return !data.error; +} +export async function deviceRemove(id: string) { await A.deviceAction({ action: 'remove', id }); await loadDevices(); } +export async function deviceAdd(address?: string, usb?: string) { + const body: Record = { action: 'add' }; + if (address) body.address = address; + if (usb) body.usb = usb; + const data = await A.deviceAction(body); + await loadDevices(); + return !data.error; +} +export const currentDevice = computed(() => store.devices.find((d) => d.selected)); + +// ---- 注入范围 ---- +export async function loadInject(force = false) { + if (!force && Date.now() - store.injectAt < 3000) return; + store.injectAt = Date.now(); + try { store.injectData = await A.getApps(); } + catch { store.injectData = { error: 'device_unavailable' }; } +} +export async function toggleScope(bundleId: string, on: boolean): Promise { + let data: { scope?: string[]; error?: string }; + try { data = await A.scopeUpdate(bundleId, on); } + catch { toast('注入范围更新失败'); return false; } + if (data.error) { toast('注入范围更新失败'); return false; } + const app = (store.injectData?.apps ?? []).find((a) => a.bundleId === bundleId); + if (app?.running) store.injectPending.add(bundleId); else store.injectPending.delete(bundleId); + if (store.injectData) store.injectData.scope = data.scope ?? store.injectData.scope; + return true; +} +export async function relaunchBundle(bundleId: string) { + await A.relaunchApp(bundleId).catch(() => undefined); + store.injectPending.delete(bundleId); + setTimeout(() => void loadInject(true), 1500); +} + +export function savePrefs(next: PanelPrefs) { + store.prefs = next; + saveLocal(PREF_KEY, next); +} +export const currentApp = computed(() => + store.apps.find((a) => a.bundleId === store.selected) + ?? store.installed.find((a) => a.bundleId === store.selected)); +export const selectedName = computed(() => currentApp.value?.name || store.selected || '应用记录'); diff --git a/panel/src/style.css b/panel/src/style.css new file mode 100644 index 0000000..5274fd9 --- /dev/null +++ b/panel/src/style.css @@ -0,0 +1,987 @@ + /* ===== ADH 观测台 · 移植 IDH「2026 workbench」深墨蓝设计系统 ===== */ + :root { + --bg:#06070a; --chrome:#090b0f; --surface:#0f1218; --surface-2:#151922; + --surface-3:#1b202a; --line:#343b48; --line-soft:#20252e; + --ink:#ffffff; --ink-2:#e5e8ee; --muted:#aeb5c0; + --blue:#78a9ff; --coral:#ff8b7b; --amber:#ffc85c; --lilac:#c7a6ff; + --cyan:#79d6e8; --pink:#ff9fbc; --green:#8bd6a8; --danger:#ff788c; --teal:#5ce1c9; + color-scheme: dark; + } + * { box-sizing:border-box; scrollbar-width:thin; scrollbar-color:#3c4452 transparent; } + *::-webkit-scrollbar { width:10px; height:10px; } + *::-webkit-scrollbar-track { background:transparent; } + *::-webkit-scrollbar-thumb { background:#3c4452; border:3px solid transparent; border-radius:8px; background-clip:padding-box; } + *::-webkit-scrollbar-thumb:hover { background:#5c6574; border:3px solid transparent; background-clip:padding-box; } + *::-webkit-scrollbar-corner { background:transparent; } + [hidden] { display:none !important; } + html, body { margin:0; padding:0; height:100%; } + body { display:flex; flex-direction:column; height:100vh; overflow:hidden; min-width:320px; + background:var(--bg); color:var(--ink); line-height:1.5; font-size:13px; letter-spacing:0; + font-family:Inter,-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,'Helvetica Neue',Arial,'PingFang SC','Microsoft YaHei',sans-serif; } + header, #nav, .filters { flex-shrink:0; } + #app { flex:1; display:flex; min-height:0; } + .muted { color:var(--muted); } + .detect-radar { font-size:12px; line-height:1.55; color:var(--muted); padding:10px 14px 0; white-space:pre-wrap; } + .spacer { flex:1; } + a.dl { color:var(--blue); text-decoration:none; } a.dl:hover { text-decoration:underline; } + code { background:var(--surface-2); border:1px solid var(--line); border-radius:4px; padding:1px 5px; color:var(--ink-2); font-family:ui-monospace,SFMono-Regular,Consolas,monospace; } + + /* ---- header / brand(对齐 iOS workbench:无第二进程条、按钮透明) ---- */ + header { display:flex; align-items:center; gap:14px; min-height:62px; padding:9px 16px; background:var(--chrome); border-bottom:1px solid var(--line-soft); } + .header-context { display:flex; align-items:center; gap:8px 12px; min-width:0; flex-wrap:wrap; } + .brand-lockup { display:flex; align-items:center; gap:11px; flex-shrink:0; } + header h1 { display:flex; align-items:center; margin:0; font-size:16px; font-weight:700; color:var(--ink); letter-spacing:0; } + .hdr-mark { width:28px; height:28px; margin-right:9px; border-radius:5px; background:var(--ink); overflow:hidden; flex-shrink:0; } + .hdr-mark img { display:block; width:100%; height:100%; } + .workspace-name { display:none; } + .stats { display:flex; align-items:center; gap:7px; padding:0; font-size:12px; color:var(--green); background:transparent; border:0; white-space:nowrap; } + .stats b { color:var(--ink); font-weight:600; } + .status-dot { display:inline-block; width:8px; height:8px; border-radius:50%; background:var(--danger); flex-shrink:0; } + .status-dot.ok { background:var(--green); animation:dh-pulse 2.4s ease-in-out infinite; } + @keyframes dh-pulse { 0%,100%{opacity:1;} 50%{opacity:.5;} } + .app-context { position:relative; min-width:0; } + .context-label { color:var(--muted); font-size:11px; white-space:nowrap; } + .app-affiliation { margin:0 0 9px; color:var(--muted); font-size:11px; } + .process-trigger { display:grid; grid-template-columns:minmax(0,1fr) auto; align-items:center; column-gap:10px; min-width:180px; max-width:280px; min-height:38px; padding:4px 10px; text-align:left; color:var(--ink-2); background:transparent; border:1px solid transparent; border-radius:4px; cursor:pointer; } + .process-trigger:hover, .process-trigger[aria-expanded="true"] { border-color:transparent; background:rgba(255,255,255,.04); color:var(--ink); } + .process-trigger .proc-primary { display:flex; align-items:center; gap:8px; min-width:0; overflow:hidden; color:var(--ink); font-size:13px; font-weight:650; } + .process-trigger .proc-face { width:22px; height:22px; flex:none; } + .process-trigger .proc-face img, .process-trigger .proc-face .app-dialog-letter { width:22px; height:22px; border-radius:6px; } + .process-trigger .proc-face .app-dialog-letter { font-size:12px; } + .process-trigger .proc-text { display:flex; flex-direction:column; min-width:0; line-height:1.25; } + .process-trigger #procLabel { overflow:hidden; text-overflow:ellipsis; white-space:nowrap; } + .process-trigger .proc-pkg { overflow:hidden; color:var(--muted); font-size:10px; font-weight:400; text-overflow:ellipsis; white-space:nowrap; } + .menu-chevron { display:inline-flex; align-items:center; justify-content:center; color:var(--muted); line-height:0; } + .menu-chevron svg { display:block; } + .process-trigger .menu-chevron { grid-column:2; align-self:center; } + .app-choices { max-height:190px; overflow:auto; } + .app-sessions { margin-top:8px; padding:9px 7px 4px; border-top:1px solid var(--line-soft); } + .app-context .proc-title { margin:3px 7px 7px; color:var(--muted); font-size:11px; font-weight:600; } + .app-sessions summary { padding:3px 0 8px; color:var(--ink-2); font-size:12px; font-weight:600; } + .app-sessions .cap-state-pill { display:inline-block; margin:0 0 8px; } + .app-item { box-sizing:border-box; display:flex; flex-direction:column; align-items:flex-start; gap:2px; width:100%; min-height:44px; padding:7px 10px; color:var(--ink-2); background:transparent; border:0; border-radius:3px; text-align:left; cursor:pointer; } + .app-item:hover, .app-item.active { color:var(--ink); background:var(--surface-3); } + .app-item .app-name-row { display:flex; align-items:center; gap:8px; width:100%; min-width:0; } + .app-item .app-name { overflow:hidden; flex:1; min-width:0; color:var(--ink); font-size:13px; font-weight:650; text-overflow:ellipsis; white-space:nowrap; } + .app-item .app-state { flex:none; color:var(--muted); font-size:10px; } + .app-item .app-state.on { color:var(--green); } + .app-item .app-pkg { overflow:hidden; max-width:100%; color:var(--muted); font:10px/1.3 ui-monospace,SFMono-Regular,Consolas,monospace; text-overflow:ellipsis; white-space:nowrap; } + .app-section { margin:8px 8px 2px; color:var(--muted); font-size:11px; font-weight:600; } + .app-row { display:flex; align-items:stretch; gap:2px; } + .app-row .app-item { flex:1; width:auto; min-width:0; } + .app-inject { flex:none; width:32px; min-height:44px; padding:0; color:var(--muted); background:transparent; border:0; border-radius:3px; cursor:pointer; } + .app-inject::before { content:''; display:inline-block; width:13px; height:13px; border:1px solid var(--line); border-radius:2px; } + .app-inject[aria-pressed="true"]::before { background:var(--blue); border-color:var(--blue); box-shadow:inset 0 0 0 2px #11151c; } + .app-inject:disabled { opacity:.45; cursor:default; } + .app-load { width:calc(100% - 12px); margin:6px; } + .app-empty { padding:8px 10px; color:var(--muted); font-size:12px; } + .procinfo { display:grid; grid-template-columns:auto minmax(0,1fr); gap:8px 14px; margin:0; font:11px/1.45 ui-monospace,SFMono-Regular,Consolas,monospace; } + .procinfo dt { color:var(--muted); } + .procinfo dd { min-width:0; margin:0; overflow-wrap:anywhere; color:var(--ink-2); text-align:right; } + .sess-lab { display:flex; align-items:center; gap:8px; margin-top:12px; padding-top:10px; border-top:1px solid var(--line-soft); color:var(--muted); font-size:11px; } + .sess-lab select { flex:1; min-width:0; background:var(--surface-2); color:var(--ink); } + /* Native