desktop_update_verify.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. """Read-only verification at the Windows Desktop handoff receipt boundary."""
  2. import json
  3. from pathlib import Path, PurePosixPath
  4. import re
  5. import struct
  6. from hermes_cli.main_desktop import (
  7. _HTML_TAG_WITH_URL,
  8. _MODULE_TAG,
  9. _desktop_build_needed,
  10. _desktop_exe_integrity_error,
  11. _desktop_packaged_executable,
  12. )
  13. def _verify_packaged_entry(resources: Path) -> None:
  14. """Read ASAR's Pickle header and the entry declared by packaged package.json.
  15. dist/** is unpacked by electron-builder. No Node install or application
  16. launch is needed at this boundary; this is not a full dependency audit.
  17. """
  18. archive = resources / "app.asar"
  19. try:
  20. with archive.open("rb") as stream:
  21. size, header_size, payload_size, json_size = struct.unpack("<4I", stream.read(16))
  22. if (size != 4 or header_size != payload_size + 4
  23. or payload_size != 4 + ((json_size + 3) // 4) * 4
  24. or not 0 < json_size <= 64 * 1024 * 1024
  25. or 8 + header_size > archive.stat().st_size):
  26. raise ValueError("invalid ASAR header")
  27. header = json.loads(stream.read(json_size))
  28. def read_member(name: str) -> bytes:
  29. path = PurePosixPath(name)
  30. if not name or path.is_absolute() or ".." in path.parts or "\\" in name or ":" in name:
  31. raise ValueError("invalid ASAR entry path")
  32. node = header
  33. for part in path.parts:
  34. node = node["files"][part]
  35. length = node["size"]
  36. if not isinstance(length, int) or length <= 0:
  37. raise ValueError(f"empty ASAR entry: {name}")
  38. if node.get("unpacked"):
  39. data = (resources / "app.asar.unpacked" / path).read_bytes()
  40. else:
  41. offset = int(node["offset"])
  42. if offset < 0 or 8 + header_size + offset + length > archive.stat().st_size:
  43. raise ValueError(f"truncated ASAR entry: {name}")
  44. stream.seek(8 + header_size + offset)
  45. data = stream.read(length)
  46. if len(data) != length or not data.strip():
  47. raise ValueError(f"incomplete ASAR entry: {name}")
  48. return data
  49. package = json.loads(read_member("package.json"))
  50. read_member(package["main"]).decode("utf-8")
  51. except (OSError, ValueError, KeyError, TypeError, struct.error) as exc:
  52. raise RuntimeError(f"The updated Desktop archive or main entry is invalid: {exc}") from exc
  53. index = resources / "app.asar.unpacked" / "dist" / "index.html"
  54. try:
  55. html = index.read_text(encoding="utf-8-sig")
  56. if not any(_MODULE_TAG.search(match.group(0))
  57. and match.group(0).lower().startswith("<script")
  58. and not re.match(r"^[a-z]+:|^//", match.group(1), re.IGNORECASE)
  59. for match in _HTML_TAG_WITH_URL.finditer(html)):
  60. raise ValueError("renderer has no local module entry")
  61. except (OSError, ValueError) as exc:
  62. raise RuntimeError(f"The updated Desktop renderer entry is invalid: {exc}") from exc
  63. def checkout_root() -> Path:
  64. """The checkout this module was imported from: the only root the receipt may describe."""
  65. return Path(__file__).resolve().parent.parent
  66. def _root_to_verify(project_root: Path | None) -> Path:
  67. """The root the receipt may describe: a caller's root is a hint, not a contract.
  68. The hand-off script is read before the pull, so an update that ships a fix to
  69. the caller side cannot apply it to its own run: a pre-fix ``windows.ps1`` still
  70. passes ``Path.cwd()``, which is HERMES_HOME and never holds a packaged Desktop
  71. app. Honour a caller-supplied root only while it actually carries one, and fall
  72. back to the checkout this module was imported from -- the tree the update just
  73. wrote. A supplied root that does carry a packaged app is still verified as
  74. given, so real damage there stays fail-closed.
  75. """
  76. if project_root is None:
  77. return checkout_root()
  78. if _desktop_packaged_executable(project_root / "apps" / "desktop") is not None:
  79. return project_root
  80. return checkout_root()
  81. def verify_windows_desktop_update(project_root: Path | None = None) -> None:
  82. """Raise when a zero-exit updater left an incomplete or stale packaged app.
  83. The root defaults to the imported checkout, never the caller's cwd: the hand-off
  84. is spawned from HERMES_HOME by the pre-update Desktop, and a cwd-derived root
  85. reported a healthy install as "Desktop executable is missing" (Sep 2026). A
  86. caller-supplied root with no packaged app falls back to that same checkout, so a
  87. stale in-flight hand-off cannot fail a healthy install either.
  88. """
  89. project_root = _root_to_verify(project_root)
  90. desktop = project_root / "apps" / "desktop"
  91. executable = _desktop_packaged_executable(desktop)
  92. if executable is None:
  93. raise RuntimeError("The updated Desktop executable is missing")
  94. error = _desktop_exe_integrity_error(executable)
  95. if error:
  96. raise RuntimeError(f"The updated Desktop executable is invalid: {error}")
  97. _verify_packaged_entry(executable.parent / "resources")
  98. if _desktop_build_needed(desktop, project_root, source_mode=False):
  99. raise RuntimeError("The updated Desktop build is stale, unstamped, or incomplete")
  100. if __name__ == "__main__":
  101. verify_windows_desktop_update()