Merge pull request #429 from dikeckaan/luci-lexical-translator

LuCI: keep translations when a browser extension overwrites window._
This commit is contained in:
KAAN DIKEC authored and GitHub committed 2026-10-29 02:46:45 +03:00
commit 7f6928ef55
5 files changed
+121 -3

No files matched your search

+4 -1
View File
@@ -115,7 +115,8 @@ if [ "$SYSTEM" = openwrt-luci ]; then
[ -s "$CAT/mu300.tr.lmo" ] || { echo "no Turkish catalog built from openwrt/luci-app-mu300/po/tr" >&2; exit 1; }
[ -s "$CAT/mu300.zh-cn.lmo" ] || { echo "no Chinese catalog built from openwrt/luci-app-mu300/po/zh_Hans" >&2; exit 1; }
set -- -v "$THEME_APK:/in/luci-theme-aurora.apk:ro" -v "$TOP/openwrt/luci-app-mu300:/in/luci-plugin:ro" \
-v "$TOP/openwrt/luci-overlay:/in/luci-overlay:ro" -v "$CAT:/in/catalogs:ro"
-v "$TOP/openwrt/luci-overlay:/in/luci-overlay:ro" -v "$CAT:/in/catalogs:ro" \
-v "$TOP/openwrt/patches/luci-lexical-translator.sh:/in/luci-lexical-translator.sh:ro"
fi
TARBALL=$FLAVOUR-$VER-armsr-armv8-rootfs.tar.gz
URL=$BASEURL/$VER/targets/armsr/armv8
@@ -300,6 +301,8 @@ if [ -d /in/luci-plugin ]; then
[ -d /in/luci-overlay ] && cp -a /in/luci-overlay/. $R/
cp -a /in/luci-plugin/root/. $R/
cp -a /in/luci-plugin/htdocs/. $R/www/
# the views keep their translations when a browser extension puts Lodash on window._ (issue #376)
sh /in/luci-lexical-translator.sh $R/www/luci-static/resources/luci.js
chmod 0755 $R/etc/init.d/unisoc-modem-ui $R/etc/hotplug.d/net/90-unisoc-usb-host $R/etc/hotplug.d/iface/90-unisoc-usb-host $R/usr/libexec/rpcd/mu300dash $R/usr/libexec/rpcd/mu300vpn $R/usr/libexec/unisoc-modem/*
chmod 0755 $R/usr/libexec/rpcd/mu300term $R/usr/libexec/mu300-terminal-login $R/etc/hotplug.d/iface/95-mu300-terminal
# the terminal is System > Terminal (the panel menu: the page, and the settings page of luci-app-ttyd); its own Services >
+26
View File
@@ -0,0 +1,26 @@
#!/bin/sh
# luci-lexical-translator.sh LUCI_JS: give LuCI's own scope a translator `_` of its own (issue #376).
#
# LuCI compiles every view and class with a direct eval() inside luci.js's outer function, so the `_()` they call
# is looked up there first and, finding nothing, in the page's globals: cbi.js's `function _`. A browser extension
# that puts Lodash (or anything else) on window._ then breaks the pages: `_(...).format is not a function`, or a
# '[data-tab=""Actions""]' selector. A `const _` at the top of that outer function is found first, and is the same
# lookup as cbi.js's: the trimmed string (with its context and \u0001 before it), hashed with sfh(), in window.TR,
# else the string itself. window._ stays whatever the page or the extension made it.
#
# Idempotent; the build fails when luci.js no longer starts the way this expects (a LuCI update to check by hand).
set -eu
f=${1:?usage: luci-lexical-translator.sh LUCI_JS}
MARK='/*mu300: lexical translator, issue #376*/'
grep -qF "$MARK" "$f" && exit 0
HEAD="((window,document,undefined)=>{'use strict';"
[ "$(grep -cF "$HEAD" "$f")" = 1 ] || { echo "luci-lexical-translator: $f does not start as expected" >&2; exit 1; }
CODE="$MARK"'const _=(s,c)=>{if(!window.TR||typeof sfh!="function"||typeof trimws!="function")return s;const k=(c!=null?trimws(c)+"\u0001":"")+trimws(s);return window.TR[sfh(k)]||s;};'
HEAD=$HEAD CODE=$CODE awk '
!done && (i = index($0, ENVIRON["HEAD"])) {
j = i + length(ENVIRON["HEAD"])
$0 = substr($0, 1, j - 1) ENVIRON["CODE"] substr($0, j); done = 1
}
{ print }' "$f" > "$f.new"
grep -qF "$MARK" "$f.new" || { rm -f "$f.new"; echo "luci-lexical-translator: not applied" >&2; exit 1; }
cat "$f.new" > "$f" && rm -f "$f.new"
+1
View File
@@ -48,6 +48,7 @@ macOS and Windows (`.github/workflows/tests.yml`).
| `test_ttl.py` | `mu300-ttl` with fake `uci`/`fw4`/`tc`/`modprobe`: the nft backend (no `act_pedit`) turns OpenWrt's flow offloading off while a TTL is set (also at boot), back on after `off`, untouched without fw4 (Ubuntu); the tc backend (`TtlTc`) puts matchall/pedit filters on every sipa_eth*, idempotently, leaves offloading alone, falls back to nft when tc fails, and `off` removes both |
| `test_zram.py` | `mu300-zram` (FINDINGS 162) on a fake `/sys/block/zram0` and `/proc`: the defaults (half the RAM, lz4, priority 100, swappiness 100), every setting in `zram.conf`, a compressor the kernel lacks, bad values, switched off, already on, `on`/`off`, a failed swapoff, `status`; the boot wiring on every image, no second zram setup, the kernels' zram options |
| `test_luci_i18n.py` | the control panel's catalogs: every `po/<lang>` complete and in the language table, CJK only in catalogs; the pages (the Languages page too) under Node; the Packages after an update page (Repair DNS only after its confirmation) |
| `test_luci_translator.py` | `openwrt/patches/luci-lexical-translator.sh` (issue #376): LuCI views keep their translations with Lodash on `window._`, applied once, an unexpected `luci.js` fails the build |
| `test_po2lmo.py` | `tools/po2lmo.py` against catalogs LuCI's own po2lmo produced (`tests/fixtures/po2lmo`) |
| `test_terminal.py` | System > Terminal on `openwrt-luci` (ttyd): `mu300term`'s one-time token (a 0600 file in a 0700 directory, at most 16, refused when ttyd runs another command), `mu300-terminal-login` (a root login for a token once and within its minute, every other argument refused), the image's ttyd config (the LAN address, origin check, no port of it opened on the cellular side, wan input never accepted), the ACL, the menu and the build |
| `test_panel.py` | the web panel for Ubuntu (the panel extra: Cockpit and the MU300 page): mu300-update's checks of its tarball, `mu300-extra install panel` online (apt) and offline (`--from`, the release's packages, checked against SHA256SUMS), remove, `link` (nothing at boot while Cockpit is there; a background restore after an update), `mu300-panel` (LAN-only socket, `info` JSON with hostile names, `hotspot-set` with the password on stdin), the firewall keeping 9090 off the uplink, the manifest and translations, the page's JavaScript under Node (argument arrays, secrets on stdin, text never as HTML), `sms json` |
+87
View File
@@ -0,0 +1,87 @@
"""openwrt/patches/luci-lexical-translator.sh (issue #376): LuCI's views keep their translations when a browser
extension puts Lodash on window._. The script gives luci.js's outer function a `const _` of its own, which the views
LuCI compiles there by direct eval() find before the global. A small stand-in for luci.js with the same opening and
the same way of compiling a view; the real luci.js was checked on a device (see the PR)."""
import json, shutil, subprocess, tempfile, unittest
from pathlib import Path
from helpers import TOP
SCRIPT = TOP / 'openwrt' / 'patches' / 'luci-lexical-translator.sh'
BUILD = TOP / 'openwrt' / 'build-rootfs.sh'
# luci.js as LuCI 25.12 ships it: a blank line, then the minified outer function; views are compiled with a direct
# eval() inside it (compileClass), so their free names resolve in this scope first
LUCI = ("\n((window,document,undefined)=>{'use strict';const env={};"
"const compile=src=>eval('(function(window, document, L) { ' + src + ' })');"
"window.mu300Compile=compile;})(window,document);")
# cbi.js's lookup: the trimmed string, its context before it with \\u0001, hashed (a stand-in hash here) into TR
CBI = r"""
var window = globalThis, document = {};
function trimws(s) { return String(s).trim().replace(/[ \t\n]+/g, ' '); }
function sfh(s) { return 'h:' + s; }
function _(s, c) { var k = (c != null ? trimws(c) + '\u0001' : '') + trimws(s); return (window.TR && TR[sfh(k)]) || s; }
window.TR = { 'h:Actions': 'Aktionen', 'h:menu\u0001Open': 'Offnen' };
"""
@unittest.skipUnless(shutil.which('node'), 'Node.js is needed for the LuCI JS tests')
class LexicalTranslator(unittest.TestCase):
def setUp(self):
self.tmp = Path(tempfile.mkdtemp())
self.addCleanup(shutil.rmtree, self.tmp)
self.js = self.tmp / 'luci.js'
self.js.write_text(LUCI)
def patch(self, ok=True):
r = subprocess.run(['sh', str(SCRIPT), str(self.js)], capture_output=True, text=True)
self.assertEqual(r.returncode == 0, ok, r.stderr)
return r
def run_page(self, lodash):
prog = CBI + (
"window._ = function lodash(v) { return { __wrapped__: v }; }; window._.VERSION = '4.17.21';\n"
if lodash else '') + self.js.read_text() + r"""
const view = window.mu300Compile("return [ _('Actions'), _(' Actions\\n'), _('Open', 'menu'), _('Untranslated'), typeof _('Actions') ];");
console.log(JSON.stringify({ view: view(window, null, null), global: typeof window._('Actions') }));
"""
r = subprocess.run(['node', '-e', prog], capture_output=True, text=True)
self.assertEqual(r.returncode, 0, r.stderr)
return json.loads(r.stdout)
def test_without_the_patch_lodash_breaks_the_view(self):
self.assertEqual(self.run_page(True)['view'][4], 'object')
def test_the_patched_view_translates_with_lodash_on_the_page(self):
self.patch()
out = self.run_page(True)
self.assertEqual(out['view'], ['Aktionen', 'Aktionen', 'Offnen', 'Untranslated', 'string'])
self.assertEqual(out['global'], 'object') # the extension's window._ is left alone
def test_the_patched_view_translates_without_lodash(self):
self.patch()
self.assertEqual(self.run_page(False)['view'][:4], ['Aktionen', 'Aktionen', 'Offnen', 'Untranslated'])
def test_it_is_applied_once(self):
self.patch()
once = self.js.read_text()
self.patch()
self.assertEqual(self.js.read_text(), once)
self.assertEqual(once.count('const _='), 1)
subprocess.run(['node', '--check', str(self.js)], check=True)
def test_an_unexpected_luci_js_fails_the_build(self):
self.js.write_text("(function(window){'use strict';})(window);")
self.patch(ok=False)
self.assertNotIn('const _=', self.js.read_text())
class Build(unittest.TestCase):
def test_the_image_build_applies_it(self):
b = BUILD.read_text()
self.assertIn('/in/luci-lexical-translator.sh:ro', b)
self.assertIn('sh /in/luci-lexical-translator.sh $R/www/luci-static/resources/luci.js', b)
if __name__ == '__main__':
unittest.main()
+3 -2
View File
@@ -1094,7 +1094,7 @@ class Rules(unittest.TestCase):
# one argument: the build's own `set --` statement is run with spaces in every path
text = (TOP / 'openwrt' / 'build-rootfs.sh').read_text()
self.assertNotIn('$LUCI', text)
m = re.search(r'\n (set -- -v "\$THEME_APK:.*?:/in/catalogs:ro")\n', text, re.S)
m = re.search(r'\n (set -- -v "\$THEME_APK:.*?:/in/luci-lexical-translator.sh:ro")\n', text, re.S)
self.assertTrue(m, 'the luci mounts are not one set -- statement')
self.assertRegex(text, r'-v "\$REGDB":/in/regdb:ro "\$@" \\\n')
for sh in shells():
@@ -1102,7 +1102,8 @@ class Rules(unittest.TestCase):
env=dict(os.environ, THEME_APK='/a b/theme.apk', TOP='/my repo', CAT='/t m/cat'))
self.assertEqual(r.stdout.splitlines(), [
'-v', '/a b/theme.apk:/in/luci-theme-aurora.apk:ro', '-v', '/my repo/openwrt/luci-app-mu300:/in/luci-plugin:ro',
'-v', '/my repo/openwrt/luci-overlay:/in/luci-overlay:ro', '-v', '/t m/cat:/in/catalogs:ro'], sh)
'-v', '/my repo/openwrt/luci-overlay:/in/luci-overlay:ro', '-v', '/t m/cat:/in/catalogs:ro',
'-v', '/my repo/openwrt/patches/luci-lexical-translator.sh:/in/luci-lexical-translator.sh:ro'], sh)
def test_openwrt_luci_starts_ndp_learn(self):
# K37: init.d/mu300-ndp is enabled in openwrt-luci's image (it does nothing unless wan is in relay mode) and