plugin_validate_desktop.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. """Static admission lint for a plugin's Desktop surface (``plugin.js`` / ``desktop/plugin.js``).
  2. A ``plugin.js`` is evaluated as ESM in the Electron renderer realm with the app's full authority
  3. (``apps/desktop/src/contrib/runtime-loader.ts`` says so in its header: error isolation only, no
  4. capability boundary). The loader accepts that for files the user put on disk; a catalog install is a
  5. remote source, so listed plugins must stay inside the SDK surface. This lint refuses the moves that
  6. step outside it. It is a tripwire for review, not a sandbox.
  7. """
  8. from __future__ import annotations
  9. import re
  10. from pathlib import Path
  11. from typing import List, Tuple
  12. # (rule, regex) applied to comment-stripped source; every hit fails the "desktop surface" check.
  13. # Prototype writes are not linted: bundled libraries (three.js) set fields on their own classes, and
  14. # no regex could tell those from patching a renderer global without misfiring on minified names.
  15. # Catalog review reads them by hand.
  16. _FORBIDDEN: tuple[tuple[str, re.Pattern[str]], ...] = (
  17. ("dynamic code evaluation",
  18. re.compile(r"(?<![\w$.])eval\(|\bnew\s+Function\(")),
  19. ("dynamic import outside the SDK",
  20. re.compile(r"\bimport\(\s*(?!['\"](?:@hermes/plugin-sdk|react)(?:/[\w/-]*)?['\"]\s*\))")),
  21. # A static `import 'https://…'` / `import x from 'file:…'` is the same second stage as the
  22. # dynamic form above (the renderer would fetch and evaluate it); the loader refuses every
  23. # URL-scheme specifier too (runtime-loader.ts::unsupportedImports) — this keeps admission and
  24. # the loader in agreement instead of letting review wave through what the app rejects.
  25. ("remote import outside the SDK",
  26. re.compile(r"\bimport\s+(?:[^;'\"]*?\bfrom\s*)?['\"][a-zA-Z][\w+.-]*:")),
  27. ("script injection",
  28. re.compile(r"createElement\(\s*['\"]script['\"]\s*\)|<script\b")),
  29. # The app's own markup (`data-slot` / `data-tour` / `data-sidebar` / `data-testid`) is not plugin
  30. # surface: a plugin that queries it to restyle, hide, click or rewrite core UI collides with every
  31. # other plugin doing the same and breaks on any Desktop release. Use a slot, route or SDK hook.
  32. ("app DOM reach",
  33. re.compile(r"\bdocument\.(?:querySelector(?:All)?|getElementsBy\w+|getElementById)\(\s*[`'\"][^`'\"]*"
  34. r"\[data-(?:slot|tour|sidebar|testid)\b")),
  35. ("app DOM reach",
  36. re.compile(r"\.observe\(\s*document\.body\s*,\s*\{[^}]*\b(?:childList|subtree)\b")),
  37. # The preview Browser can hold pages the user is signed in to. Script reaches it only through
  38. # ``ctx.preview.executeJavaScript``: a declared capability plus the user's per-origin consent.
  39. # Grabbing the app's ``<webview>`` (or minting one on the preview partition) skips both.
  40. ("preview guest reach",
  41. re.compile(r"\b(?:querySelector(?:All)?|closest|getElementsByTagName|createElement)\(\s*[`'\"]webview\b")),
  42. )
  43. # Review cues, warned and never refused (catalog rule 8): the raw ``window.hermesDesktop`` native bridge
  44. # (files, git, REST, installs) has no folder or profile scoping — ``ctx.files`` / ``ctx.os`` /
  45. # ``host.request`` do — yet listed plugins still use it where the SDK has no verb (microphone access,
  46. # favicon lookup). And the app's markup selected from a CSS rule string, ``closest()`` or a template
  47. # (``[data-tree-tab=…]{display:none}``) is the reach the refused ``document.querySelector`` rule
  48. # names, in shapes no refusal regex can tell from a plugin styling SDK components it rendered itself.
  49. _REVIEW: tuple[tuple[str, re.Pattern[str]], ...] = (
  50. ("raw bridge window.hermesDesktop",
  51. re.compile(r"\b(?:window|globalThis|self)\s*(?:\?\.|\.)\s*hermesDesktop\b")),
  52. ("app markup selector",
  53. re.compile(r"\[data-(?:slot|tour|sidebar|testid|tree-[\w-]+|pane-host|titlebar-cluster)\b")),
  54. )
  55. # String literals are matched first and kept, so a ``/*`` or ``//`` INSIDE a string (a glob such as
  56. # ``'**/*.md'``, a URL) cannot open a "comment" that blanks every line up to the next ``*/`` and
  57. # hides whatever forbidden construct sits there.
  58. _COMMENT = re.compile(
  59. r"(\"(?:[^\"\\\n]|\\.)*\"|'(?:[^'\\\n]|\\.)*'|`(?:[^`\\]|\\.)*`)"
  60. r"|/\*.*?\*/|(?<![:\w])//[^\n]*",
  61. re.DOTALL,
  62. )
  63. def _strip_comments(source: str) -> str:
  64. return _COMMENT.sub(lambda m: m.group(1) or "\n" * m.group(0).count("\n"), source)
  65. # A JS regex literal (``/<script[\s\S]*?<\/script>/gi``) matches markup, it cannot inject any: a
  66. # feed sanitiser that STRIPS script tags is the opposite of the move the rule refuses. Regex
  67. # literals are masked for the markup-shaped rules only; a ``<script`` inside a string literal is
  68. # still the payload of an ``innerHTML`` write and keeps firing. The lookbehind keeps division
  69. # (``a / b / c``) from reading as a literal. The pattern string handed straight to ``new RegExp(``
  70. # is the same sanitiser spelled for a dynamic flag (rss-reader split it into ``"<scr"+"ipt"`` to
  71. # dodge this rule) — but only where the constructor is USED as a matcher: the argument of a string
  72. # method (``html.replace(new RegExp("<script…", flags), '')``) or the receiver of ``.test``/``.exec``.
  73. # Anywhere else (``el.innerHTML = new RegExp("<script src=x></script>").source``) the constructor is
  74. # a string-builder and its literal keeps firing.
  75. _REGEX_LITERAL = re.compile(r"(?<![\w)\]])/(?:[^/\\\n\[]|\\.|\[(?:[^\]\\\n]|\\.)*\])+/[a-z]*")
  76. _JS_STRING = r"(?:\"(?:[^\"\\\n]|\\.)*\"|'(?:[^'\\\n]|\\.)*')"
  77. _REGEXP_CTOR_MATCHER = re.compile(
  78. r"\.(?:replace|replaceAll|split|match|matchAll|search)\(\s*new\s+RegExp\(\s*" + _JS_STRING
  79. + r"|\bnew\s+RegExp\(\s*" + _JS_STRING + r"(?=[^()\n]*\)\s*\.\s*(?:test|exec)\()")
  80. _MARKUP_RULES = frozenset({"script injection"})
  81. def _mask_regex_literals(source: str) -> str:
  82. masked = _REGEX_LITERAL.sub(lambda m: " " * len(m.group(0)), source)
  83. return _REGEXP_CTOR_MATCHER.sub(lambda m: " " * len(m.group(0)), masked)
  84. def desktop_surface_findings(source: str) -> list[tuple[str, int]]:
  85. """Return ``[(rule, line)]`` for every forbidden construct in a plugin.js source."""
  86. stripped = _strip_comments(source)
  87. no_regex = _mask_regex_literals(stripped)
  88. findings: list[tuple[str, int]] = []
  89. for rule, pattern in _FORBIDDEN:
  90. haystack = no_regex if rule in _MARKUP_RULES else stripped
  91. for match in pattern.finditer(haystack):
  92. findings.append((rule, haystack.count("\n", 0, match.start()) + 1))
  93. return sorted(findings, key=lambda f: f[1])
  94. def desktop_review_findings(source: str) -> list[tuple[str, int]]:
  95. """``[(cue, line)]`` for every review cue in a plugin.js source, skipping lines a refusal covers."""
  96. stripped = _strip_comments(source)
  97. refused = {line for _rule, line in desktop_surface_findings(source)}
  98. found = {(cue, stripped.count("\n", 0, m.start()) + 1) for cue, pattern in _REVIEW for m in pattern.finditer(stripped)}
  99. return sorted((hit for hit in found if hit[1] not in refused), key=lambda h: (h[1], h[0]))
  100. # The Desktop installer's entry rules (apps/desktop/electron/desktop-plugin-install.ts
  101. # ``findDesktopEntry``): a repo-root ``plugin.js`` wins and the whole repo root is published as the
  102. # plugin folder; otherwise ``desktop/plugin.js`` and its ``desktop/`` tree. Admission must lint every
  103. # layout the installer accepts, or a root-layout plugin ships to the renderer unlinted.
  104. _ROOT_ENTRY = "plugin.js"
  105. _DESKTOP_DIR = "desktop"
  106. def _has_root_entry(plugin_dir: Path) -> bool:
  107. return (plugin_dir / _ROOT_ENTRY).exists()
  108. def is_desktop_surface(rel_path: str, root_entry: bool = False) -> bool:
  109. """Whether a file is part of the Desktop surface this lint governs.
  110. That is the repo-root ``plugin.js`` (an installer entry on its own), JS under ``desktop/``, and,
  111. when the root entry exists (*root_entry*), the root-level JS published beside it. A Node sidecar
  112. (``sidecar/*.mjs``), a build script or a ``tests/*.test.mjs`` never runs in the renderer, so a
  113. lazy ``import('jszip')`` there is ordinary Node code — running the rules over every ``*.js`` /
  114. ``*.mjs`` in a repository reports noise, not a surface violation. Batch tooling should scope
  115. with this predicate (or call ``desktop_surface_hits``) instead of ``rglob``-ing the tree.
  116. """
  117. path = Path(rel_path)
  118. if path.suffix != ".js":
  119. return False
  120. parts = path.parts
  121. if len(parts) == 1:
  122. return parts[0] == _ROOT_ENTRY or root_entry
  123. return parts[0] == _DESKTOP_DIR
  124. def _desktop_surface_files(plugin_dir: Path) -> list[Path]:
  125. root_entry = _has_root_entry(plugin_dir)
  126. candidates = list(plugin_dir.glob("*.js"))
  127. desktop = plugin_dir / _DESKTOP_DIR
  128. if desktop.is_dir():
  129. candidates.extend(desktop.rglob("*.js"))
  130. return sorted(
  131. f for f in candidates
  132. if f.is_file() and is_desktop_surface(f.relative_to(plugin_dir).as_posix(), root_entry)
  133. )
  134. def desktop_surface_hits(plugin_dir: Path, findings=None) -> list[str]:
  135. """``["<rule> (<rel>:<line>)", ...]`` over the plugin's Desktop surface files only. *findings* is
  136. the per-source rule pass (``desktop_surface_findings`` refusals by default)."""
  137. plugin_dir = Path(plugin_dir)
  138. hits: list[str] = []
  139. for js in _desktop_surface_files(plugin_dir):
  140. rel = js.relative_to(plugin_dir).as_posix()
  141. try:
  142. source = js.read_text(encoding="utf-8-sig", errors="replace")
  143. except OSError:
  144. continue
  145. hits.extend(f"{rule} ({rel}:{line})" for rule, line in (findings or desktop_surface_findings)(source))
  146. return hits
  147. def check_desktop_surface(report, plugin_dir: Path) -> None:
  148. """Fail the report when the Desktop surface steps outside the SDK; silent when there is none."""
  149. plugin_dir = Path(plugin_dir)
  150. if not ((plugin_dir / _DESKTOP_DIR).is_dir() or _has_root_entry(plugin_dir)):
  151. return
  152. hits = desktop_surface_hits(plugin_dir)
  153. report.add(
  154. "desktop surface", not hits,
  155. "; ".join(hits[:8]) + (f" (+{len(hits) - 8} more)" if len(hits) > 8 else "")
  156. if hits else "stays inside the plugin SDK surface",
  157. )
  158. if cues := desktop_surface_hits(plugin_dir, desktop_review_findings):
  159. report.warn("desktop surface review (catalog rule 8: SDK surface only): " + "; ".join(cues[:8])
  160. + (f" (+{len(cues) - 8} more)" if len(cues) > 8 else "")
  161. + ". Use ctx.files / ctx.os / host.request and SDK slots, or open an issue for the hook you need.")