| 1 |
# vim:fileencoding=utf-8 |
| 2 |
# License: GPL v3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net> |
| 3 |
from __python__ import bound_methods, hash_literals |
| 4 |
|
| 5 |
import traceback |
| 6 |
from aes import GCM |
| 7 |
from elementmaker import E |
| 8 |
from gettext import install |
| 9 |
|
| 10 |
from book_list.globals import get_translations, main_js |
| 11 |
from book_list.theme import get_font_family |
| 12 |
from dom import ensure_id |
| 13 |
|
| 14 |
LOADING_DOC = ''' |
| 15 |
<!DOCTYPE html> |
| 16 |
<html> |
| 17 |
<head> |
| 18 |
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no"> |
| 19 |
<meta http-equiv="X-UA-Compatible" content="IE=edge"> |
| 20 |
<!-- script must be on a single line so that source map matches up --> |
| 21 |
<script type="text/javascript" id="bootstrap">window.iframe_entry_point = '__ENTRY_POINT__'; window.default_font_family = '__FONT__'; __SCRIPT__ |
| 22 |
end_script |
| 23 |
</head> |
| 24 |
<body> |
| 25 |
<div style="font-size:larger; font-weight: bold; margin-top:48vh; text-align:center"> |
| 26 |
__BS__ |
| 27 |
</div> |
| 28 |
</body> |
| 29 |
</html> |
| 30 |
'''.replace('end_script', '<' + '/script>') # cannot have a closing script tag as this is embedded inside a script tag in index.html |
| 31 |
|
| 32 |
|
| 33 |
class Messenger: |
| 34 |
def __init__(self): |
| 35 |
self.secret = Uint8Array(64) |
| 36 |
|
| 37 |
def reset(self): |
| 38 |
window.crypto.getRandomValues(self.secret) |
| 39 |
self.gcm_to_iframe = GCM(self.secret.subarray(0, 32)) |
| 40 |
self.gcm_from_iframe = GCM(self.secret.subarray(32)) |
| 41 |
|
| 42 |
def encrypt(self, data): |
| 43 |
return self.gcm_to_iframe.encrypt(JSON.stringify(data)) |
| 44 |
|
| 45 |
def decrypt(self, data): |
| 46 |
return JSON.parse(self.gcm_from_iframe.decrypt(data)) |
| 47 |
|
| 48 |
|
| 49 |
class IframeWrapper: |
| 50 |
def __init__(self, handlers, iframe, entry_point, bootstrap_text): |
| 51 |
self.messenger = Messenger() |
| 52 |
self.iframe_id = ensure_id(iframe, 'content-iframe') |
| 53 |
self.reload_count = 0 |
| 54 |
if ':' in entry_point: |
| 55 |
self.needs_init = iframe.src is not entry_point |
| 56 |
self.srcdoc_created = True |
| 57 |
self.constructor_url = entry_point |
| 58 |
self.entry_point = None |
| 59 |
else: |
| 60 |
self.needs_init = True |
| 61 |
self.srcdoc_created = False |
| 62 |
self.constructor_url = None |
| 63 |
self.entry_point = entry_point |
| 64 |
self.ready = False |
| 65 |
self.encrypted_communications = False |
| 66 |
self.bootstrap_text = bootstrap_text or '' |
| 67 |
self.handlers = {k: handlers[k] for k in handlers} |
| 68 |
self.on_ready_handler = self.handlers.ready |
| 69 |
self.handlers.ready = self.on_iframe_ready |
| 70 |
window.addEventListener('message', self.handle_message, False) |
| 71 |
|
| 72 |
def destroy(self): |
| 73 |
window.removeEventListener('message', self.handle_message, False) |
| 74 |
|
| 75 |
@property |
| 76 |
def iframe(self): |
| 77 |
return document.getElementById(self.iframe_id) |
| 78 |
|
| 79 |
def create_srcdoc(self): |
| 80 |
r = /__([A-Z][A-Z_0-9]*[A-Z0-9])__/g |
| 81 |
if self.entry_point: |
| 82 |
data = { |
| 83 |
'BS': self.bootstrap_text, |
| 84 |
'SCRIPT': main_js(), |
| 85 |
'FONT': get_font_family(), |
| 86 |
'ENTRY_POINT': self.entry_point, |
| 87 |
} |
| 88 |
self.iframe.srcdoc = LOADING_DOC.replace(r, def (match, field): return data[field];) |
| 89 |
else: |
| 90 |
self.iframe.src = self.constructor_url |
| 91 |
self.srcdoc_created = True |
| 92 |
|
| 93 |
def init(self): |
| 94 |
if not self.needs_init: |
| 95 |
return |
| 96 |
self.needs_init = False |
| 97 |
iframe = self.iframe |
| 98 |
if self.srcdoc_created: |
| 99 |
if self.entry_point: |
| 100 |
sdoc = iframe.srcdoc |
| 101 |
iframe.srcdoc = '<p> </p>' |
| 102 |
iframe.srcdoc = sdoc |
| 103 |
else: |
| 104 |
self.reload_count += 1 |
| 105 |
ch = '&' if '?' in self.constructor_url else '?' |
| 106 |
iframe.src = self.constructor_url + f'{ch}rc={self.reload_count}' |
| 107 |
else: |
| 108 |
self.create_srcdoc() |
| 109 |
|
| 110 |
def reset(self): |
| 111 |
self.ready = False |
| 112 |
self.needs_init = True |
| 113 |
self.encrypted_communications = False |
| 114 |
|
| 115 |
def _send_message(self, action, encrypted, data): |
| 116 |
if not self.ready: |
| 117 |
return |
| 118 |
data.action = action |
| 119 |
msg = {'data': data, 'encrypted': encrypted} |
| 120 |
if encrypted: |
| 121 |
msg.data = self.messenger.encrypt(data) |
| 122 |
self.iframe.contentWindow.postMessage(msg, '*') |
| 123 |
|
| 124 |
def send_message(self, action, **data): |
| 125 |
self._send_message(action, self.encrypted_communications, data) |
| 126 |
|
| 127 |
def send_unencrypted_message(self, action, **data): |
| 128 |
self._send_message(action, False, data) |
| 129 |
|
| 130 |
def handle_message(self, event): |
| 131 |
if event.source is not self.iframe?.contentWindow: |
| 132 |
return |
| 133 |
data = event.data |
| 134 |
if self.encrypted_communications: |
| 135 |
if data.tag is undefined: |
| 136 |
print('Ignoring unencrypted message from iframe:', data) |
| 137 |
return |
| 138 |
try: |
| 139 |
data = self.messenger.decrypt(data) |
| 140 |
except Exception as e: |
| 141 |
print('Could not decrypt message from iframe:') |
| 142 |
console.log(e) |
| 143 |
traceback.print_exc() |
| 144 |
return |
| 145 |
if not data.action: |
| 146 |
return |
| 147 |
func = self.handlers[data.action] |
| 148 |
if func: |
| 149 |
func(data) |
| 150 |
else: |
| 151 |
print('Unknown action in message from iframe to parent:', data.action) |
| 152 |
|
| 153 |
def on_iframe_ready(self, data): |
| 154 |
self.messenger.reset() |
| 155 |
msg = {'secret': self.messenger.secret, 'translations': get_translations()} |
| 156 |
self.ready = True |
| 157 |
callback = None |
| 158 |
if self.on_ready_handler: |
| 159 |
callback = self.on_ready_handler(msg) |
| 160 |
self._send_message('initialize', False, msg) |
| 161 |
self.encrypted_communications = True |
| 162 |
if callback: |
| 163 |
callback() |
| 164 |
|
| 165 |
|
| 166 |
def create_wrapped_iframe(handlers, bootstrap_text, entry_point, kw): |
| 167 |
if ':' in entry_point: |
| 168 |
# this is a document loaded via the fake protocol from web_view.py |
| 169 |
kw.src = entry_point |
| 170 |
kw.sandbox = (kw.sandbox or '') + ' allow-same-origin' |
| 171 |
iframe = E.iframe(**kw) |
| 172 |
ans = IframeWrapper(handlers, iframe, entry_point, bootstrap_text) |
| 173 |
return iframe, ans |
| 174 |
|
| 175 |
|
| 176 |
instance_numbers = {} |
| 177 |
|
| 178 |
|
| 179 |
class IframeClient: |
| 180 |
def __init__(self, handlers, name): |
| 181 |
self.encrypted_communications = False |
| 182 |
self.name = name |
| 183 |
if not instance_numbers[self.name]: |
| 184 |
instance_numbers[self.name] = 0 |
| 185 |
instance_numbers[self.name] += 1 |
| 186 |
self.instance_num = instance_numbers[self.name] |
| 187 |
self.handlers = {k: handlers[k] for k in handlers} |
| 188 |
self.initialize_handler = handlers.initialize |
| 189 |
self.handlers.initialize = self.initialize |
| 190 |
self.ready_sent = False |
| 191 |
window.addEventListener('message', self.handle_message, False) |
| 192 |
window.addEventListener('load', self.send_ready, {'once': True}) |
| 193 |
|
| 194 |
def send_ready(self): |
| 195 |
if not self.ready_sent: |
| 196 |
self.send_message('ready', {}) |
| 197 |
self.ready_sent = True |
| 198 |
|
| 199 |
def initialize(self, data): |
| 200 |
nonlocal print |
| 201 |
self.gcm_from_parent, self.gcm_to_parent = GCM(data.secret.subarray(0, 32)), GCM(data.secret.subarray(32)) |
| 202 |
self.encrypted_communications = True |
| 203 |
if data.translations: |
| 204 |
install(data.translations) |
| 205 |
print = self.print_to_parent |
| 206 |
if self.initialize_handler: |
| 207 |
self.initialize_handler(data) |
| 208 |
|
| 209 |
def print_to_parent(self, *args): |
| 210 |
self.send_message('print', string=' '.join(map(str, args))) |
| 211 |
|
| 212 |
def handle_message(self, event): |
| 213 |
if event.source is not window.parent: |
| 214 |
return |
| 215 |
msg = event.data |
| 216 |
data = msg.data |
| 217 |
if msg.encrypted: |
| 218 |
if not self.gcm_from_parent: |
| 219 |
print(f'the iframe {self.name}-{self.instance_num} got an encrypted message from its parent without being initialized') |
| 220 |
return |
| 221 |
# We cannot use self.encrypted_communications as the 'display' |
| 222 |
# message has to be unencrypted as it transports Blob objects |
| 223 |
try: |
| 224 |
data = JSON.parse(self.gcm_from_parent.decrypt(data)) |
| 225 |
except Exception as e: |
| 226 |
print('Could not process message from parent:') |
| 227 |
console.log(e) |
| 228 |
return |
| 229 |
if not data or not data.action: |
| 230 |
console.log('Got a null message from parent in iframe, ignoring') |
| 231 |
return |
| 232 |
func = self.handlers[data.action] |
| 233 |
if func: |
| 234 |
try: |
| 235 |
func(data) |
| 236 |
except Exception as e: |
| 237 |
console.log('Error in iframe message handler {}:'.format(data?.action)) |
| 238 |
console.log(e) |
| 239 |
details = traceback.format_exc() |
| 240 |
console.log(details) |
| 241 |
self.send_message('error', title='Error in message handler', details=details, msg=e.toString()) |
| 242 |
else: |
| 243 |
print('Unknown action in message to iframe from parent: ' + data.action) |
| 244 |
|
| 245 |
def send_message(self, action, data): |
| 246 |
data.action = action |
| 247 |
data.iframe_id = f'{self.name}-{self.instance_num}' |
| 248 |
if self.encrypted_communications: |
| 249 |
data = self.gcm_to_parent.encrypt(JSON.stringify(data)) |
| 250 |
window.parent.postMessage(data, '*') |