From 5cd013fd3bc636bdc6e2d13fcf8cdd1f9bc6e906 Mon Sep 17 00:00:00 2001 From: Albert Hsieh Date: Wed, 4 Nov 2026 10:09:24 +0800 Subject: [PATCH 1/2] fix(installer): prevent duplicate plugin registration --- install_plugin.py | 3 ++- tests/test_install_plugin.py | 47 +++++++++++++++++++++++++++++++++++- 2 files changed, 48 insertions(+), 2 deletions(-) diff --git a/install_plugin.py b/install_plugin.py index 3e11043..6c67217 100644 --- a/install_plugin.py +++ b/install_plugin.py @@ -2,6 +2,7 @@ import os import shutil import json +import re from pathlib import Path PLUGIN_CONFIG = { @@ -92,7 +93,7 @@ def update_plugins_js(target_dir): with open(plugins_js_path, "r", encoding="utf-8") as f: content = f.read() - if '"name":"DynamicTranslation"' in content: + if re.search(r'"name"\s*:\s*"DynamicTranslation"', content): print("DynamicTranslation is already in plugins.js. Skipping update.") return diff --git a/tests/test_install_plugin.py b/tests/test_install_plugin.py index 7d83d28..1bc6748 100644 --- a/tests/test_install_plugin.py +++ b/tests/test_install_plugin.py @@ -215,7 +215,7 @@ def test_adds_plugin_to_existing_list(self, tmp_path): def test_skips_when_plugin_already_registered(self, tmp_path, capsys): _make_rpg_project(tmp_path) - # Use compact format - install_plugin checks for '"name":"DynamicTranslation"' + # Keep support for the compact format emitted by RPG Maker. (tmp_path / "www" / "js").mkdir(parents=True, exist_ok=True) plugins_path = tmp_path / "www" / "js" / "plugins.js" plugins_path.write_text('[{"name":"DynamicTranslation","status":true}]', encoding="utf-8") @@ -229,6 +229,51 @@ def test_skips_when_plugin_already_registered(self, tmp_path, capsys): out = capsys.readouterr().out.lower() assert "skipping" in out + @pytest.mark.parametrize("indent", [None, 2]) + def test_skips_existing_registration_with_json_whitespace(self, tmp_path, indent): + _make_rpg_project(tmp_path) + plugins_path = tmp_path / "www" / "js" / "plugins.js" + existing = [{ + "name": "DynamicTranslation", + "status": False, + "parameters": {"Default Language": "ja"}, + }] + content = "var $plugins = " + json.dumps(existing, indent=indent) + ";\n" + plugins_path.write_text(content, encoding="utf-8") + + from install_plugin import update_plugins_js + + update_plugins_js(str(tmp_path / "www")) + + # Existing status, user parameters and formatting must stay untouched. + assert plugins_path.read_text(encoding="utf-8") == content + + @pytest.mark.parametrize("with_other_plugin", [False, True]) + def test_repeated_registration_is_idempotent(self, tmp_path, with_other_plugin): + _make_rpg_project(tmp_path) + existing = ( + [{"name": "OtherPlugin", "status": True}] if with_other_plugin else [] + ) + plugins_path = _make_plugins_js(tmp_path, existing) + plugins_path.write_text( + "var $plugins = " + plugins_path.read_text(encoding="utf-8") + ";\n", + encoding="utf-8", + ) + + from install_plugin import update_plugins_js + + update_plugins_js(str(tmp_path / "www")) + first_install = plugins_path.read_text(encoding="utf-8") + update_plugins_js(str(tmp_path / "www")) + second_install = plugins_path.read_text(encoding="utf-8") + + assert second_install == first_install + entries = json.loads( + second_install.removeprefix("var $plugins = ").rstrip(";\n") + ) + assert sum(entry["name"] == "DynamicTranslation" for entry in entries) == 1 + assert len(entries) == len(existing) + 1 + def test_handles_missing_plugins_js(self, tmp_path, capsys): _make_rpg_project(tmp_path) plugins_js = tmp_path / "www" / "js" / "plugins.js" From 5f9d20f8327bc0209ed7679689d3a7a0bb781c04 Mon Sep 17 00:00:00 2001 From: Albert Hsieh Date: Thu, 5 Nov 2026 08:05:35 +0800 Subject: [PATCH 2/2] fix(installer): parse actual plugin array before registration Bound registration lookup and insertion to the decoded JSON array, preserve comments and existing plugin settings, reject unsupported expressions without modifying plugins.js, and propagate parse failure to the CLI. Add 18 regression cases. Local Python 3.12.14 / pytest 9.1.1: 49 passed. Pre-fix negative control: 17 failed, 32 passed. Actual installer repeated twice and resulting authored plugins.js evaluated with Node 24.22.1 successfully. Local verification commit f8d287bb37ad7fabe39cc2348c2cdeab21af7cfc has the identical Git tree c5e58d5d6d46f6fc342ce957a0920c425672e668. --- README.md | 2 + docs/research/plugin-registration.md | 52 ++++++++++++ install_plugin.py | 51 ++++++++---- tests/test_install_plugin.py | 118 +++++++++++++++++++++++++++ 4 files changed, 207 insertions(+), 16 deletions(-) create mode 100644 docs/research/plugin-registration.md diff --git a/README.md b/README.md index 93a7419..0ac177f 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,8 @@ python3 install_plugin.py ../MyRPGProject * 更新 `js/plugins.js` 以啟用外掛。 * 自動搜尋專案根目錄下的 JSON 翻譯檔(如 `A翻譯.json`),並將其安裝為預設中文翻譯 (`translations/zh.json`)。 +自動註冊支援 RPG Maker 產生的 JSON 外掛清單,並保留前後的註解及既有外掛設定。若清單包含自訂 JavaScript 運算式、陣列內註解、尾端逗號或格式錯誤,腳本會保留 `plugins.js` 原文並以非零狀態結束;此外掛檔案可能已複製,請改用下方的手動註冊方式。 + ### 📦 手動安裝 如果您無法使用腳本,也可以手動安裝: diff --git a/docs/research/plugin-registration.md b/docs/research/plugin-registration.md new file mode 100644 index 0000000..8aefb46 --- /dev/null +++ b/docs/research/plugin-registration.md @@ -0,0 +1,52 @@ +# Safe plugin registration + +Checked 2026-11-04 against PR #5 head `5cd013fd3bc636bdc6e2d13fcf8cdd1f9bc6e906`. + +## Reproduction and decision + +The existing 31 installer tests pass. Two authored valid JavaScript fixtures fail: +`var $plugins = [];\n// documentation [optional]\n` is corrupted because the +installer inserts before the last `]` in the entire file. A leading comment +containing `{"name": "DynamicTranslation"}` prevents registration even though +the actual plugin array is empty. Nested parameter objects can likewise match +the whole-file registration regex. + +Use the existing Python standard library rather than add a JavaScript parser. +Recognize only an optional leading BOM/comments, followed by a bare JSON array +or `var`/`let`/`const $plugins =` and a JSON array. Decode that array and use the +returned end offset for insertion. Check names only on top-level plugin entries. +Require the array to end the assignment (only comments/whitespace before a +semicolon or EOF), so array-starting expressions such as `[].concat(...)` +cannot be mistaken for a supported JSON value. +Preserve the prefix/suffix and existing registrations. Unsupported or malformed +arrays are left unchanged, with a diagnostic; arbitrary JavaScript expressions, +comments within JSON arrays and JavaScript trailing commas are not supported. +The CLI exits nonzero on parse failure instead of claiming installation completed. +The plugin file has already been copied at that point; no rollback or fully +transactional installation is claimed. The existing missing-plugins.js warning +policy remains unchanged. + +## Upstream evidence + +Targeted connected GitHub search: `raw_decode` in `python/cpython`. Read +`JSONDecoder.raw_decode` in +[Lib/json/decoder.py](https://github.com/python/cpython/blob/3d6d2a63a23ee4d340ed8df6de0bd70ef175c4cf/Lib/json/decoder.py): +it returns the decoded object and the absolute document-end index, including +when other text follows. It raises JSONDecodeError when no document starts at +the supplied offset. This is precisely the array-boundary primitive needed; +calling `json.loads` on the entire JavaScript file would reject the assignment +and comments. A custom last-bracket scan remains incorrect for strings/comments. + +[CPython LICENSE](https://github.com/python/cpython/blob/3d6d2a63a23ee4d340ed8df6de0bd70ef175c4cf/LICENSE) +identifies the PSF License Version 2. The change directly uses the standard-library +API; no upstream implementation is copied or vendored. The repository currently +declares ISC in package.json and has no root license file, so this note does not +assert additional distribution rights for unrelated project files. + +## Validation + +Run the complete Python installer suite, regression negative controls against +the pre-fix implementation, Python syntax compilation, Node syntax checks, and +an actual installer subprocess followed by Node evaluation of the authored +plugin list. Existing Jest coverage is separate from a real RPG Maker runtime; +no game, paid translation API, or real user content is accessed. diff --git a/install_plugin.py b/install_plugin.py index 6c67217..245b863 100644 --- a/install_plugin.py +++ b/install_plugin.py @@ -90,31 +90,46 @@ def update_plugins_js(target_dir): return print("Updating plugins.js...") - with open(plugins_js_path, "r", encoding="utf-8") as f: + with open(plugins_js_path, "r", encoding="utf-8", newline="") as f: content = f.read() - if re.search(r'"name"\s*:\s*"DynamicTranslation"', content): + # RPG Maker emits a JSON array after an assignment and optional comments. + # Parse that array, not brackets or name-like text in comments/parameters. + trivia_pattern = r'(?:\s+|//[^\r\n]*(?:\r\n?|\n|$)|/\*.*?\*/)*' + prefix_match = re.match( + r'\A\ufeff?' + trivia_pattern + + r'(?:(?:var|let|const)\s+\$plugins\s*=\s*)?', + content, + re.DOTALL, + ) + array_start = prefix_match.end() + try: + if content[array_start:array_start + 1] != "[": + raise ValueError("expected a JSON plugin array") + plugins, array_end = json.JSONDecoder().raw_decode(content, array_start) + if not all(isinstance(plugin, dict) for plugin in plugins): + raise ValueError("plugin entries must be objects") + suffix = content[array_end:] + trivia_end = re.match(trivia_pattern, suffix, re.DOTALL).end() + if suffix[trivia_end:] and suffix[trivia_end] != ";": + raise ValueError("expected the JSON array to end the assignment") + except (ValueError, RecursionError) as error: + print(f"Error: Could not parse plugins.js ({error}). File left unchanged.") + return False + + if any(plugin.get("name") == "DynamicTranslation" for plugin in plugins): print("DynamicTranslation is already in plugins.js. Skipping update.") return plugin_string = json.dumps(PLUGIN_CONFIG, ensure_ascii=False) - # Find the last closing bracket - last_bracket_index = content.rfind("]") - if last_bracket_index == -1: - print("Error: Could not parse plugins.js (could not find closing bracket).") - return - - before_bracket = content[:last_bracket_index].rstrip() - after_bracket = content[last_bracket_index:] - - # Check if we need a comma: if before_bracket not empty and last char != '[' - needs_comma = bool(before_bracket) and before_bracket[-1] != "[" - prefix = ", " if needs_comma else "" + before_bracket = content[:array_end - 1].rstrip() + after_bracket = content[array_end - 1:] + prefix = ", " if plugins else "" new_content = f"{before_bracket}\n{prefix}{plugin_string}\n{after_bracket}" - with open(plugins_js_path, "w", encoding="utf-8") as f: + with open(plugins_js_path, "w", encoding="utf-8", newline="") as f: f.write(new_content) print("plugins.js updated successfully.") @@ -166,7 +181,11 @@ def main(): print(f"Target directory: {target_dir}") copy_plugin_file(script_dir, www_dir) - update_plugins_js(www_dir) + if update_plugins_js(www_dir) is False: + raise SystemExit( + "Registration failed; plugins.js was not changed. " + "Use RPG Maker's Plugin Manager for manual registration." + ) install_translation(target_dir, www_dir) print("Installation complete!") diff --git a/tests/test_install_plugin.py b/tests/test_install_plugin.py index 1bc6748..8610518 100644 --- a/tests/test_install_plugin.py +++ b/tests/test_install_plugin.py @@ -286,6 +286,124 @@ def test_handles_missing_plugins_js(self, tmp_path, capsys): out = capsys.readouterr().out assert "Warning" in out + @pytest.mark.parametrize("suffix", [ + ";\n// documentation [optional]\n", + ";\n/* preserve [this] comment */\n", + ';\nconst audit = ["preserved"];\n', + ' /* preserve comment before semicolon */;\n', + ]) + def test_inserts_into_plugin_array_not_trailing_brackets(self, tmp_path, suffix): + _make_rpg_project(tmp_path) + plugins_path = _make_plugins_js(tmp_path) + prefix = "// Generated by RPG Maker.\nvar $plugins =\n" + plugins_path.write_text(prefix + "[]" + suffix, encoding="utf-8") + + from install_plugin import PLUGIN_CONFIG, update_plugins_js + + update_plugins_js(str(tmp_path / "www")) + content = plugins_path.read_text(encoding="utf-8") + entries, end = json.JSONDecoder().raw_decode(content, len(prefix)) + assert entries == [PLUGIN_CONFIG] + assert content[end:] == suffix + update_plugins_js(str(tmp_path / "www")) + assert plugins_path.read_text(encoding="utf-8") == content + + @pytest.mark.parametrize("comment", [ + '// removed {"name": "DynamicTranslation"}\n', + '/* removed {"name": "DynamicTranslation"} */\n', + ]) + def test_name_in_leading_comment_is_not_registration(self, tmp_path, comment): + _make_rpg_project(tmp_path) + plugins_path = _make_plugins_js(tmp_path) + prefix = comment + "var $plugins = " + plugins_path.write_text(prefix + "[];\n", encoding="utf-8") + + from install_plugin import update_plugins_js + + update_plugins_js(str(tmp_path / "www")) + content = plugins_path.read_text(encoding="utf-8") + assert content.startswith(prefix) + entries, _ = json.JSONDecoder().raw_decode(content, len(prefix)) + assert [entry["name"] for entry in entries] == ["DynamicTranslation"] + + def test_nested_name_is_not_registration(self, tmp_path): + _make_rpg_project(tmp_path) + other = {"name": "OtherPlugin", "parameters": {"name": "DynamicTranslation"}} + plugins_path = _make_plugins_js(tmp_path, [other]) + + from install_plugin import update_plugins_js + + update_plugins_js(str(tmp_path / "www")) + entries = json.loads(plugins_path.read_text(encoding="utf-8")) + assert entries[0] == other + assert [entry["name"] for entry in entries] == ["OtherPlugin", "DynamicTranslation"] + + def test_escaped_existing_name_preserves_registration(self, tmp_path): + _make_rpg_project(tmp_path) + plugins_path = _make_plugins_js(tmp_path) + content = r'var $plugins = [{"name":"Dynamic\u0054ranslation","status":false}];' + plugins_path.write_text(content, encoding="utf-8") + + from install_plugin import update_plugins_js + + update_plugins_js(str(tmp_path / "www")) + assert plugins_path.read_text(encoding="utf-8") == content + + @pytest.mark.parametrize("content", [ + 'var $plugins = [{"name": "OtherPlugin"}; // ]\n', + 'var $plugins = [null];\n', + 'var $plugins = [{"name": "OtherPlugin"},];\n', + 'var unrelated = [];\n', + 'var $plugins = loadPlugins(); // []\n', + 'var $plugins = [].concat([]);\n', + 'var $plugins = []\n.concat([]);\n', + 'var $plugins = [{"name":"OtherPlugin"}][0];\n', + ]) + def test_unsupported_or_malformed_list_is_unchanged(self, tmp_path, capsys, content): + _make_rpg_project(tmp_path) + plugins_path = _make_plugins_js(tmp_path) + plugins_path.write_text(content, encoding="utf-8") + + from install_plugin import update_plugins_js + + assert update_plugins_js(str(tmp_path / "www")) is False + assert plugins_path.read_text(encoding="utf-8") == content + assert "Error:" in capsys.readouterr().out + + def test_cli_reports_registration_failure_without_claiming_completion(self, tmp_path): + _make_rpg_project(tmp_path) + plugins_path = _make_plugins_js(tmp_path) + content = 'var $plugins = loadPlugins(); // []\n' + plugins_path.write_text(content, encoding="utf-8") + + result = subprocess.run( + [sys.executable, str(PROJECT_ROOT / "install_plugin.py"), str(tmp_path)], + capture_output=True, + text=True, + encoding="utf-8", + ) + + assert result.returncode != 0 + assert "Registration failed" in result.stderr + assert "Installation complete" not in result.stdout + assert plugins_path.read_text(encoding="utf-8") == content + + def test_bom_and_crlf_are_preserved(self, tmp_path): + _make_rpg_project(tmp_path) + plugins_path = _make_plugins_js(tmp_path) + prefix = "\ufeff// generated\r\nvar $plugins = " + suffix = ";\r\n// [optional]\r\n" + plugins_path.write_bytes((prefix + "[]" + suffix).encode("utf-8")) + + from install_plugin import update_plugins_js + + update_plugins_js(str(tmp_path / "www")) + content = plugins_path.read_bytes().decode("utf-8") + assert content.startswith(prefix) + entries, end = json.JSONDecoder().raw_decode(content, len(prefix)) + assert len(entries) == 1 + assert content[end:] == suffix + class TestInstallTranslation: """Tests for install_translation()."""