Repository navigation
Expand file tree
/
Copy pathpatch_install.py
More file actions
2187 lines (1945 loc) · 109 KB
/
Copy pathpatch_install.py
File metadata and controls
2187 lines (1945 loc) · 109 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""ZCode app.asar 注入/卸载工具(token 用量悬浮条)。
用法:
python patch_install.py install # 安装/重定向(幂等;自动替换旧注入行,含指向旧目录的历史行;
# 客户端运行中则生成 .tmp 待退出后替换)
python patch_install.py install --finalize # 客户端退出后完成替换
python patch_install.py remove # 卸载(从 asar 剥离本工具注入行,不依赖备份)
python patch_install.py check # 检查当前注入状态与入口语法
python patch_install.py install --finalize --asar <app.asar 完整路径> --runtime <运行时目录>
# standalone 运行须显式指定非默认安装位置的目标,
# 否则按平台默认位置猜测,自定义路径下会猜错/找不到文件;
# 也可各设一次环境变量 ZCODE_ASAR / ZCODE_RUNTIME 代替每次都传
# (命令行参数优先于环境变量)。--runtime 只有 install --finalize
# 需要——pending TMP 的 sidecar 记录了生成时的运行时目录,
# standalone 默认 RUNTIME 是脚本自身所在目录,插件安装的运行时
# 数据目录通常是另一个目录,不传会被来源授权校验拒绝;
# remove/check 不受影响。install.py / overlay_install.py
# 拉起时会调用 set_target()/set_runtime() 代为处理,不受此限制。
原理:asar 主入口 out/main/index.js 尾部追加一行 dynamic import(loader)(ESM 入口,实测见下),
并在主 bundle 内做定向补丁:①远控中继 stash/uplink 两处(transform_mobile_entry);
②getLogin 身份桥(transform_remote_login_entry,移动端远程控制:让远控设备以所选快照账号
身份注册,手机登录该账号即可远控本机)。补丁均按唯一锚点 + 幂等标记装卸,卸载不依赖备份。
Electron fuses: EmbeddedAsarIntegrityValidation=0(已实测),改动 asar 可正常加载。
安装/卸载均只增删本工具自己的注入行(ZUSAGE_LINE_RE 识别,不限目录的历史行一并匹配),
不制作也不依赖 asar 备份:卸载不会连带移除其它工具后装的注入行;ZCode 官方升级覆盖 asar
之后再卸载,也不会把客户端降级回安装时的旧版本。历史版本遗留的 app.asar.zusage.bak
会在成功安装/卸载后自动清理。
安装成功后自动弹出常驻监控窗口(install_monitor.py,每 10 秒检测一次):提醒重启
ZCode、确认注入加载后自动退出;运行中替换失败(.tmp 待替换)时还会在 ZCode 退出后
自动完成替换 —— 该收尾职责已由监控窗口承担,旧的 schtasks 计划任务方案废弃。
"""
import base64
import hashlib
import json
import os
import re
import stat
import struct
import subprocess
import sys
import time
from pathlib import Path
import contextlib
from contextlib import ExitStack, contextmanager, nullcontext
import runtime_lock
from runtime_lock import bounded_mkstemp, file_lock, publish_install, real_home, sudo_user
IS_WIN = sys.platform == "win32"
IS_MAC = sys.platform == "darwin"
# 手动命令模板里的解释器:用当前正在跑的真实解释器绝对路径,不猜 python/python3
# 别名——Windows 上 python3 可能是 Microsoft Store 存根(静默失败),python 也可能
# 被禁用;能走到提示这一步说明本解释器一定可用(用户反馈 2026-11-03)。
PYEXE = sys.executable or "python"
if IS_WIN:
ASAR_DEFAULT = Path(r"D:\ZCode\resources\app.asar")
ZCODE_EXE_DEFAULT = Path(r"D:\ZCode\ZCode.exe")
elif IS_MAC:
ASAR_DEFAULT = Path("/Applications/ZCode.app/Contents/Resources/app.asar")
ZCODE_EXE_DEFAULT = Path("/Applications/ZCode.app/Contents/MacOS/ZCode")
else:
ASAR_DEFAULT = Path("app.asar") # 其它平台无默认位置,用 --asar / install.py 指定
ZCODE_EXE_DEFAULT = None
ASAR = ASAR_DEFAULT # 可被 set_target() 改指其它安装位置(install.py 探测后调用)
BAK = ASAR.with_name("app.asar.zusage.bak")
TMP = ASAR.with_name("app.asar.zusage.tmp")
TMP_META = TMP.with_name(TMP.name + ".json")
HERE = Path(__file__).parent.resolve()
# 运行时目录:install.py 标准安装时指向数据目录(~/.zcode/zcode-token-usage-statusbar,
# 经 set_runtime() 切换);独立运行本脚本或 --dev 安装时保持仓库目录(向后兼容)。
RUNTIME = HERE
LOADER = RUNTIME / "inject-main.cjs"
ENTRY = "out/main/index.js"
# 入口是 ESM(package.json type:module,实测 2026-09-04):必须用 dynamic import(CJS/ESM 通用),
# 指向 .cjs loader(在 type:module 包里仍按 CJS 加载,require 可用);asar 内相对路径不可用,用绝对 file URL。
INJECT_LINE_TMPL = (
'\n;import("{url}").then(() => null, (e) => console.error("[zusage] load failed", e));'
)
INJECT_LINE = INJECT_LINE_TMPL.format(url=(RUNTIME / "inject-main.cjs").as_uri())
# 匹配任何 zusage 注入行(不限当前目录)——迁移/重装/标准↔dev 互切时剥离旧行用
ZUSAGE_LINE_RE = re.compile(
rb'\n;import\("[^"]*inject-main\.cjs"\)\.then\(\(\) => null, '
rb'\(e\) => console\.error\("\[zusage\] load failed", e\)\);'
)
ZCODE_EXE = ZCODE_EXE_DEFAULT
# install(extra_modify=...) 的能力标记:调用方(overlay_install)按此探测——旧运行目录里的
# 模块或测试替身没有该常量时不传钩子,install() 的调用形状保持不变。
EXTRA_MODIFY = True
PATCH_SUPPLEMENT = hasattr(runtime_lock, "publish_supplement")
# overlay_install checks this before passing an initial snapshot or consuming diagnostic status.
REUSE_ARCHIVE_SNAPSHOT = True
ALIGN = 4
BLOCK = 4194304
# 输出语言:惰性读 config.json 的 "lang"(运行时目录优先,其次数据目录;缺省 zh)。
# install.py 标准安装流程里 set_runtime() 先于 install(),此时序下读到的就是本次安装写入的语言。
_LANG = None
def L(zh, en):
global _LANG
if _LANG is None:
_LANG = "zh"
# sudo 运行时(Linux 系统级安装)config 在真实用户的家目录,Path.home() 会指到 root
user_home = real_home(lambda: sudo_user(sys.platform), Path.home)
bases = [RUNTIME,
Path.home() / ".zcode" / "zcode-token-usage-statusbar"]
if user_home != Path.home():
bases.append(user_home / ".zcode" / "zcode-token-usage-statusbar")
for base in bases:
try:
lang = json.loads((base / "config.json").read_text(encoding="utf-8")).get("lang")
if lang in ("zh", "en"):
_LANG = lang
break
except (OSError, ValueError):
pass
return en if _LANG == "en" else zh
def set_runtime(path):
"""改运行时目录(LOADER/INJECT_LINE 随动)。ZCode 端泵的全套路径都基于 __dirname,
运行时副本目录即自洽运行,无需改运行时代码。"""
global RUNTIME, LOADER, INJECT_LINE
RUNTIME = Path(path)
LOADER = RUNTIME / "inject-main.cjs"
INJECT_LINE = INJECT_LINE_TMPL.format(url=LOADER.as_uri())
def zcode_exe_for(asar_path):
"""从 asar 位置推 ZCode 可执行文件(语法自检用):Windows 布局 <root>/ZCode.exe,
macOS bundle 布局 <root>/MacOS/ZCode,Linux 布局 <root>/zcode(deb/rpm 官方包,/opt/ZCode);
非 ZCode 布局(如 %LOCALAPPDATA%\\Programs 下其它 Electron 应用)返回 None——
客户端进程名随之失去语义(客户端是别的应用),语法检查自动跳过。"""
root = asar_path.parent.parent
if IS_WIN:
exe = root / "ZCode.exe"
return exe if exe.is_file() else None
if IS_MAC:
return root / "MacOS" / "ZCode"
if sys.platform.startswith("linux"):
return root / "zcode"
return None
def _safe_is_file(path):
try:
return bool(path) and Path(path).is_file()
except OSError:
return False
def ui_element_exe_for(exe_path):
"""darwin 后台拉起换 LSUIElement 的 Helper(plugin-updater.cjs cliExecutable 同款):
主 bundle 二进制即使带 ELECTRON_RUN_AS_NODE,部分客户端版本仍会向 LaunchServices
登记 Foreground 应用,Dock 闪现「zcode」图标(issue #238);Helper 登记 UIElement
不进 Dock。Helper 缺失/不可执行/结构不符时原样返回——宁可闪图标不可更新/自检失败。"""
if not IS_MAC or not exe_path:
return exe_path
helper = (Path(exe_path).parent.parent / "Frameworks" / "ZCode Helper.app"
/ "Contents" / "MacOS" / "ZCode Helper")
if _safe_is_file(helper) and os.access(helper, os.X_OK):
return helper
return exe_path
def set_target(asar_path):
"""改指目标安装位置(BAK/TMP/ZCODE_EXE 随动)。ZCODE_EXE 只用于语法自检,缺了自动跳过。"""
global ASAR, BAK, TMP, TMP_META, ZCODE_EXE
asar_path = Path(asar_path).resolve()
ASAR = asar_path
BAK = asar_path.with_name("app.asar.zusage.bak")
TMP = asar_path.with_name("app.asar.zusage.tmp")
TMP_META = TMP.with_name(TMP.name + ".json")
ZCODE_EXE = zcode_exe_for(asar_path)
def client_running():
try:
if IS_WIN:
out = subprocess.run(
["tasklist", "/FI", "IMAGENAME eq ZCode.exe"],
capture_output=True, text=True, encoding="gbk", errors="replace",
creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0), # issue #221:无控制台宿主里探测会弹终端窗
).stdout
return "ZCode.exe" in out
# macOS/Linux:pgrep 精确匹配主进程名;误判"未运行"在 POSIX 上也无害
# (运行中替换本就允许:rename 语义,旧进程继续读旧 inode)
return subprocess.run(["pgrep", "-x", "ZCode"], capture_output=True).returncode == 0
except Exception:
return True # 查不到时按在跑处理,走安全路径
def _win_asar_in_use(path):
"""Windows 零写入共享占用探测:以 DELETE 权限与全共享
打开目标,仅在内核返回 ERROR_SHARING_VIOLATION (32) 时确认被运行中进程锁定
(os.replace 必然失败)。打开成功立即关闭句柄返回 False;非 Windows、其它错误码或
任何异常一律保守返回 False,交回原有 _replace_pending 路径。"""
if not IS_WIN:
return False
try:
import ctypes
kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
kernel32.CreateFileW.argtypes = [
ctypes.c_wchar_p, ctypes.c_uint32, ctypes.c_uint32,
ctypes.c_void_p, ctypes.c_uint32, ctypes.c_uint32, ctypes.c_void_p,
]
kernel32.CreateFileW.restype = ctypes.c_void_p
kernel32.CloseHandle.argtypes = [ctypes.c_void_p]
kernel32.CloseHandle.restype = ctypes.c_int
invalid = ctypes.c_void_p(-1).value
handle = kernel32.CreateFileW(
str(path), 0x00010000, 0x00000001 | 0x00000002 | 0x00000004,
None, 3, 0, None)
if handle in (None, invalid):
return ctypes.get_last_error() == 32 # ERROR_SHARING_VIOLATION
kernel32.CloseHandle(handle)
return False
except Exception:
return False
def _spawn_detached(cmd, flags, fallback=True, **kwargs):
"""Windows:优先带 CREATE_BREAKAWAY_FROM_JOB 拉起,让监控脱离父进程的 Job 对象——
从 agent/工具会话里跑安装时,会话清理会整树杀掉子进程,监控等不到客户端退出就被杀,
收尾只能寄望下次 SessionStart 重试。Job 不允许 breakaway 时降级为普通创建,并留
一行 stderr 线索(降级后的监控大概率活不过宿主回收,见 issue #208;静默场景的
存活兜底由 launch_monitor 的 WMI 通道承担,这里只是最后一级回退)。
fallback=False 时 breakaway 被拒直接抛 OSError,由调用方改走 WMI 脱离通道,
不先留一个注定被回收的树内监控。"""
if not IS_WIN:
return None
breakaway = getattr(subprocess, "CREATE_BREAKAWAY_FROM_JOB", 0)
try:
return subprocess.Popen(cmd, creationflags=flags | breakaway, **kwargs)
except OSError as e:
if not fallback:
raise
_warn_breakaway_denied(e)
return subprocess.Popen(cmd, creationflags=flags, **kwargs)
def _warn_breakaway_denied(e):
print(L(f"(breakaway 被拒({e}):监控留在父进程 Job 内,会随宿主回收被杀,"
f"可能收不了尾,见 issue #208)",
f"(breakaway denied ({e}): the monitor stays inside the parent job and "
f"will be killed with it; finalization may strand, see issue #208)"),
file=sys.stderr)
WMI_TIMEOUT = 15 # powershell 冷启动 + CIM 创建的富余上限(秒)
def _wmi_interpreter():
"""WMI 创建没有创建标志位可用:静默监控必须用无控制台的 pythonw.exe,缺失时
返回 None——不用 python.exe 顶替(会在交互会话闪现控制台窗,行为不能劣化,
宁可跳过 WMI 走树内回退)。"""
if not sys.executable: # 嵌入式场景可能为空:Path("").with_name 会抛 ValueError
return None
pythonw = Path(sys.executable).with_name("pythonw.exe")
return str(pythonw) if pythonw.is_file() else None
def _spawn_via_wmi(cmd):
"""Windows 脱离式拉起:经 WMI Win32_Process.Create 创建监控(父进程是 WmiPrvSE,
天然不在调用方的进程树/Job 内,宿主回收与会话清理都杀不到它)。插件宿主与
agent/工具会话的 Job 常不允许 breakaway,树内监控实测只活几分钟,等不到
「客户端完全退出」的收尾窗口(issue #208)。WMI 创建的进程不继承调用方环境,
静默开关由监控的 --quiet 参数传达;返回新进程 PID,任何失败返回 None
(调用方回退 _spawn_detached 树内拉起)。powershell -EncodedCommand 承载
UTF-16LE base64 脚本,避开 argv→PS 字符串→argv 的三层引号嵌套。"""
try:
command_line = subprocess.list2cmdline([str(part) for part in cmd])
script = ("$r = Invoke-CimMethod -ClassName Win32_Process -MethodName Create "
"-Arguments @{ CommandLine = '%s' }; "
"if ($r.ReturnValue -ne 0) { exit 1 }; [int]$r.ProcessId"
% command_line.replace("'", "''"))
encoded = base64.b64encode(script.encode("utf-16-le")).decode("ascii")
result = subprocess.run(
["powershell", "-NoProfile", "-NonInteractive", "-EncodedCommand", encoded],
capture_output=True, timeout=WMI_TIMEOUT,
creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0)) # issue #221
except (OSError, ValueError, subprocess.SubprocessError):
return None
if result.returncode != 0:
return None
try:
return int(result.stdout.decode("ascii", "replace").strip())
except ValueError:
return None
def _spawn_survivor_monitor(epoch):
"""WMI 脱离式拉起无窗口 --quiet 监控(静默收尾与可见监控 breakaway 被拒共用)。
ZUSAGE_MONITOR_NO_WMI=1 或无 pythonw.exe 时返回 None;解释器约束见 _wmi_interpreter。"""
if os.environ.get("ZUSAGE_MONITOR_NO_WMI"):
return None
interpreter = _wmi_interpreter()
if not interpreter:
return None
return _spawn_via_wmi([interpreter, str(HERE / "install_monitor.py"), "%.3f" % epoch,
str(ASAR), str(RUNTIME), "--quiet"])
def launch_monitor(epoch):
"""Windows 开新控制台窗口跑安装监控(提醒重启 + 确认生效 + .tmp 收尾);
macOS/Linux 无控制台概念,后台静默跑(收尾与自动退出照常)。设 ZUSAGE_NO_MONITOR=1 可禁用。
同目标已有存活监控时不再拉起(issue #120:SessionStart 每次自动安装都会走到这里,
不去重会随会话数线性堆积);锁在 spawn 前释放,由监控进程自己去持有。
返回值:Windows 走 WMI(静默分支,或可见分支 breakaway 被拒的幸存通道)时返回新进程
PID,其余返回 Popen 对象或 None(当前调用方均不消费返回值;PID 供测试断言与排查用)。"""
if os.environ.get("ZUSAGE_NO_MONITOR") and not os.environ.get("ZUSAGE_MONITOR_QUIET"):
return
monitor = HERE / "install_monitor.py"
if not monitor.exists():
return
with monitor_instance_lock() as acquired:
if not acquired:
if not os.environ.get("ZUSAGE_MONITOR_QUIET"): # 静默模式服务 hook,stdout 不夹文本
print(L("(已有监控在值守同一目标,不再重复弹窗:完全退出 ZCode 后会自动完成替换)",
"(A monitor is already watching this target, so no new window is opened: the replacement finishes automatically once ZCode quits completely)"))
return # 已有同目标监控在等:复用即可,不叠加进程
# 试锁成功即释放,锁的长期持有者是监控进程自己;极小竞态窗口内并发双拉起
# 也无害——后到的监控抢锁失败会自行退出。
cmd = [sys.executable, str(monitor), "%.3f" % epoch, str(ASAR), str(RUNTIME)]
try:
if os.environ.get("ZUSAGE_MONITOR_QUIET"):
if IS_WIN:
# 静默收尾必须活得过会话清理:优先 WMI 脱离式拉起(issue #208);
# 设 ZUSAGE_MONITOR_NO_WMI=1 可禁用(排查/测试出口)。WMI 创建不
# 继承本进程环境、也没有创建标志位,解释器须换同目录 pythonw.exe
#(无控制台;缺失时跳过 WMI 走树内回退——用 python.exe 会在交互
# 会话闪现控制台窗,行为不能劣化),静默开关走 --quiet 参数。
pid = _spawn_survivor_monitor(epoch)
if pid is not None:
return pid
return _spawn_detached(cmd, subprocess.CREATE_NO_WINDOW, cwd=str(HERE),
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL)
return subprocess.Popen(cmd, creationflags=0, cwd=str(HERE),
start_new_session=True,
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL)
if IS_WIN:
try:
return _spawn_detached(cmd, subprocess.CREATE_NEW_CONSOLE, fallback=False,
cwd=str(HERE))
except OSError as denied:
# breakaway 被拒:树内可见监控会在用户退出 ZCode 时随宿主回收一起消失,
# 手动安装就永远收不了尾(issue #208 同源)。先试 WMI 脱离的静默监控,
# 都不可用才回到原树内回退。注意 fallback=False 会把任意 Popen OSError
# 一并抛到这里(AV 拦截/磁盘故障同码 WinError 5,无法按错误码区分):
# 行为只会多一次 WMI 尝试、永不劣于基线,警告标签按最常见原因措辞。
pid = _spawn_survivor_monitor(epoch)
if pid is not None:
print(L("(监控窗口无法脱离 ZCode 进程组,已改为后台静默监控:没有监控窗口、"
"也无需保持任何窗口,完全退出 ZCode 后会自动完成替换)",
"(The monitor window cannot detach from ZCode's process group, so a silent background monitor was started instead: "
"there is no window to keep open; the replacement finishes automatically once ZCode quits completely)"))
return pid
_warn_breakaway_denied(denied)
return subprocess.Popen(cmd, creationflags=subprocess.CREATE_NEW_CONSOLE, cwd=str(HERE))
return subprocess.Popen(cmd, cwd=str(HERE),
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
except OSError as e:
print(L(f"(监控窗口启动失败,不影响安装:{e})",
f"(monitor window failed to launch; installation is unaffected: {e})"))
return None
# ---------- asar 读写 ----------
ASSET = "/" + ENTRY
# 注入表达式(逗号表达式元素,求值后结果被丢弃):stash 属宿主 bundle,本项目只 append。
STASH = "__zusageRelayStash"
# 只剥本项目的 loader 尾缀来复原指纹;其它尾部代码保持不动。
_INJECT_TAIL_RE = re.compile(ZUSAGE_LINE_RE.pattern + rb'\s*$')
# 桥接创建点:bridge.relayProtocol=<sym>,bridge.disposeBridge=...(混淆名随版本轮换)
_ANCHOR_RE = re.compile(rb"\b(\w+)\.relayProtocol=(\w+),\1\.disposeBridge\b")
# 注入串自身即补丁标记(符号随锚点);remove/检测按它定位,不依赖原始锚点连续存在
_INJECT_RE = re.compile(
rb"\(globalThis\.__zusageRelayStash=globalThis\.__zusageRelayStash\|\|\[\]\)"
rb"\.push\(\{p:(\w+)\.protocol,b:(\w+)\}\),")
# uplink 钩子原始锚点:onRawTransportPayload:s(ve=>Fg(ye,ve),"onRawTransportPayload")
# ——包装符号(s)/箭头参数(ve)/原调用(Fg)/运行时(ye)随版本轮换,稳定的是属性名与
# 字符串标签;body 必须恰为「单次调用」形态(3.18.1 实测),复杂化时 derive 拒绝。
_UPLINK_ANCHOR_RE = re.compile(
rb'onRawTransportPayload:(\w+)\((\w+)=>(\w+)\((\w+),\2\),"onRawTransportPayload"\)')
# 两代必须匹配完整回调,避免将游离的中段误认为可安全剥离的补丁。
_UPLINK_V1_RE = re.compile(
rb'onRawTransportPayload:(?P<w>\w+)\((?P<p>\w+)=>'
rb'\((?P=p)&&(?P=p)\.zuUp\?\(\(globalThis\.'
rb'__zusageRelayUplinkQueue=globalThis\.__zusageRelayUplinkQueue\|\|\[\]\)\.push\((?P=p)\),'
rb'true\):0\)\|\|(?P<f>\w+)\((?P<r>\w+),(?P=p)\),"onRawTransportPayload"\)')
# v2 回调(新/旧代共用):箭头体捕获一次桥并入队;差异只在属性值是否带代际 marker。
_V2_HEAD = rb'(?P<w>\w+)\((?P<p>\w+)=>'
_V2_VALUE = (
rb'\((?P=p)&&(?P=p)\.zuUp\?\(\((?P<b>\w+)\)=>\(\(globalThis\.'
rb'__zusageRelayUplinkQueue=globalThis\.__zusageRelayUplinkQueue\|\|\[\]\)\.push\('
rb'\{frame:(?P=p),b:(?P=b),relay:(?P=b)\?(?P=b)\.relayProtocol:void 0\}\),true\)\)'
rb'\((?P<r>\w+)\.currentBridge\):0\)\|\|(?P<f>\w+)\((?P=r),(?P=p)\)')
_V2_SUFFIX = rb',"onRawTransportPayload"\)'
# 新代在 transport options 构造时(announce / 首帧之前)于属性值内用逗号表达式写
# 代际 marker:onRawTransportPayload:(globalThis.__zusageRelayUplinkGeneration=2,<原包装>)。
# 已安装的旧 v2(无 marker)仍可识别、剥离与升级;两种形态起始字节不同,
# 不会互相嵌套命中。
UPLINK_GENERATION = 2
_UPLINK_GENERATION_MARKER = b"__zusageRelayUplinkGeneration"
_UPLINK_V2_RE = re.compile(rb'onRawTransportPayload:' + _V2_HEAD + _V2_VALUE + _V2_SUFFIX)
_UPLINK_V2_MARKED_RE = re.compile(
rb'onRawTransportPayload:\(globalThis\.' + _UPLINK_GENERATION_MARKER
+ b"=" + str(UPLINK_GENERATION).encode() + b","
+ _V2_HEAD + _V2_VALUE + _V2_SUFFIX + rb'\)')
_ROUTE_RE = re.compile(
rb'function (?P<f>\w+)\((?P<r>\w+),(?P<p>\w+)\)\{let (?P<b>\w+)=(?P=r)\.currentBridge;'
rb'return!(?P=b)\|\|(?P=b)\.degraded\?!1:(?P=b)\.relayProtocol\?\.acceptPayload\((?P=p)\)\?\?!1\}')
_UPLINK_MARKER = b"__zusageRelayUplinkQueue"
_STASH_MARKER = STASH.encode()
# ---------- 远控身份桥(getLogin 定向补丁,移动端远程控制)----------
# 官方 Web 远控以「当前登录账号」的 JWT 注册中继设备(manager 依赖装配点 getLogin),
# 手机必须登录同一账号才能配对。本补丁在 getLogin 箭头体首部插入
# globalThis.__zusageRemoteLogin(account-remote.cjs 桥)优先调用:桥返回身份即直接采用,
# 未启用/不可用返回 undefined 回官方原逻辑(fail-open,绝不让远控停在 auth-required)。
# 编译后形态(3.18.1 实测):
# getLogin:i(async()=>{let e=await r8(),t=await o8(e);return t?{userId:e,jwt:t.slice(7)}:void 0},"getLogin")
# wrapper/局部变量符号随版本轮换,稳定的是 getLogin 字面量、"Bearer ".length 的字面量 7
# 与「单次双调用」体形态;getLogin: 全 bundle 唯一(3.18.1 实测 1 处)。自身标记
# __zusageRemoteLogin 幂等装卸;不做 SHA 钉扎——本补丁排在 transform_mobile_entry 之后,
# 校验基底已含中继补丁,指纹会随两侧内容联动,改用严格锚点推导(唯一 + 形态完整匹配)。
_REMOTE_LOGIN_MARKER = b"__zusageRemoteLogin"
_REMOTE_LOGIN_STRIP_RE = re.compile(
rb'let (?P<v>\w+);try\{(?P=v)=await globalThis\.__zusageRemoteLogin\?\.\(\)\}catch\{\}'
rb'if\((?P=v)\)return (?P=v);')
_REMOTE_ANCHOR_RE = re.compile(
rb'getLogin:(?P<w>\w+)\(async\(\)=>\{let (?P<a>\w+)=await (?P<b>\w+)\(\),'
rb'(?P<c>\w+)=await (?P<d>\w+)\((?P=a)\);return (?P=c)\?\{userId:(?P=a),'
rb'jwt:(?P=c)\.slice\(7\)\}:void 0\},"getLogin"\)')
# 指纹表(新→旧):版本以 asar package.json 为准,SHA 是剥尾缀后的原始 bundle。
MOBILE_RELAY_TARGETS = [
{
"version": "3.18.1",
"asset": ASSET,
# 剥 patch_install 注入尾缀后的原始 bundle 指纹(以实测为准;尾缀差异
# 不影响——校验永远发生在剥尾缀之后)
"sha256": "9f414b7c9391de3a92d6373511df1374a6f270ae260ce802647ef0a05fe5cde8",
"anchor": b"relayProtocol=Ce,Q.disposeBridge",
"anchor2": b'onRawTransportPayload:s(ve=>Fg(ye,ve),"onRawTransportPayload")',
},
]
class RelayPatchError(ValueError):
pass
def inject_for(anchor):
"""锚点 → 注入表达式。锚点形如 relayProtocol=<r>,<b>.disposeBridge;
注入串插在 `relayProtocol=<r>,` 之后,捕获 <r>.protocol 与 <b> 整体。
两侧都必须显式 globalThis.:主 bundle 是 ESM(严格模式),对未声明标识符
赋值会 ReferenceError 炸掉桥接创建点。"""
m = re.fullmatch(rb"relayProtocol=(\w+),(\w+)\.disposeBridge", anchor)
if not m:
raise RelayPatchError("Malformed anchor")
relay, bridge = m.group(1), m.group(2)
g = b"globalThis." + STASH.encode()
return b"(" + g + b"=" + g + b"||[]).push({p:" + relay + b".protocol,b:" + bridge + b"}),"
def inject_for_uplink(anchor2):
"""包裹原回调;一次捕获当前桥,保持帧、桥和 relay 的对象身份。
整个属性值(原包装调用)被外层逗号表达式包裹:marker 在 transport options
构造时立即求值,announce 与任何帧都发生在其后,消费者据此在首帧前确认代际。"""
m = _UPLINK_ANCHOR_RE.fullmatch(anchor2)
if not m:
raise RelayPatchError("Malformed uplink anchor")
head = b"onRawTransportPayload:"
wrapper, param, _fn, runtime = m.groups()
bridge = b"__zuBridge"
while bridge in m.groups():
bridge += b"_"
arrow = head + wrapper + b"(" + param + b"=>"
mid = (b"(" + param + b"&&" + param + b".zuUp?((" + bridge + b")=>(("
b"globalThis.__zusageRelayUplinkQueue=globalThis.__zusageRelayUplinkQueue||[]).push("
b"{frame:" + param + b",b:" + bridge + b",relay:" + bridge + b"?" + bridge
+ b".relayProtocol:void 0}),true))(" + runtime + b".currentBridge):0)||")
wrapped = arrow + mid + anchor2[len(arrow):]
return (head + b"(globalThis." + _UPLINK_GENERATION_MARKER + b"="
+ str(UPLINK_GENERATION).encode() + b"," + wrapped[len(head):] + b")")
def _injection_state(prefix):
"""只接受完整、唯一的已知指纹;未知或混合代际一律拒绝。"""
stash = list(_INJECT_RE.finditer(prefix))
marked = list(_UPLINK_V2_MARKED_RE.finditer(prefix))
uplinks = list(_UPLINK_V1_RE.finditer(prefix)) + list(_UPLINK_V2_RE.finditer(prefix)) + marked
if len(stash) > 1 or prefix.count(_STASH_MARKER) != 2 * len(stash):
raise RelayPatchError("Unknown or duplicate stash inject")
if len(uplinks) > 1 or prefix.count(_UPLINK_MARKER) != 2 * len(uplinks):
raise RelayPatchError("Unknown or duplicate uplink inject")
if prefix.count(_UPLINK_GENERATION_MARKER) != len(marked):
raise RelayPatchError("Unknown or duplicate uplink generation marker")
return stash[0] if stash else None, uplinks[0] if uplinks else None
def _strip_injects(prefix):
"""剥离已知两代注入与 getLogin 身份桥注入,逐字节还原 pristine 前缀。"""
stash, uplink = _injection_state(prefix)
if uplink:
original = (b'onRawTransportPayload:' + uplink.group('w') + b'(' + uplink.group('p')
+ b'=>' + uplink.group('f') + b'(' + uplink.group('r') + b','
+ uplink.group('p') + b'),"onRawTransportPayload")')
prefix = prefix[:uplink.start()] + original + prefix[uplink.end():]
if stash:
# 上行还原后重新定位 stash,且注入串两侧必须仍是同一桥的原始锚点。
match = _INJECT_RE.search(prefix)
relay, bridge = match.groups()
before = bridge + b".relayProtocol=" + relay + b","
after = bridge + b".disposeBridge"
if (prefix[match.start() - len(before):match.start()] != before
or not prefix.startswith(after, match.end())):
raise RelayPatchError("Stash inject is not at the relay anchor")
prefix = prefix[:match.start()] + prefix[match.end():]
return _strip_remote_login(prefix)
def _strip_remote_login(prefix):
"""剥离已装的 getLogin 身份桥注入(0 或 1 处;>1 或标记数不符一律拒绝)。"""
matches = list(_REMOTE_LOGIN_STRIP_RE.finditer(prefix))
if len(matches) > 1 or prefix.count(_REMOTE_LOGIN_MARKER) != len(matches):
raise RelayPatchError("Unknown or duplicate remote-login inject")
for match in reversed(matches):
prefix = prefix[:match.start()] + prefix[match.end():]
return prefix
def transform_remote_login_entry(data, operation):
"""getLogin 身份桥补丁:从 pristine 幂等重建;锚点全量唯一匹配,fail-closed。"""
if operation not in ("apply", "remove"):
raise RelayPatchError("Unknown operation")
prefix, tail = _split_tail(data)
pristine = _strip_remote_login(prefix)
if operation == "remove":
if pristine != prefix and len(list(_REMOTE_ANCHOR_RE.finditer(pristine))) != 1:
raise RelayPatchError("Remote-login anchor not derivable after strip")
return pristine + tail
matches = list(_REMOTE_ANCHOR_RE.finditer(pristine))
if len(matches) != 1:
raise RelayPatchError("Remote-login anchor missing or ambiguous")
match = matches[0]
inject = b"let zuRemote;try{zuRemote=await globalThis.__zusageRemoteLogin?.()}catch{}if(zuRemote)return zuRemote;"
if any(match.group(name) == b"zuRemote" for name in ("w", "a", "b", "c", "d")):
raise RelayPatchError("Remote-login anchor symbols collide with inject variable")
# 注入点 = 箭头体开头(getLogin:<w>(async()=>{ 之后),原始体保持逐字节不变。
body_start = match.start() + len(b"getLogin:") + len(match.group("w")) + len(b"(async()=>{")
result = pristine[:body_start] + inject + pristine[body_start:]
return result + tail
def _remote_check_status(entry):
"""Return whether the getLogin identity bridge hook is complete with localized detail."""
try:
updated = transform_remote_login_entry(entry, "apply")
except RelayPatchError as error:
return False, L(f"无法检查({error})", f"unavailable ({error})")
if updated == entry:
return True, L("已注入", "patched")
if _REMOTE_LOGIN_MARKER in entry:
return False, L("可升级或补齐", "can be upgraded or completed")
return False, L("未注入,可补装", "not patched; install can add it")
def _derive_uplink_anchor(prefix):
"""表外版本需唯一匹配回调及其读取 currentBridge 的原始路由函数。"""
matches = list(_UPLINK_ANCHOR_RE.finditer(prefix))
if len(matches) != 1:
raise RelayPatchError("Uplink anchor not derivable (missing or ambiguous)")
match = matches[0]
routes = [route for route in _ROUTE_RE.finditer(prefix) if route.group('f') == match.group(3)]
if len(routes) != 1:
raise RelayPatchError("Uplink bridge route not derivable (missing or ambiguous)")
return match.group(0)
def _split_tail(data):
"""剥 patch_install 注入尾缀(有则剥,无则原样)。返回 (前缀, 尾缀)。"""
m = _INJECT_TAIL_RE.search(data)
if not m:
return data, b""
return data[:m.start()], data[m.start():]
def transform_mobile_entry(data, operation, target=None, *, package=None):
"""以同一份原始前缀校验布局并变换钩子,保留 loader 尾缀。"""
if operation not in ("apply", "remove"):
raise RelayPatchError("Unknown operation")
if isinstance(package, str):
raise RelayPatchError(package)
prefix, tail = _split_tail(data)
pristine = _strip_injects(prefix)
pinned = False
if package is not None:
target, pinned = _resolve_target(package, pristine)
if operation == "remove":
if pristine != prefix and target is None:
_derive_anchor(pristine)
_derive_uplink_anchor(pristine)
return pristine + tail
# 始终从 pristine 重建,避免旧代和新代叠加;两个锚点都必须唯一。
anchor = (target or {}).get("anchor")
if anchor is None:
anchor = _derive_anchor(pristine)
anchor2 = (target or {}).get("anchor2")
if anchor2 is None:
anchor2 = _derive_uplink_anchor(pristine)
if not pinned:
if pristine.count(anchor) != 1:
raise RelayPatchError("Missing or duplicate relay anchor")
if pristine.count(anchor2) != 1:
raise RelayPatchError("Missing or duplicate uplink anchor")
inject = inject_for(anchor)
split = anchor.split(b",", 1)[0] + b"," # relayProtocol=<sym>,
patched_anchor = split + inject + anchor[len(split):]
result = pristine.replace(anchor, patched_anchor, 1)
result = result.replace(anchor2, inject_for_uplink(anchor2), 1)
return result + tail
def _derive_anchor(prefix):
"""表外版本的严格推导:全 bundle 唯一的 bridge.relayProtocol 赋值锚点。"""
matches = _ANCHOR_RE.findall(prefix)
if len(matches) != 1:
raise RelayPatchError("Relay anchor not derivable (missing or ambiguous)")
bridge, relay = matches[0] # 捕获组1=桥接宿主对象(Q),组2=relay 协议实例(Ce)
return b"relayProtocol=" + relay + b"," + bridge + b".disposeBridge"
def _resolve_target(package, pristine):
"""返回目标锚点及是否已按登记指纹校验其唯一性。"""
version = package.get("version")
target = next((t for t in MOBILE_RELAY_TARGETS if t["version"] == version), None)
if target is not None:
if hashlib.sha256(pristine).hexdigest() != target["sha256"]:
raise RelayPatchError(f"asset hash mismatch for pinned version {version}")
if pristine.count(target["anchor"]) != 1:
raise RelayPatchError("Pinned anchor drift")
anchor2 = target.get("anchor2")
if anchor2 is None or pristine.count(anchor2) != 1:
raise RelayPatchError("Pinned uplink anchor drift")
return target, True
return {"anchor": _derive_anchor(pristine), "anchor2": _derive_uplink_anchor(pristine)}, False
def _relay_check_status(entry, package):
"""Return whether the current hooks are complete along with the localized detail."""
try:
updated = transform_mobile_entry(entry, "apply", package=package)
except RelayPatchError as error:
return False, L(f"无法检查({error})", f"unavailable ({error})")
if updated == entry:
return True, L("已注入", "patched")
if _STASH_MARKER in entry or _UPLINK_MARKER in entry or _UPLINK_GENERATION_MARKER in entry:
return False, L("可升级或补齐", "can be upgraded or completed")
return False, L("未注入,可补装", "not patched; install can add it")
def _mobile_check_status(asar_path, entry):
"""Compatibility entry point for an older overlay_install doctor."""
try:
_, current, package = _archive_snapshot(asar_path)
if current != entry:
raise PendingTmpError("archive entry changed during inspection")
except (OSError, ValueError, TypeError, KeyError, OverflowError, struct.error) as error:
return L(f"无法检查({error})", f"unavailable ({error})")
return _relay_check_status(entry, package)[1]
def read_header(f, *, digest=None):
f.seek(0)
prefix = f.read(16)
a, b, c, d = struct.unpack("<4I", prefix)
assert a == 4, f"unexpected pickle prefix {a}"
raw = f.read(d)
if digest is not None:
digest.update(prefix)
digest.update(raw)
return json.loads(raw), 8 + b
def read_asar_package(asar_path, pi=None):
"""读取 asar 根目录 package.json 解析后的字典;非 asar、unpacked 外置或损坏时返回 None。"""
reader = read_header if pi is None else getattr(pi, "read_header", read_header)
try:
with open(asar_path, "rb") as stream:
header, base = reader(stream)
node = header.get("files", {}).get("package.json")
if not isinstance(node, dict) or node.get("unpacked") or "size" not in node:
return None
stream.seek(base + int(node["offset"]))
data = stream.read(int(node["size"]))
if b"\x00" in data:
return None
pkg = json.loads(data.decode("utf-8"))
return pkg if isinstance(pkg, dict) else None
except Exception:
return None
def iter_files(node, path=""):
"""yield (path_in_asar, node_dict)。node_dict 为文件(含 size)。"""
for name, ch in node.get("files", {}).items():
p = f"{path}/{name}"
if "files" in ch:
yield from iter_files(ch, p)
else:
yield p, ch
def compute_integrity(data: bytes):
return {
"algorithm": "SHA256",
"hash": hashlib.sha256(data).hexdigest(),
"blockSize": BLOCK,
"blocks": [hashlib.sha256(data[i:i + BLOCK]).hexdigest() for i in range(0, len(data), BLOCK)],
}
class _Digest:
"""边写边算的整包摘要;size 记录喂入的字节数,对不上产物大小即不可信。"""
def __init__(self):
self.hash = hashlib.sha256()
self.size = 0
def update(self, data):
self.hash.update(data)
self.size += len(data)
_REPACK_SINK = None # _repack_digest() 持有期间的摘要接收方
@contextmanager
def _repack_digest():
"""让其间的 repack() 边写边算产物的 SHA256。repack 被替身顶替或没写满时
sink.size 为 0 或小于产物,调用方回退整包回读。"""
global _REPACK_SINK
sink = _Digest()
_REPACK_SINK = sink
try:
yield sink
finally:
_REPACK_SINK = None
def repack(src_path: Path, modify: dict, dst_path: Path):
"""重建 asar。modify: {asar内路径: 新内容bytes}。逐文件边读边写,未改动文件不落内存。"""
with open(src_path, "rb") as src:
header, base = read_header(src)
header = json.loads(json.dumps(header)) # 深拷贝
nodes = dict(iter_files(header))
missing = set(modify) - set(nodes)
assert not missing, f"paths not in asar: {missing}"
# 第一遍只定新偏移:改写项记新内容,其余记源数据起点,都不读数据
plan, offset = [], 0
for p, node in nodes.items():
if node.get("unpacked"):
node["offset"] = "0"
continue
if "link" in node:
continue
if p in modify:
data = modify[p]
node["size"] = len(data)
node["integrity"] = compute_integrity(data)
plan.append((None, data))
else:
plan.append((base + int(node["offset"]), node["size"]))
node["offset"] = str(offset)
offset += node["size"]
header_bytes = json.dumps(header, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
d = len(header_bytes)
c = (d + 4 + ALIGN - 1) // ALIGN * ALIGN
b_total = c + 4
sink = _REPACK_SINK
with open(dst_path, "wb", buffering=BLOCK) as out:
def write(data):
out.write(data)
if sink is not None:
sink.update(data)
write(struct.pack("<4I", 4, b_total, c, d))
write(header_bytes)
write(b"\0" * (c - d - 4)) # pickle 对齐:数据区从 8+b = 12+c 处开始
assert out.tell() == 8 + b_total, f"header pad mismatch: {out.tell()} vs {8 + b_total}"
for start, payload in plan:
if start is None:
write(payload)
continue
src.seek(start)
remaining = payload
while remaining:
chunk = src.read(min(BLOCK, remaining))
if not chunk:
raise OSError(f"source archive truncated: {src_path}")
write(chunk)
remaining -= len(chunk)
return dst_path
def _lookup_node(header, path):
"""按绝对归档路径沿 header 目录树直接定位文件节点,避免为读单个条目而展开全表
node_modules(3 万余文件)。找不到或命中带 files 的目录节点返回 None。"""
node = header
for part in path.lstrip("/").split("/"):
files = node.get("files") if isinstance(node, dict) else None
if not isinstance(files, dict) or part not in files:
return None
node = files[part]
return node if isinstance(node, dict) and "files" not in node else None
def entry_bytes_of(asar_path: Path) -> bytes:
with open(asar_path, "rb") as f:
header, base = read_header(f)
node = _lookup_node(header, "/" + ENTRY)
if node is None:
raise KeyError("/" + ENTRY)
f.seek(base + int(node["offset"]))
return f.read(node["size"])
def self_check(asar_path: Path, expect=True):
"""结构自检:header 可解析、文件数、入口注入行符合预期(install 期望有,remove 期望无)。"""
with open(asar_path, "rb") as f:
header, base = read_header(f)
n = sum(1 for _ in iter_files(header))
entry = entry_bytes_of(asar_path)
has = INJECT_LINE.encode() in entry if expect else bool(ZUSAGE_LINE_RE.search(entry))
ok = has == expect
print(L(f" [check] header ok, 文件数={n}, 注入行{'符合' if ok else '不符合'}预期(期望{'有' if expect else '无'})",
f" [check] header ok, files={n}, injection line {'as expected' if ok else 'UNEXPECTED'} (expected {'present' if expect else 'absent'})"))
return ok
def syntax_check(asar_path: Path):
"""用 ZCode 自身当 node(ELECTRON_RUN_AS_NODE)对入口做语法检查;
找不到/无法运行 ZCode 可执行文件时跳过(此时不挡安装;收尾校验真跑出语法错误仍 fail-closed 拒收)。"""
exe = ui_element_exe_for(ZCODE_EXE)
if not _safe_is_file(exe):
print(L(" [check] 未找到 ZCode 可执行文件,跳过语法检查",
" [check] ZCode executable not found; syntax check skipped"))
return True
src = entry_bytes_of(asar_path)
env = dict(os.environ, ELECTRON_RUN_AS_NODE="1")
fd, tmp_js, r, run_err = None, None, None, ""
try:
# 入口是 ESM(package.json type:module):临时 .js 在 HERE(无 type:module 上下文)里
# 会被 node --check 按 CJS goal 解析,顶层 import 必报语法错误;用 .mjs 按 ESM 检查。
# 走 bounded_mkstemp:HERE 若位于受保护目录(无锁先行证明可写),stdlib 的
# tempfile.mkstemp 在 Windows 上会吞掉 PermissionError 无限换名挂起(issue #360),
# 根本进不了下方 except OSError 的跳过分支。
fd, name = bounded_mkstemp(prefix=".entry-check.", suffix=".mjs", dir=HERE)
tmp_js = Path(name)
with os.fdopen(fd, "wb") as stream:
stream.write(src)
# Node 恒写 UTF-8:按区域编码解码,回显里的非 ASCII(中文路径/源码行)会让 Windows
# 读线程崩溃(stderr 变 None)或解成乱码。
r = subprocess.run([str(exe), "--check", str(tmp_js)], capture_output=True, text=True,
encoding="utf-8", errors="replace", env=env)
except OSError as e:
r = None
run_err = str(e)
finally:
if tmp_js is not None:
try:
tmp_js.unlink(missing_ok=True) # mkstemp 本身失败时无临时文件可清
except OSError:
pass
if r is None:
print(L(f" [check] 语法检查无法执行({run_err}),跳过",
f" [check] syntax check failed to run ({run_err}); skipped"))
return True
# 当前输出编码打印不了的字符(cp1252/ASCII 管道上的中文路径等)转义,其余原样显示;
# 重定向到 StringIO 时 encoding 为 None,按 UTF-8 处理。
enc = getattr(sys.stdout, "encoding", None) or "utf-8"
detail = r.stderr.strip()[:200].encode(enc, "backslashreplace").decode(enc)
print(L(" [check] 语法检查 exit=", " [check] node --check exit=") + str(r.returncode) + " " + detail)
return r.returncode == 0
def cleanup_legacy_bak():
"""备份机制已退役(安装/卸载均改为剥离注入行):清掉历史版本遗留的 .bak,省约 300MB 磁盘。"""
if not BAK.exists():
return
try:
BAK.unlink()
print(L(f"已清理历史遗留备份 {BAK}", f"Removed legacy backup {BAK}"))
except OSError as e:
print(L(f"(遗留备份清理失败,可手动删除 {BAK}:{e})",
f"(failed to remove legacy backup {BAK}; delete it manually: {e})"))
# ---------- 待替换包的来源与身份 ----------
class PendingTmpError(ValueError):
"""来源/身份不可信:立即取消收尾,保留文件供诊断,不按文件占用重试。"""
class PatchSourceChanged(PendingTmpError):
"""补装的锁外构建遇到源归档变化;调用方可基于新入口重建一次。"""
class PatchLockBusy(TimeoutError):
"""零等待补装锁竞争,可由 SessionStart 按预算退避重试。"""
class PendingTmpBusy(PendingTmpError):
"""发布中 journal 的瞬时态(issue #228):监控重试续守而非取消让位。_publish_pending
先写 cancelled+publishing journal、全量 hash 大包后才落终版 sidecar——这个秒级
窗口里轮询的旧监控若按 cancelled 退出让位,而 launch_monitor 的去重又认定
「已有监控在等」不拉新监控,交接就断裂成孤儿 pending(之后重启不再替换)。子类化
保持既有 except PendingTmpError 全部语义,监控循环按需先行捕获。"""
# Windows 的 st_ctime 是创建时间:内容修改不会改变它(没有防篡改价值),且杀软过滤
# 驱动下同一路径 lstat 与打开句柄 fstat 读到的 ctime_ns 可能恒不一致(NTFS 实测,
# size/mtime/dev/ino 均相同),纳入比对会让每次 source_fingerprint 都误报
# "file changed"。POSIX 的 ctime 是 inode 变更时间,写入会更新,保留作额外信号。
if sys.platform == "win32":
_STAMP_FIELDS = ("size", "mtime_ns", "dev", "ino")
else:
_STAMP_FIELDS = ("size", "mtime_ns", "ctime_ns", "dev", "ino")
def _stat_stamp(st):
if not stat.S_ISREG(st.st_mode):
raise PendingTmpError("not a regular file")
values = {"size": st.st_size, "mtime_ns": st.st_mtime_ns,
"ctime_ns": st.st_ctime_ns, "dev": st.st_dev, "ino": st.st_ino}
return {key: values[key] for key in _STAMP_FIELDS}
def file_stamp(path):
"""廉价身份快照(不跟随 symlink);每轮监控只读 stat 和小 sidecar。"""
return _stat_stamp(Path(path).lstat())
def _hash_up_to(stream, digest, offset):
"""Feed the bytes up to an absolute offset into the same running digest."""
if offset < digest.size:
raise PendingTmpError("archive assets overlap")
stream.seek(digest.size)
while digest.size < offset:
block = stream.read(min(BLOCK, offset - digest.size))
if not block:
raise PendingTmpError("file truncated while hashing")
digest.update(block)
def source_fingerprint(path):
"""流式 SHA256;hash 前后及打开的 inode 都须一致,避免读取升级中的混合包。"""
before = file_stamp(path)
digest = _Digest()
with open(path, "rb") as stream:
if _stat_stamp(os.fstat(stream.fileno())) != before:
raise PendingTmpError("file changed before hashing")
_hash_up_to(stream, digest, before["size"])
if _stat_stamp(os.fstat(stream.fileno())) != before:
raise PendingTmpError("file changed while hashing")
if file_stamp(path) != before:
raise PendingTmpError("file replaced while hashing")
return dict(before, sha256=digest.hash.hexdigest())
def _read_relay_package(raw, nodes, entry):
if raw is None:
raise RelayPatchError("Missing packed package.json")
package = json.loads(raw.decode("utf-8"))
if (not isinstance(package, dict)
or (package.get("name"), package.get("type")) != ("@zcode/desktop", "module")):
raise RelayPatchError("Unknown host package")
if b"sourceMappingURL" in entry or any(
item in nodes for item in (ASSET + ".map", ASSET[:-3] + ".map")):
raise RelayPatchError("Unverified source map layout")
return package
def _archive_extent(node, base, size):
offset = base + int(node["offset"])
length = int(node["size"])
if offset < base or length < 0 or offset + length > size:
raise PendingTmpError("archive asset extent is invalid")