desktop_plugins.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. """The Webapp's door to this host's desktop plugins (``<root>/desktop-plugins/<name>/plugin.js``).
  2. Native Desktop reads that folder from its own disk (``desktopPluginsRoot`` in Electron's
  3. ``fs-ipc.ts``). The Webapp's renderer runs in a browser whose only disk is this server, so the
  4. browser bridge asks here instead, and the same runtime loader scans, loads and polls it.
  5. The routes answer only what the loader reads: the root, its plugin folders, and each folder's
  6. ``plugin.js`` and ``.hermes-package.json``. Containment is checked on the path as written, then
  7. symlinks are followed as Electron's ``readDir`` does, so ``desktop-plugins/foo -> ~/src/foo`` loads
  8. here too. They never go through ``/api/fs``, which follows the profile's SSH workspace and truncates
  9. at the preview cap. Like Electron, resolving the root first copies agent+desktop packages' desktop
  10. halves into it (``desktop_plugin_halves.py``), the one write these routes make. Webapp only
  11. (``SurfacePolicy.desktop_plugins``; 404 elsewhere).
  12. """
  13. from __future__ import annotations
  14. import asyncio
  15. import os
  16. import stat
  17. from pathlib import Path
  18. from fastapi import APIRouter, HTTPException
  19. from hermes_cli.desktop_plugin_halves import reconcile_desktop_halves, reconcile_desktop_halves_report
  20. from hermes_cli.desktop_plugin_install import DESKTOP_PLUGINS_DIR, desktop_plugins_root
  21. from hermes_constants import get_default_hermes_root
  22. router = APIRouter()
  23. #: The files the loader reads in a plugin folder: its entry and the unified-package marker.
  24. _READABLE_FILES = frozenset({"plugin.js", ".hermes-package.json"})
  25. #: Electron's ``PLUGIN_SOURCE_MAX_BYTES``: a plugin loads whole or not at all, never truncated.
  26. PLUGIN_SOURCE_MAX_BYTES = 16 * 1024 * 1024
  27. #: Never follow a final link where the OS can refuse one, and never block on a FIFO.
  28. _OPEN_FLAGS = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_BINARY", 0)
  29. def _inside_root(raw: str) -> tuple[Path, tuple[str, ...]]:
  30. """*raw* and its parts below the root, judged as written: no ``..``, at most a folder and a file.
  31. Links are not resolved here; a linked plugin folder is followed like native Desktop follows it.
  32. The files inside it are not: :func:`_read` refuses a linked entry file, which could name any
  33. file on the host, ``.env`` included, past the sensitive-file guard ``/api/fs`` applies."""
  34. root = desktop_plugins_root()
  35. try:
  36. parts = Path(raw).relative_to(root).parts
  37. except ValueError:
  38. raise HTTPException(status_code=404, detail="Not a desktop plugin path") from None
  39. if len(parts) > 2 or ".." in parts:
  40. raise HTTPException(status_code=404, detail="Not a desktop plugin path")
  41. return root.joinpath(*parts), parts
  42. def _list(raw: str) -> dict:
  43. target, parts = _inside_root(raw)
  44. if len(parts) > 1 or not target.is_dir():
  45. raise HTTPException(status_code=404, detail="Not a desktop plugin folder")
  46. entries = [
  47. {"name": child.name, "path": str(target / child.name), "isDirectory": child.is_dir()}
  48. for child in sorted(target.iterdir(), key=lambda child: child.name)
  49. ]
  50. return {"entries": entries}
  51. def _read(raw: str) -> dict:
  52. from hermes_cli.web_routers.files import _is_sensitive_path
  53. target, parts = _inside_root(raw)
  54. not_found = HTTPException(status_code=404, detail="Not a desktop plugin file")
  55. if len(parts) != 2 or parts[1] not in _READABLE_FILES:
  56. raise not_found
  57. # Follow a linked plugin folder, never a linked file in it. The file actually opened must be the
  58. # regular file at the entry's real, non-sensitive path, checked again after the open, so swapping
  59. # the entry or its folder for a link mid-read fails closed, with or without O_NOFOLLOW.
  60. try:
  61. entry = target.parent.resolve(strict=True) / parts[1]
  62. if _is_sensitive_path(entry) or not stat.S_ISREG(os.lstat(entry).st_mode):
  63. raise not_found
  64. fd = os.open(entry, _OPEN_FLAGS)
  65. except OSError:
  66. raise not_found from None
  67. with os.fdopen(fd, "rb") as handle:
  68. st = os.fstat(handle.fileno())
  69. try:
  70. here = os.lstat(entry)
  71. unchanged = entry.resolve(strict=True) == entry
  72. except OSError:
  73. raise not_found from None
  74. if not (unchanged and stat.S_ISREG(st.st_mode) and (st.st_dev, st.st_ino) == (here.st_dev, here.st_ino)):
  75. raise not_found
  76. if st.st_size > PLUGIN_SOURCE_MAX_BYTES:
  77. raise HTTPException(status_code=413, detail="Plugin source exceeds 16 MiB")
  78. data = handle.read(PLUGIN_SOURCE_MAX_BYTES + 1)
  79. if len(data) > PLUGIN_SOURCE_MAX_BYTES:
  80. raise HTTPException(status_code=413, detail="Plugin source exceeds 16 MiB")
  81. text = data.decode("utf-8-sig", errors="replace")
  82. return {"byteSize": st.st_size, "path": str(target), "text": text, "truncated": False}
  83. def _root_reconciled() -> str:
  84. """The root, after copying unified packages' desktop halves into it: what Electron's
  85. ``desktopPluginsRoot`` does before every scan. On a host native Desktop only reaches over SSH,
  86. nothing else ever makes that copy."""
  87. root = desktop_plugins_root()
  88. reconcile_desktop_halves(get_default_hermes_root(), root)
  89. return str(root)
  90. @router.get("/api/desktop-plugins/root")
  91. async def desktop_plugins_root_route() -> dict:
  92. return {"root": await asyncio.to_thread(_root_reconciled)}
  93. @router.post("/api/desktop-plugins/reconcile")
  94. async def reconcile_desktop_plugins() -> dict:
  95. """Electron's ``reconcileDesktopPluginsReport``: re-run the copy after an install, update or removal, and
  96. name each package whose desktop half it refused and no later profile published, so the install tab does not
  97. report it as installed."""
  98. return await asyncio.to_thread(reconcile_desktop_halves_report, get_default_hermes_root(), desktop_plugins_root())
  99. @router.get("/api/desktop-plugins/list")
  100. async def list_desktop_plugins(path: str) -> dict:
  101. return await asyncio.to_thread(_list, path)
  102. @router.get("/api/desktop-plugins/read")
  103. async def read_desktop_plugin_file(path: str) -> dict:
  104. return await asyncio.to_thread(_read, path)