The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(plugins): drop the prototype-patching rule from the Desktop surface lint
Teknium098365431981
diff --git a/hermes_cli/plugin_validate_desktop.py b/hermes_cli/plugin_validate_desktop.pyindex e57db92ab9f..4fd3911e377 100644--- a/hermes_cli/plugin_validate_desktop.py+++ b/hermes_cli/plugin_validate_desktop.py@@ -14,14 +14,10 @@ from pathlib import Pathfrom typing import List, Tuple# (rule, regex) applied to comment-stripped source; every hit fails the "desktop surface" check.-# ``X.prototype.y =`` is checked separately (``_foreign_prototype_writes``): it passes only where ``X``-# is provably the file's own class/function, because a bundled library setting fields on its own-# classes (three.js: ``Vector2.prototype.isVector2 = true``) is not reaching into the renderer.+# Prototype writes are not linted: bundled libraries (three.js) set fields on their own classes, and+# no regex could tell those from patching a renderer global without misfiring on minified names.+# Catalog review reads them by hand._FORBIDDEN: tuple[tuple[str, re.Pattern[str]], ...] = (- ("prototype patching",- re.compile(r"\bObject\.definePropert(?:y|ies)\(\s*[\w$.]+\.prototype\b")),- ("prototype patching",- re.compile(r"\b(?:Reflect|Object)\.setPrototypeOf\(|\.__proto__\s*=")),("dynamic code evaluation",re.compile(r"(?<![\w$.])eval\(|\bnew\s+Function\(")),("dynamic import outside the SDK",@@ -80,201 +76,11 @@ def _mask_regex_literals(source: str) -> str:return _REGEXP_CTOR_MATCHER.sub(lambda m: " " * len(m.group(0)), masked)-_PROTOTYPE_WRITE = re.compile(r"\b([A-Za-z_$][\w$]*)\.prototype\.[\w$]+\s*=[^=]")-_RENDERER_GLOBAL_NAMES = (- r"Object|Function|Array|String|Number|Boolean|Symbol|Promise|RegExp|Date|Error|JSON|Map|Set"- r"|WeakMap|WeakSet|Proxy|Reflect|Storage|Window|Document|Node|EventTarget|Event|Location|History"- r"|Navigator|WebSocket|XMLHttpRequest|Request|Response|Headers|URL|Blob|File|FileReader"- r"|MutationObserver|Worker|BroadcastChannel|MessagePort|IDB\w*|\w*Element|\w*Event|CSS\w*")-# A regex cannot see scope, so a same-named local declaration elsewhere in the file must not excuse-# a write to a renderer global: these receivers always fail, declared or not.-_RENDERER_GLOBAL = re.compile(rf"^(?:{_RENDERER_GLOBAL_NAMES})$")-# A regex cannot see scope, and minifiers reuse one-letter names (three.js minified is-# ``class s{constructor(){s.prototype.isVector2=!0}}`` beside a dozen unrelated ``s=`` locals), so-# file-wide name checks cannot decide. The write passes only where ``X`` provably IS the class:-# inside the body of ``class X``/``function X``, or after such a declaration statement in the same-# block, with nothing rebinding ``X`` in between. ``window["Storage"]``, ``(0, window.Storage)`` and every-# other aliasing spelling then fail by default, wherever an unrelated ``class X`` lives.-_OWN_DECLARATION = r"(?:\bclass\s+{0}\b[^{{]*|\bfunction\s*\*?\s*{0}\s*\([^)]*\)\s*)\{{"-# ``var X = class {...}`` / ``X = function () {...}``: what bundlers emit; binds ``X`` in its block.-_ASSIGNED_DECLARATION = (r"(?<![\w$.]){0}\s*=\s*(?:class\b[^{{]*|function\s*\*?\s*[\w$]*\s*\([^)]*\)\s*)\{{")-# What can make ``X`` name something else, read liberally (a false hit only refuses a bundle for-# review; a miss would excuse a renderer patch): any assignment operator on ``X``; a declaration;-# ``X`` inside a destructuring pattern that is assigned or iterated (``({X} = o)``, ``for ([X] of-# a)``); a parameter (function, method, arrow, catch); ``for (X of/in …)``; an import binding.-# A reference (``register(X)``, ``[X, Y]``, ``{ Array: X }``) is not a binding.-_REBINDING = (- r"(?<![\w$.]){0}\s*(?:&&|\|\||\?\?|\*\*|<<|>>>?|[-+*/%&|^])?=(?![=>])"- r"|\b(?:let|const|var|class|function\s*\*?)\s+{0}(?![\w$])"- # a PATTERN opens where an expression cannot (not ``obj[`` / ``f()[``), names ``X`` itself as a- # target (not ``X.name``, not the key in ``{X: other}``), and is assigned or iterated- r"|(?:^|(?<=[;(,{{}}=?:&|!\n])|\b(?:let|const|var|return|yield|void))\s*[\[{{][^;=()]*?(?<![\w$.]){0}(?![\w$.]|\s*:)[^;=()]*?[}}\]][\s}}\]]*"- r"(?:=(?![=>])|\b(?:of|in)\b)"- r"|(?:\bfunction\s*\*?\s*[\w$]*|(?<![\w$.])(?!(?:if|for|while|switch|with|return|typeof|await)\b)[\w$]+)"- r"\s*\([^()]*?(?<![\w$.]){0}(?![\w$])[^()]*\)\s*\{{"- r"|\(([^()]*?(?<![\w$.]){0}(?![\w$])[^()]*)\)\s*=>|(?<![\w$.]){0}\s*=>"- r"|\bcatch\s*\([^)]*(?<![\w$.]){0}(?![\w$])"- r"|(?<![\w$.]){0}\s+(?:of|in)\b|\bas\s+{0}(?![\w$])|\bimport\s+{0}(?![\w$])")---_REGEX_AFTER_WORD = re.compile(r"(?:^|[^\w$.])(?:return|typeof|case|do|else|in|of|void|delete|throw|new|yield|await)\s*$")-_MAX_READINGS = 32---def _slash_readings(source: str, at: int) -> tuple[bool, bool]:- """(may be a regex, may be division) for the ``/`` at *at* in code. After ``)`` or ``}`` both- are legal JavaScript (``if (x) /re/.test(s)`` vs ``(a) / b``); only a parser could tell."""- if source.startswith("/", at + 1):- return False, True- j = at - 1- while j >= 0 and source[j] in " \t\r\n":- j -= 1- if j < 0:- return True, False- prev = source[j]- if prev in ")}":- return True, True- if prev in "+-" and j > 0 and source[j - 1] == prev: # ``a++ / b``- return False, True- if prev in "(,=:[!&|?{;+-*%<>~^":- return True, False- keyword = _REGEX_AFTER_WORD.search(source, max(0, j - 12), j + 1)- if keyword: # an expression must follow ``return`` etc.; ``of`` may also be a plain name- return True, source[j - 1:j + 1] == "of"- return False, True---def _step(source: str, i: int, state: tuple) -> tuple[bool, list[tuple]]:- """Advance one reading of the source by the character at *i*: (is that character literal text,- next readings). An empty list means this reading is not valid JavaScript (it dies)."""- kind, holes = state- c = source[i]- if kind in ("\"", "'"):- if c == "\\":- return True, [(kind + "\\", holes)]- if c == "\n":- return True, []- return c != kind, [("c" if c == kind else kind, holes)]- if kind in ("\"\\", "'\\", "t\\", "r\\", "k\\"):- return True, [(kind[0], holes)]- if kind == "t":- if c == "\\":- return True, [("t\\", holes)]- if c == "`":- return False, [("c", holes)]- if c == "$" and source.startswith("${", i):- return True, [("$", holes + (0,))]- return True, [("t", holes)]- if kind == "$": # the ``{`` of ``${``- return True, [("c", holes)]- if kind in ("r", "k"):- if c == "\n":- return True, []- if c == "\\":- return True, [(kind + "\\", holes)]- if kind == "r" and c == "/":- return False, [("c", holes)]- nxt = {"[": "k"} if kind == "r" else {"]": "r"}- return True, [(nxt.get(c, kind), holes)]- # code- if c in "\"'":- return False, [(c, holes)]- if c == "`":- return False, [("t", holes)]- if c == "/":- regex, division = _slash_readings(source, i)- return False, ([("r", holes)] if regex else []) + ([("c", holes)] if division else [])- if holes and c == "{":- return False, [("c", holes[:-1] + (holes[-1] + 1,))]- if holes and c == "}":- if holes[-1] == 0:- return True, [("t", holes[:-1])]- return False, [("c", holes[:-1] + (holes[-1] - 1,))]- return False, [("c", holes)]---def _code_view(source: str) -> str:- """*source* with the text of quoted strings, template literals and regex literals blanked, same- length; a template's ``${…}`` stays code. Where a ``/`` could be either a regex or division,- BOTH readings are followed, and a character is blanked only when every live reading agrees it- is literal text. Since the true reading is always among them, executable code is never blanked- (a wrong guess cannot hide a patch); ambiguity only costs a refusal for manual review."""- out = list(source)- readings: set[tuple] = {("c", ())}- for i in range(len(source)):- literal_everywhere = True- nxt: set[tuple] = set()- for state in readings:- literal, follow = _step(source, i, state)- literal_everywhere &= literal- nxt.update(follow)- if literal_everywhere and source[i] != "\n":- out[i] = " "- if not nxt or len(nxt) > _MAX_READINGS: # beyond what we can follow: blank nothing more- break- readings = nxt- return "".join(out)---def _brace_pairs(code: str) -> dict[int, int]:- """``{`` offset -> matching ``}`` offset in *code* (a :func:`_code_view`)."""- pairs: dict[int, int] = {}- stack: list[int] = []- for i, ch in enumerate(code):- if ch == "{":- stack.append(i)- elif ch == "}" and stack:- pairs[stack.pop()] = i- return pairs---def _enclosing_block_end(pairs: dict[int, int], at: int, size: int) -> int:- """End of the innermost ``{...}`` containing *at* (``size`` at top level)."""- ends = [close for open_, close in pairs.items() if open_ < at < close]- return min(ends) if ends else size---def _own_class_write(source: str, name: str, at: int, pairs: dict[int, int]) -> bool:- """The write is inside ``X``'s own body (any declaration form), or follows a ``class X`` /- ``function X`` STATEMENT in the same block; either way with no rebinding of ``X`` in between."""- escaped = re.escape(name)- rebinding = re.compile(_REBINDING.format(escaped))- named = re.compile(_OWN_DECLARATION.format(escaped))- assigned = re.compile(_ASSIGNED_DECLARATION.format(escaped))- decls = sorted([(d, False) for d in named.finditer(source, 0, at)] + [(d, True) for d in assigned.finditer(source, 0, at)],- key=lambda item: item[0].start())- for decl, is_assignment in decls:- body = decl.end() - 1- close = pairs.get(body, -1)- if close > at:- if not rebinding.search(source, body + 1, at):- return True- continue- # A class EXPRESSION's own name is visible only in its body; a statement or ``X = class``- # binds ``X`` for the rest of its block.- statement = is_assignment or not re.search(- r"[=(,:?&|]\s*$|\breturn\s*$", source[max(0, decl.start() - 20):decl.start()])- if (statement and close != -1 and _enclosing_block_end(pairs, decl.start(), len(source)) > at- and not rebinding.search(source, close + 1, at)):- return True- return False---def _foreign_prototype_writes(source: str) -> list[int]:- """Offsets of ``X.prototype.y =`` that are not provably on ``X``'s own class (see above)."""- code = _code_view(source) # offsets unchanged; string/template text never reads as code- writes = [(m.start(), m.group(1)) for m in _PROTOTYPE_WRITE.finditer(code)]- pairs = _brace_pairs(code) if writes else {}- return [at for at, name in writes- if _RENDERER_GLOBAL.match(name) or not _own_class_write(code, name, at, pairs)]--def desktop_surface_findings(source: str) -> list[tuple[str, int]]:"""Return ``[(rule, line)]`` for every forbidden construct in a plugin.js source."""stripped = _strip_comments(source)no_regex = _mask_regex_literals(stripped)- findings = [("prototype patching", stripped.count("\n", 0, at) + 1)- for at in _foreign_prototype_writes(stripped)]+ findings: list[tuple[str, int]] = []for rule, pattern in _FORBIDDEN:haystack = no_regex if rule in _MARKUP_RULES else strippedfor match in pattern.finditer(haystack):diff --git a/plugin-catalog/README.md b/plugin-catalog/README.mdindex 2c7fbe30d1b..19a91c72fae 100644--- a/plugin-catalog/README.md+++ b/plugin-catalog/README.md@@ -49,8 +49,9 @@ meaningful:in the Desktop renderer with the app's full authority (the loader isolateserrors, not capabilities), so a listed one may only use the plugin SDK:no prototype patching of renderer or browser objects (`Storage.prototype.y =`,- `Object.defineProperty(...prototype`); a bundled library setting fields on- classes it declares itself (three.js and the like) is fine,+ `Object.defineProperty(...prototype`), which reviewers check by hand (the+ lint does not); a bundled library setting fields on classes it declares+ itself (three.js and the like) is fine,no `eval`/`new Function`, no `import()` of anything but `@hermes/plugin-sdk`/ `react` (app bundle chunks, blob or http URLs included), no script-taginjection, no reaching into the app's internal stores or its own markupdiff --git a/tests/hermes_cli/test_plugin_validate.py b/tests/hermes_cli/test_plugin_validate.pyindex 3f25a32a8bc..7ab96bf8b9d 100644--- a/tests/hermes_cli/test_plugin_validate.py+++ b/tests/hermes_cli/test_plugin_validate.py@@ -271,7 +271,8 @@ class TestRequiresHermesSpec:class TestDesktopSurface:"""Catalog-listed desktop plugins must stay inside the SDK surface: the renderer loader gives- plugin.js full app authority, so prototype patching / app-chunk imports are refused at admission."""+ plugin.js full app authority, so app-chunk imports and the like are refused at admission. Prototype+ writes are not linted (review reads them by hand): a bundled library's own classes look the same."""def _desktop_plugin(self, tmp_path, js: str) -> Path:d = tmp_path / "desk"@@ -327,10 +328,9 @@ class TestDesktopSurface:assert desktop_surface_hits(d) == ["app DOM reach (desktop/plugin.js:2)","app DOM reach (desktop/plugin.js:3)",- "prototype patching (desktop/plugin.js:4)",]- def test_prototype_patch_and_chunk_import_fail(self, tmp_path):+ def test_chunk_import_fails_and_prototype_writes_are_left_to_review(self, tmp_path):d = self._desktop_plugin(tmp_path, ("const raw = Storage.prototype.setItem\n""Storage.prototype.setItem = function (k, v) { return raw.call(this, k, v) }\n"@@ -340,65 +340,10 @@ class TestDesktopSurface:report = validate_plugin_dir(d)failed = {name: detail for name, ok, detail in report.checks if not ok}assert "desktop surface" in failed- assert "prototype patching (desktop/plugin.js:2)" in failed["desktop surface"]+ assert "prototype patching" not in failed["desktop surface"]assert "dynamic import outside the SDK (desktop/plugin.js:3)" in failed["desktop surface"]assert ":4)" not in failed["desktop surface"]- def test_bundled_library_own_class_prototypes_pass_but_renderer_globals_still_fail(self, tmp_path):- """A bundled library setting fields on classes it declares (three.js: ``var Vector2 = class- _Vector2 { constructor() { _Vector2.prototype.isVector2 = true } }``, ``function Track(){}``)- is not prototype patching. A write to a renderer global or an undeclared receiver still is,- including a global the file shadows with a same-named class elsewhere, and an alias of a- global (any spelling: assigned, bracketed, destructured) whose name some unrelated scope- also declares as a class, including a minifier-reused one-letter name, and a parameter- shadowing the class, a destructuring assignment, and writes hidden in a template ``${}`` or- between divisions. Passing the class around (``register(Q)``, ``{ Array: Q }``,- ``registry[F.name] = F``) or text in a string, template or regex literal is not a- rebinding, nor is a class name used only as a destructuring key. Ambiguous text never hides- code: where a ``/`` could open a regex or be division, both readings are followed."""- d = self._desktop_plugin(tmp_path, (- "var Vector2 = class _Vector2 { constructor() { _Vector2.prototype.isVector2 = true } }\n"- "function Track() {}\nTrack.prototype.ValueTypeName = 'vector'\n"- "const S = window.Storage\nS.prototype.setItem = noop\n"- "class Storage {}\nStorage.prototype.setItem = noop\n"- "HTMLElement.prototype.click = spy\n"- "function unused() { class H {} }\nconst H = window.Storage\nH.prototype.setItem = noop\n"- "function K() {}\nK.prototype.ValueTypeName = 'v'\nconst types = { Array: K }\n"- "function unused2() { class W {} }\nconst { Storage: W } = window\nW.prototype.setItem = noop\n"- "function unused3() { class B {} }\nconst B = window['Storage']\nB.prototype.setItem = noop\n"- "var Mv=class s{constructor(){s.prototype.isMv=!0}};var s=window.Storage;s.prototype.setItem=noop\n"- "function Q() {}\nregister(Q); const label = \"Q = vector\"\nQ.prototype.ValueTypeName = 'v'\n"- "function R() {}\nfunction patch(R) { R.prototype.setItem = noop }\n"- "function D() {}\n({D} = {D: window.Storage}); D.prototype.setItem = spy\n"- "const label = `${Storage.prototype.setItem = spy}`\n"- "const n = 1 / (Storage.prototype.setItem = spy, 2) / 3\n"- "function E() {}\nconst re = /E = x/, t = `E = ${1}`; E.prototype.isE = 1\n"- "function F() {}\nregistry[F.name] = F; F.prototype.isF = 1\n"- "function G() {}\nlet {a: G} = window; G.prototype.setItem = spy\n"- "function J() {}\ntrue ? [J] = [window.Storage] : null; J.prototype.setItem = spy\n"- "const m = Number(\"if (\") / (Storage.prototype.setItem = spy, 2) / 3\n"- "if (false) /\"/.test(label); Storage.prototype.setItem = spy; const tail = \"/\"\n"- "function L() {}\nlet v; true ? {L: v} = options : null; L.prototype.isL = 1\n"- "function U() {}\nfunction matcher() { return /U = vector/ } U.prototype.isU = 1\n"- ))- assert desktop_surface_hits(d) == [- "prototype patching (desktop/plugin.js:5)",- "prototype patching (desktop/plugin.js:7)",- "prototype patching (desktop/plugin.js:8)",- "prototype patching (desktop/plugin.js:11)",- "prototype patching (desktop/plugin.js:17)",- "prototype patching (desktop/plugin.js:20)",- "prototype patching (desktop/plugin.js:21)",- "prototype patching (desktop/plugin.js:26)",- "prototype patching (desktop/plugin.js:28)",- "prototype patching (desktop/plugin.js:29)",- "prototype patching (desktop/plugin.js:30)",- "prototype patching (desktop/plugin.js:36)",- "prototype patching (desktop/plugin.js:38)",- "prototype patching (desktop/plugin.js:39)",- "prototype patching (desktop/plugin.js:40)",- ]-def test_node_sidecar_and_test_mjs_outside_desktop_are_not_the_surface(self, tmp_path):"""A tools plugin with a Node sidecar (``sidecar/*.mjs`` lazily importing a lockfile-pinneddependency) and ``tests/*.test.mjs`` has no Desktop surface: the lint stays silent, and thediff --git a/website/docs/developer-guide/plugins/catalog-submission.md b/website/docs/developer-guide/plugins/catalog-submission.mdindex 942bea6d4f9..ab145ca0ef5 100644--- a/website/docs/developer-guide/plugins/catalog-submission.md+++ b/website/docs/developer-guide/plugins/catalog-submission.md@@ -107,8 +107,9 @@ the gallery. There is no separate listing to maintain.in the Desktop renderer with the app's full authority (the loader isolateserrors, not capabilities), so a listed one may only use the plugin SDK:no prototype patching of renderer or browser objects (`Storage.prototype.y =`,- `Object.defineProperty(...prototype`); a bundled library setting fields on- classes it declares itself (three.js and the like) is fine,+ `Object.defineProperty(...prototype`), which reviewers check by hand (the+ lint does not); a bundled library setting fields on classes it declares+ itself (three.js and the like) is fine,no `eval`/`new Function`, no `import()` of anything but `@hermes/plugin-sdk`/ `react` (app bundle chunks, blob or http URLs included), no script-taginjection, no reaching into the app's internal stores or its own markupdiff --git a/website/docs/user-guide/features/plugin-catalog.md b/website/docs/user-guide/features/plugin-catalog.mdindex 6680c136fe5..ee2a8bd161a 100644--- a/website/docs/user-guide/features/plugin-catalog.md+++ b/website/docs/user-guide/features/plugin-catalog.md@@ -88,8 +88,8 @@ The catalog is designed so you know exactly what you're installing:bridge, storage of other plugins). What protects you is the trust modelabove — a human read the exact pinned commit, and the install is thatcommit — plus two tripwires: admission's `desktop surface` lint refuses- the obvious moves outside the plugin SDK (patching built-in prototypes,- `eval`, importing anything other than `@hermes/plugin-sdk`/`react`,+ the obvious moves outside the plugin SDK (`eval`, importing anything+ other than `@hermes/plugin-sdk`/`react`,including remote scripts), and the app's loader refuses every non-SDKimport again at load time. The lint reads a `<script` regex — a literal, orthe pattern string of a `new RegExp(...)` passed straight to