-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathserver_manager.go
More file actions
1644 lines (1465 loc) · 55.5 KB
/
server_manager.go
File metadata and controls
1644 lines (1465 loc) · 55.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"fmt"
"io"
"net"
"net/http"
"net/http/httputil"
"net/url"
"os"
"path/filepath"
"strings"
"sync"
"github.com/civilware/tela"
)
// ServerManager handles TELA server lifecycle
// ServerInfo represents an active TELA server
type ActiveServer struct {
Name string `json:"name"`
SCID string `json:"scid"`
Port int `json:"port"`
URL string `json:"url"`
IsLocal bool `json:"isLocal"`
Directory string `json:"directory,omitempty"`
}
// Global server registry
var serverRegistry = struct {
sync.RWMutex
servers map[string]*ActiveServer
}{
servers: make(map[string]*ActiveServer),
}
// Proxy server registry - maps SCID to proxy server
var proxyRegistry = struct {
sync.RWMutex
proxies map[string]*http.Server // SCID -> proxy server
ports map[string]int // SCID -> proxy port
}{
proxies: make(map[string]*http.Server),
ports: make(map[string]int),
}
// In-memory server registry - for serving DocShards content assembled by HOLOGRAM
var memoryServerRegistry = struct {
sync.RWMutex
servers map[string]*http.Server // SCID -> in-memory server
ports map[string]int // SCID -> port
content map[string]*TELAContent // SCID -> assembled content
}{
servers: make(map[string]*http.Server),
ports: make(map[string]int),
content: make(map[string]*TELAContent),
}
// findAvailableProxyPort finds an available port for the proxy server
func findAvailableProxyPort() (int, error) {
// Use port range 50000-60000 for proxy servers (separate from tela servers)
for port := 50000; port < 60000; port++ {
addr := fmt.Sprintf("127.0.0.1:%d", port)
listener, err := net.Listen("tcp", addr)
if err == nil {
listener.Close()
return port, nil
}
}
return 0, fmt.Errorf("no available ports in range 50000-60000")
}
// createProxyServer creates a reverse proxy that strips CSP headers
//
// SECURITY CONSIDERATIONS:
// =======================
// This proxy removes Content-Security-Policy (CSP) headers to allow TELA apps
// like dero-explorer to function properly. While removing CSP reduces one
// security layer, Hologram maintains security through multiple other layers:
//
// 1. Blockchain Immutability: TELA content is stored on-chain and cannot be
// modified after deployment. The content served is cryptographically verified.
//
// 2. Iframe Sandboxing: All TELA apps run in a sandboxed iframe with restricted
// permissions (allow-scripts, allow-same-origin, allow-forms, allow-modals).
//
// 3. Controlled API Access: The telaHost API requires explicit user approval for
// sensitive operations (transactions, wallet access). Apps cannot access
// wallet functions without user interaction.
//
// 4. Local Execution: Content runs locally on the user's machine, not on a
// remote server that could be compromised.
//
// 5. Source Verification: Content is fetched directly from the DERO blockchain
// daemon, not from arbitrary web servers.
//
// The risk of removing CSP is mitigated by these layers. A malicious TELA app
// would need to:
// - Be deployed to the blockchain (permanent, verifiable)
// - Bypass iframe sandbox restrictions
// - Get user approval for any wallet operations
// - Operate within the constraints of local execution
//
// This defense-in-depth approach provides security while enabling TELA apps
// that require CSP relaxation to function.
func createProxyServer(targetURL, scid string) (string, error) {
// Parse target URL
target, err := url.Parse(targetURL)
if err != nil {
return "", fmt.Errorf("invalid target URL: %w", err)
}
// Extract the base URL (scheme + host) for the proxy target
// The reverse proxy needs just the base, not the full path
baseTarget := &url.URL{
Scheme: target.Scheme,
Host: target.Host,
}
// Find available port
port, err := findAvailableProxyPort()
if err != nil {
return "", err
}
// Create reverse proxy pointing to base URL
proxy := httputil.NewSingleHostReverseProxy(baseTarget)
// Get XSWD bridge script (same as in Browser.svelte)
xswdBridgeScript := getXSWDBridgeScript()
// Modify response to strip CSP headers and inject XSWD bridge
// The bridge is needed because iframe sandbox restrictions may block direct WebSocket connections
proxy.ModifyResponse = func(r *http.Response) error {
// Remove Content-Security-Policy header to allow apps that need it
r.Header.Del("Content-Security-Policy")
r.Header.Del("Content-Security-Policy-Report-Only")
// Add security headers for defense-in-depth
// X-Frame-Options is not needed since we control the iframe
// X-Content-Type-Options prevents MIME sniffing
r.Header.Set("X-Content-Type-Options", "nosniff")
// Inject XSWD bridge script into HTML responses
contentType := r.Header.Get("Content-Type")
if strings.Contains(contentType, "text/html") {
// Read the response body
body, err := io.ReadAll(r.Body)
if err != nil {
return err
}
r.Body.Close()
// Inject bridge scripts at the beginning of HTML (before any other scripts)
bodyStr := string(body)
modifiedBody := xswdBridgeScript + getHologramClipboardBridgeScript() + bodyStr
// Update content length
r.ContentLength = int64(len(modifiedBody))
r.Header.Set("Content-Length", fmt.Sprintf("%d", len(modifiedBody)))
// Create new body reader
r.Body = io.NopCloser(strings.NewReader(modifiedBody))
}
return nil
}
// Create HTTP server
server := &http.Server{
Addr: fmt.Sprintf("127.0.0.1:%d", port),
Handler: proxy,
}
// Start server in goroutine
go func() {
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
// Log error but don't fail - proxy server error
fmt.Printf("[PROXY] Error serving proxy for %s: %v\n", scid, err)
}
}()
// Register proxy
proxyRegistry.Lock()
proxyRegistry.proxies[scid] = server
proxyRegistry.ports[scid] = port
proxyRegistry.Unlock()
// Return proxy URL at root - the reverse proxy handles all paths
// The tela server URL may include a path (e.g. entry point), but the proxy
// should serve the entire site from root
proxyURL := fmt.Sprintf("http://127.0.0.1:%d", port)
return proxyURL, nil
}
// serveDocShardsContent creates an in-memory HTTP server for assembled DocShards content.
// This bypasses the tela library (which doesn't support DocShards) and serves content
// directly from memory, including binary files like WASM that can't be inlined into HTML.
func (a *App) serveDocShardsContent(scid string, content *TELAContent) (string, error) {
a.logToConsole("[MEM] Creating in-memory server for DocShards content")
// Check if server already exists for this SCID
memoryServerRegistry.RLock()
if existingServer := memoryServerRegistry.servers[scid]; existingServer != nil {
port := memoryServerRegistry.ports[scid]
memoryServerRegistry.RUnlock()
serverURL := fmt.Sprintf("http://127.0.0.1:%d", port)
a.logToConsole(fmt.Sprintf("[MEM] Reusing existing in-memory server: %s", serverURL))
return serverURL, nil
}
memoryServerRegistry.RUnlock()
// Find available port
port, err := findAvailableProxyPort()
if err != nil {
return "", fmt.Errorf("failed to find available port: %w", err)
}
// Create HTTP handler that serves content from memory
mux := http.NewServeMux()
// Serve HTML at root
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
path := r.URL.Path
if path == "/" || path == "/index.html" {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("Access-Control-Allow-Origin", "*")
// Inject XSWD bridge script for wallet connectivity
html := content.HTML
bridgeScript := getXSWDBridgeScript()
html = injectScriptIntoHTML(html, bridgeScript)
html = injectScriptIntoHTML(html, getHologramClipboardBridgeScript())
w.Write([]byte(html))
return
}
// Strip leading slash for filename lookup
filename := strings.TrimPrefix(path, "/")
// Try to serve from JSByName
if js, ok := content.JSByName[filename]; ok {
w.Header().Set("Content-Type", "application/javascript; charset=utf-8")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Write([]byte(js))
return
}
// Try to serve from CSSByName
if css, ok := content.CSSByName[filename]; ok {
w.Header().Set("Content-Type", "text/css; charset=utf-8")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Write([]byte(css))
return
}
// Try to serve from StaticByName (WASM, RIV, images, etc.)
if static, ok := content.StaticByName[filename]; ok {
ext := strings.ToLower(filepath.Ext(filename))
var contentType string
switch ext {
case ".wasm":
contentType = "application/wasm"
case ".riv":
contentType = "application/octet-stream"
case ".json":
contentType = "application/json"
case ".svg":
contentType = "image/svg+xml"
case ".png":
contentType = "image/png"
case ".jpg", ".jpeg":
contentType = "image/jpeg"
case ".gif":
contentType = "image/gif"
case ".webp":
contentType = "image/webp"
case ".ico":
contentType = "image/x-icon"
default:
contentType = "application/octet-stream"
}
w.Header().Set("Content-Type", contentType)
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Write([]byte(static))
return
}
// File not found
http.NotFound(w, r)
})
// Create and start server
server := &http.Server{
Addr: fmt.Sprintf("127.0.0.1:%d", port),
Handler: mux,
}
// Start server in goroutine
go func() {
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
a.logToConsole(fmt.Sprintf("[MEM] Server error for %s: %v", scid, err))
}
}()
// Register server
memoryServerRegistry.Lock()
memoryServerRegistry.servers[scid] = server
memoryServerRegistry.ports[scid] = port
memoryServerRegistry.content[scid] = content
memoryServerRegistry.Unlock()
serverURL := fmt.Sprintf("http://127.0.0.1:%d", port)
a.logToConsole(fmt.Sprintf("[MEM] In-memory server started: %s", serverURL))
// Log what files are available
if len(content.JSByName) > 0 {
for name := range content.JSByName {
a.logToConsole(fmt.Sprintf(" [MEM] Serving JS: /%s", name))
}
}
if len(content.StaticByName) > 0 {
for name := range content.StaticByName {
a.logToConsole(fmt.Sprintf(" [MEM] Serving static: /%s", name))
}
}
return serverURL, nil
}
// injectScriptIntoHTML injects a script into HTML, preferably into <head>
func injectScriptIntoHTML(html, script string) string {
// Try to inject after <head>
if idx := strings.Index(strings.ToLower(html), "<head>"); idx != -1 {
insertPos := idx + 6
return html[:insertPos] + "\n" + script + "\n" + html[insertPos:]
}
// Try to inject after <!DOCTYPE html>
if idx := strings.Index(strings.ToLower(html), "<!doctype html>"); idx != -1 {
insertPos := idx + 15
return html[:insertPos] + "\n" + script + "\n" + html[insertPos:]
}
// Prepend to HTML
return script + "\n" + html
}
// getHologramClipboardBridgeScript wraps navigator.clipboard read/write inside the TELA iframe.
// WKWebKit/WebKitGTK often rejects the Clipboard API in embedded frames even with sandbox flags;
// the parent resolves operations via Wails ClipboardGetText / ClipboardSetText (see Browser.svelte).
func getHologramClipboardBridgeScript() string {
return `<script>
(function() {
'use strict';
try {
if (!navigator || !navigator.clipboard || window.parent === window) return;
var clip = navigator.clipboard;
var ow = clip.writeText && clip.writeText.bind(clip);
var or = clip.readText && clip.readText.bind(clip);
function viaBridge(op, text) {
return new Promise(function(resolve, reject) {
var id = 'hcb_' + Math.random().toString(36).slice(2) + '_' + Date.now();
function onMsg(ev) {
var d = ev.data;
if (!d || d.type !== 'hologram-clipboard-response' || d.id !== id) return;
window.removeEventListener('message', onMsg);
clearTimeout(tmo);
if (d.ok) {
if (op === 'read') resolve(typeof d.text === 'string' ? d.text : '');
else resolve();
} else reject(new Error(d.error || 'Clipboard operation failed'));
}
window.addEventListener('message', onMsg);
var tmo = setTimeout(function() {
window.removeEventListener('message', onMsg);
reject(new Error('Clipboard bridge timeout'));
}, 15000);
try {
window.parent.postMessage({ type: 'hologram-clipboard-request', id: id, op: op, text: text === undefined || text === null ? '' : String(text) }, '*');
} catch (e) {
window.removeEventListener('message', onMsg);
clearTimeout(tmo);
reject(e);
}
});
}
clip.writeText = function(txt) {
if (!ow) return viaBridge('write', txt);
return ow(txt).catch(function() { return viaBridge('write', txt); });
};
clip.readText = function() {
if (!or) return viaBridge('read');
return or().catch(function() { return viaBridge('read'); });
};
} catch (e) {}
})();
</script>`
}
// getXSWDBridgeScript returns the XSWD bridge script to inject into TELA apps
// This script intercepts WebSocket connections to localhost:44326 and routes them
// through Hologram's XSWD server via postMessage
func getXSWDBridgeScript() string {
return `<script>
(function() {
'use strict';
// Simple log to parent
function log(msg) {
try { window.parent.postMessage({ type: 'xswd-request', id: 0, action: 'log', payload: msg }, '*'); } catch(e) {}
// Also log to console for debugging
try { console.log('[XSWD Bridge]', msg); } catch(e) {}
}
log('[Bridge] Initializing...');
// CRITICAL: Override WebSocket IMMEDIATELY before any other scripts can use it
// Store original WebSocket FIRST, before anything else
var OriginalWebSocket = window.WebSocket;
log('[Bridge] Original WebSocket stored');
// Request ID for parent communication
var reqId = 0;
var pending = {};
// Listen for parent responses
window.addEventListener('message', function(e) {
if (e.data && e.data.type === 'xswd-response' && pending[e.data.id]) {
var p = pending[e.data.id];
delete pending[e.data.id];
e.data.error ? p.reject(new Error(e.data.error)) : p.resolve(e.data.result);
}
});
// Send to parent and wait
function request(action, payload) {
return new Promise(function(resolve, reject) {
var id = ++reqId;
pending[id] = { resolve: resolve, reject: reject };
var message = { type: 'xswd-request', id: id, action: action, payload: payload };
log('[Bridge] Sending postMessage to parent: ' + JSON.stringify({ id: id, action: action, payloadKeys: Object.keys(payload || {}) }));
window.parent.postMessage(message, '*');
setTimeout(function() {
if (pending[id]) {
log('[Bridge] Request ' + id + ' timed out after 60s');
delete pending[id];
reject(new Error('timeout'));
}
}, 60000);
});
}
// XSWD WebSocket Proxy
// Don't inherit from WebSocket.prototype - it has readonly properties that break in Wails
// Instead, create a plain object and manually implement WebSocket interface
function XSWDProxy(url) {
var self = this;
// Use Object.defineProperty to set writable properties (avoids readonly errors)
Object.defineProperty(self, 'url', { value: url, writable: true, enumerable: true });
Object.defineProperty(self, 'readyState', { value: 0, writable: true, enumerable: true }); // CONNECTING
// Monitor onopen handler being set
var originalOnopen = null;
Object.defineProperty(self, 'onopen', {
get: function() { return originalOnopen; },
set: function(value) {
log('[Bridge] onopen handler being set by dApp');
originalOnopen = value;
// If connection is already open and handler is being set, trigger it
if (self.readyState === 1 && value && !self._handshakeSent) {
setTimeout(function() {
log('[Bridge] Triggering onopen handler (set after connection opened)');
try {
value({ type: 'open', target: self });
} catch(e) {
log('[Error] onopen error (late set): ' + e.message);
}
}, 0);
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(self, 'onmessage', { value: null, writable: true, enumerable: true });
Object.defineProperty(self, 'onerror', { value: null, writable: true, enumerable: true });
Object.defineProperty(self, 'onclose', { value: null, writable: true, enumerable: true });
// Internal state
self._auth = 'pending';
self._queue = [];
self._handshakeSent = false;
log('[XSWD] Connection intercepted: ' + url);
// Simulate connection open - use setTimeout to give dApp time to set handlers
// Real WebSocket takes a moment to connect, so this delay is realistic
setTimeout(function() {
self.readyState = 1; // OPEN
log('[XSWD] WebSocket opened (readyState = OPEN)');
if (self.onopen) {
log('[OK] onopen handler is set, calling it');
try {
self.onopen({ type: 'open', target: self });
} catch(e) {
log('[Error] onopen error: ' + e.message);
}
} else {
log('[Warn] No onopen handler set yet - dApp may set it later');
}
// Process queued messages
var queuedCount = self._queue.length;
if (queuedCount > 0) {
log('[Queue] Processing ' + queuedCount + ' queued message(s)');
}
while (self._queue.length) {
var msg = self._queue.shift();
log('[Queue] Processing queued message:', typeof msg === 'string' ? msg.substring(0, 200) : JSON.stringify(msg).substring(0, 200));
self._handle(msg);
}
}, 10);
// Also check for onopen handler after delays in case dApp sets it asynchronously
// Some dApps set onopen handler in setTimeout or after other initialization
[50, 100, 200, 500, 1000].forEach(function(delay) {
setTimeout(function() {
if (self.onopen && !self._handshakeSent && self.readyState === 1) {
log('[Bridge] onopen handler now set (delayed ' + delay + 'ms), triggering manually');
try {
self.onopen({ type: 'open', target: self });
} catch(e) {
log('[Error] onopen error (delayed ' + delay + 'ms): ' + e.message);
}
}
}, delay);
});
}
// Don't inherit from WebSocket.prototype - it has readonly properties
// Instead, create a plain prototype and manually implement the interface
// This avoids "readonly property" errors in Wails WebView
// MUST set prototype BEFORE defining methods, otherwise methods get wiped out!
XSWDProxy.prototype = {};
XSWDProxy.prototype.constructor = XSWDProxy;
// Now define all methods on the prototype
XSWDProxy.prototype.send = function(data) {
log('[Bridge] WebSocket.send() called with data:', typeof data === 'string' ? data.substring(0, 200) : JSON.stringify(data).substring(0, 200));
if (this.readyState === 0) {
log('[Bridge] Queueing message (connection not open yet)');
this._queue.push(data);
return;
}
if (this.readyState !== 1) throw new Error('WebSocket closed');
this._handle(data);
};
XSWDProxy.prototype._handle = function(data) {
var self = this;
try {
var msg = typeof data === 'string' ? JSON.parse(data) : data;
log('[XSWD] ' + (msg.method || 'handshake') + ' | Full message: ' + JSON.stringify(msg).substring(0, 200));
// Handshake detection - multiple patterns
// Pattern 1: Plain object with name/description (no method)
var isHandshake1 = !msg.method && (msg.name || msg.description || msg.appName || msg.app_name);
// Pattern 2: JSON-RPC with method "handshake"
var isHandshake2 = msg.method === 'handshake' || msg.method === 'Handshake';
// Pattern 3: First message after connection (if no auth yet)
var isHandshake3 = self._auth === 'pending' && !msg.method && Object.keys(msg).length > 0;
if (isHandshake1 || isHandshake2 || isHandshake3) {
log('[Bridge] Detected handshake message (pattern: ' + (isHandshake1 ? '1' : isHandshake2 ? '2' : '3') + ')');
self._handshakeSent = true;
// Normalize handshake data
var handshakeData = msg.params || msg;
var appInfo = {
name: handshakeData.name || msg.name || handshakeData.appName || msg.appName || handshakeData.app_name || msg.app_name || 'Unknown App',
description: handshakeData.description || msg.description || handshakeData.desc || msg.desc || '',
url: handshakeData.url || msg.url || handshakeData.origin || msg.origin || window.location.href
};
log('[Bridge] Sending connect request with appInfo:', JSON.stringify(appInfo));
request('connect', { appInfo: appInfo }).then(function(ok) {
self._auth = ok ? 'accepted' : 'denied';
log(ok ? '[OK] Connection approved' : '[Denied] Connection denied');
// Match real XSWD server response format exactly - dApp checks for both 'accepted' and 'message'
if (ok) {
self._respond({ accepted: true, message: 'Wallet connection approved' });
} else {
self._respond({ accepted: false, message: 'Connection denied' });
}
}).catch(function(e) {
self._auth = 'denied';
log('[Error] Handshake error: ' + e.message);
self._respond({ accepted: false, message: e.message || 'Connection failed' });
});
return;
}
// RPC call - but check if we need to authenticate first
if (!self._handshakeSent && self._auth === 'pending') {
log('[Bridge] RPC call received before handshake - triggering connection request');
log('[Bridge] Method: ' + msg.method + ', will request connection approval');
// Treat this as a handshake attempt - trigger connection modal
var appInfo = {
name: msg.method ? (msg.method.replace('DERO.', '').replace('Gnomon.', '') + ' App') : 'Unknown App',
description: 'Connection request for ' + (msg.method || 'wallet access'),
url: window.location.href
};
self._handshakeSent = true;
log('[Bridge] Requesting connection with appInfo:', JSON.stringify(appInfo));
request('connect', { appInfo: appInfo }).then(function(ok) {
log('[Bridge] Connection request resolved:', ok);
self._auth = ok ? 'accepted' : 'denied';
if (ok) {
log('[OK] Connection approved, processing original RPC call');
// Now process the original RPC call
request('call', { method: msg.method, params: msg.params, authState: self._auth }).then(function(r) {
self._respond({ jsonrpc: '2.0', id: msg.id, result: r });
}).catch(function(e) {
log('[Error] RPC call failed:', e.message);
self._respond({ jsonrpc: '2.0', id: msg.id, error: { code: -32000, message: e.message } });
});
} else {
log('[Denied] Connection denied');
self._respond({ jsonrpc: '2.0', id: msg.id, error: { code: -32003, message: 'Connection denied' } });
}
}).catch(function(e) {
log('[Error] Connection request error:', e.message);
self._auth = 'denied';
self._respond({ jsonrpc: '2.0', id: msg.id, error: { code: -32000, message: e.message } });
});
return;
}
// Normal RPC call (after handshake)
request('call', { method: msg.method, params: msg.params, authState: self._auth }).then(function(r) {
self._respond({ jsonrpc: '2.0', id: msg.id, result: r });
}).catch(function(e) {
self._respond({ jsonrpc: '2.0', id: msg.id, error: { code: -32000, message: e.message } });
});
} catch(e) {
log('[Error] XSWD error: ' + e.message);
}
};
XSWDProxy.prototype._respond = function(r) {
var self = this;
if (self.onmessage) setTimeout(function() { self.onmessage({ type: 'message', data: JSON.stringify(r), target: self }); }, 0);
};
XSWDProxy.prototype.addEventListener = function(event, handler) {
var self = this;
if (event === 'open') {
log('[Bridge] addEventListener("open") called');
if (self.readyState === 1) {
// Connection already open, trigger immediately
setTimeout(function() {
log('[Bridge] Triggering addEventListener("open") handler (connection already open)');
try {
handler({ type: 'open', target: self });
} catch(e) {
log('[Error] addEventListener("open") error: ' + e.message);
}
}, 0);
} else {
// Store handler to call when connection opens
self.onopen = handler;
}
} else if (event === 'message') {
if (!self._messageHandlers) self._messageHandlers = [];
self._messageHandlers.push(handler);
// Also set onmessage for compatibility
if (!self.onmessage) {
self.onmessage = function(e) {
if (self._messageHandlers) {
self._messageHandlers.forEach(function(h) { h(e); });
}
};
}
} else if (event === 'error') {
if (!self._errorHandlers) self._errorHandlers = [];
self._errorHandlers.push(handler);
if (!self.onerror) {
self.onerror = function(e) {
if (self._errorHandlers) {
self._errorHandlers.forEach(function(h) { h(e); });
}
};
}
} else if (event === 'close') {
if (!self._closeHandlers) self._closeHandlers = [];
self._closeHandlers.push(handler);
if (!self.onclose) {
self.onclose = function(e) {
if (self._closeHandlers) {
self._closeHandlers.forEach(function(h) { h(e); });
}
};
}
}
};
XSWDProxy.prototype.removeEventListener = function(event, handler) {
// Basic implementation - could be improved
if (event === 'message' && this._messageHandlers) {
var idx = this._messageHandlers.indexOf(handler);
if (idx >= 0) this._messageHandlers.splice(idx, 1);
}
// Similar for other events...
};
XSWDProxy.prototype.close = function() {
this.readyState = 3;
if (this.onclose) this.onclose({ type: 'close', code: 1000 });
if (this._closeHandlers) {
this._closeHandlers.forEach(function(h) { h({ type: 'close', code: 1000 }); });
}
};
XSWDProxy.CONNECTING = 0;
XSWDProxy.OPEN = 1;
XSWDProxy.CLOSING = 2;
XSWDProxy.CLOSED = 3;
// Override WebSocket IMMEDIATELY - must happen before any dApp code runs
window.WebSocket = function(url, protocols) {
log('[Bridge] WebSocket constructor called: ' + (url || 'no url'));
// XSWD port: 44326 (mainnet)
if (url && (url.indexOf('44326') !== -1 || url.indexOf('44325') !== -1 || url.indexOf('xswd') !== -1)) {
log('[Bridge] Intercepting XSWD connection: ' + url);
try {
// Create proxy - it already has the right prototype from XSWDProxy.prototype
var proxy = new XSWDProxy(url);
log('[Bridge] XSWDProxy created successfully');
return proxy;
} catch(e) {
log('[Error] Error creating XSWDProxy: ' + e.message);
log('[Error] Error stack: ' + (e.stack || 'no stack'));
// Fallback to original WebSocket
return protocols ? new OriginalWebSocket(url, protocols) : new OriginalWebSocket(url);
}
}
// Not an XSWD connection, use original WebSocket
return protocols ? new OriginalWebSocket(url, protocols) : new OriginalWebSocket(url);
};
window.WebSocket.CONNECTING = 0;
window.WebSocket.OPEN = 1;
window.WebSocket.CLOSING = 2;
window.WebSocket.CLOSED = 3;
log('[Bridge] Ready - WebSocket interception active');
// NOTE: We do NOT inject telaHost here because:
// 1. The real telaHost is injected by Browser.svelte's injectTelaHostAPI() after iframe loads
// 2. If we inject an incomplete telaHost here, dApps find it but can't use it, causing silent failures
// 3. By not providing telaHost, dApps will fall back to WebSocket, which our bridge intercepts
// 4. Once the real telaHost is injected, dApps can use it if they prefer
// ── Blob download interceptor ────────────────────────────────────────────
// HTTP-served TELA apps run cross-origin from the parent Wails window, so the
// parent cannot inject JavaScript into this iframe's context directly. The
// bridge script runs here (in the iframe's own origin) and is therefore the
// right place to intercept downloads and forward them via postMessage so the
// parent can open a native save-file dialog.
(function() {
// Cache blobs at createObjectURL time so we still have the data even after
// the app calls revokeObjectURL synchronously (e.g. Villager does this
// immediately after a.click(), which races against any async fetch).
var _blobCache = {};
var _origCreate = URL.createObjectURL.bind(URL);
URL.createObjectURL = function(obj) {
var url = _origCreate(obj);
if (obj && typeof obj === 'object') _blobCache[url] = obj;
return url;
};
var _origRevoke = URL.revokeObjectURL.bind(URL);
URL.revokeObjectURL = function(url) {
delete _blobCache[url];
return _origRevoke(url);
};
function _saveBlobDownload(href, filename, cachedBlob) {
var blob = cachedBlob || _blobCache[href];
if (!blob) {
// Last-resort fetch (may fail if already revoked, but worth trying)
fetch(href).then(function(r) { return r.blob(); }).then(function(b) {
_saveBlobDownload(href, filename, b);
}).catch(function(e) {
log('[Download] Blob unavailable: ' + e.message);
});
return;
}
var reader = new FileReader();
reader.onloadend = function() {
request('saveFile', {
filename: filename,
base64: reader.result,
mimeType: blob.type || 'application/octet-stream'
}).then(function(result) {
if (result && result.success) {
log('[OK] File saved: ' + (result.path || filename));
} else if (result && result.cancelled) {
log('[Info] Download cancelled');
} else {
log('[Download] Save failed: ' + (result && result.error));
}
}).catch(function(e) {
log('[Download] Save request error: ' + e.message);
});
};
reader.readAsDataURL(blob);
}
// Intercept programmatic .click() on <a download blob:...> elements.
// Must be synchronous so the blob reference is captured before revokeObjectURL fires.
var _origAnchorClick = HTMLAnchorElement.prototype.click;
HTMLAnchorElement.prototype.click = function() {
if (this.hasAttribute('download') && this.href && this.href.indexOf('blob:') === 0) {
var href = this.href;
var filename = this.download || 'download';
var cached = _blobCache[href]; // capture sync
log('[Download] Intercepting: ' + filename);
_saveBlobDownload(href, filename, cached);
return;
}
return _origAnchorClick.call(this);
};
// Intercept declarative clicks on <a download> in markup.
document.addEventListener('click', function(e) {
var el = e.target;
while (el && el.tagName !== 'A') el = el.parentElement;
if (!el || !el.hasAttribute('download')) return;
var href = el.href;
if (!href || href.indexOf('blob:') !== 0) return;
e.preventDefault();
e.stopPropagation();
var filename = el.download || 'download';
var cached = _blobCache[href];
log('[Download] Intercepting click: ' + filename);
_saveBlobDownload(href, filename, cached);
}, true);
log('[Bridge] Download interceptor installed');
})();
// ── File input interceptor ────────────────────────────────────────────────
// Intercepts file input elements so dApps can select files through HOLOGRAM's
// native file dialog. This works around iframe sandbox restrictions that
// prevent file inputs from working in Wails WebView.
(function() {
// Override click on file inputs to route through parent
function interceptFileInputClick(input) {
var accept = input.getAttribute('accept') || '';
var title = input.getAttribute('title') || input.getAttribute('data-title') || 'Select File';
log('[File] Intercepting file input click: accept=' + accept);
request('selectFile', { title: title, accept: accept }).then(function(result) {
if (result && result.success && result.base64) {
log('[OK] File selected: ' + result.filename + ' (' + result.size + ' bytes)');
// Convert base64 to Blob and create a File object
var byteString = atob(result.base64);
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
var blob = new Blob([ab], { type: result.mimeType || 'application/octet-stream' });
// Create a File object (for browser compatibility)
var file;
try {
file = new File([blob], result.filename, { type: result.mimeType || 'application/octet-stream' });
} catch(e) {
// Safari workaround - File constructor may not work in some contexts
file = blob;
file.name = result.filename;
file.lastModified = Date.now();
}
// Create a synthetic FileList-like object
var dt = new DataTransfer();
dt.items.add(file);
// Set the files on the input (this triggers any onchange handlers)
try {
input.files = dt.files;
} catch(e) {
log('[Warn] Could not set input.files: ' + e.message);
}
// Dispatch change event so dApp knows a file was selected
var changeEvent = new Event('change', { bubbles: true, cancelable: false });
input.dispatchEvent(changeEvent);
// Also dispatch input event for completeness
var inputEvent = new Event('input', { bubbles: true, cancelable: false });
input.dispatchEvent(inputEvent);
log('[File] File data injected and events dispatched');
} else if (result && result.cancelled) {
log('[File] User cancelled file selection');
} else {
log('[File] Selection failed: ' + (result && result.error || 'unknown'));
}
}).catch(function(e) {
log('[Error] File selection error: ' + e.message);
});
}
// Method 1: Intercept programmatic .click() calls on file inputs
var _origInputClick = HTMLInputElement.prototype.click;
HTMLInputElement.prototype.click = function() {
if (this.type === 'file') {
interceptFileInputClick(this);
return;
}
return _origInputClick.call(this);
};
// Method 2: Intercept direct click events on file inputs
document.addEventListener('click', function(e) {
var el = e.target;
if (el && el.tagName === 'INPUT' && el.type === 'file') {
e.preventDefault();
e.stopPropagation();
interceptFileInputClick(el);
}
}, true);
// Method 3: Override showOpenFilePicker if it exists (modern File System Access API)
if (window.showOpenFilePicker) {
var _origShowOpenFilePicker = window.showOpenFilePicker;
window.showOpenFilePicker = function(options) {
log('[File] showOpenFilePicker intercepted');
options = options || {};
var accept = '';
if (options.types && options.types.length > 0) {
var exts = [];
options.types.forEach(function(t) {
if (t.accept) {
Object.keys(t.accept).forEach(function(mime) {
t.accept[mime].forEach(function(ext) {
exts.push(ext);
});
});
}
});
accept = exts.join(',');
}
return new Promise(function(resolve, reject) {
request('selectFile', { title: 'Select File', accept: accept }).then(function(result) {
if (result && result.success && result.base64) {
var byteString = atob(result.base64);
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
var blob = new Blob([ab], { type: result.mimeType || 'application/octet-stream' });
// Create a mock FileSystemFileHandle
var mockHandle = {
kind: 'file',
name: result.filename,
getFile: function() {
return Promise.resolve(new File([blob], result.filename, { type: result.mimeType }));
}
};
resolve([mockHandle]);
} else if (result && result.cancelled) {
reject(new DOMException('The user aborted a request.', 'AbortError'));
} else {
reject(new Error(result && result.error || 'File selection failed'));
}
}).catch(reject);
});
};
}
log('[Bridge] File input interceptor installed');
})();
})();
</script>`
}
// shutdownProxyServer shuts down the proxy server for a given SCID
func shutdownProxyServer(scid string) {
proxyRegistry.Lock()
defer proxyRegistry.Unlock()