Repository navigation
Expand file tree
/
Copy pathmain.rs
More file actions
1728 lines (1633 loc) · 79.6 KB
/
Copy pathmain.rs
File metadata and controls
1728 lines (1633 loc) · 79.6 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
// navette — the browser for agents.
// One binary, two modes: `navette serve` (HTTP on loopback) and `navette mcp`
// (MCP stdio for agent hosts). The engine is the OS's native WebView;
// navette is only the glue. No Chromium, no download.
#[cfg(target_os = "macos")]
#[path = "backend_macos.rs"]
mod backend;
#[cfg(any(target_os = "windows", target_os = "linux"))]
#[path = "backend_wry.rs"]
mod backend;
#[cfg(not(any(target_os = "macos", target_os = "windows", target_os = "linux")))]
#[path = "backend_stub.rs"]
mod backend;
mod mcp;
mod webviewkit;
mod keystore;
use serde_json::{json, Value};
use std::io::{Read, Write};
use std::net::{TcpListener, TcpStream};
use std::process::Command;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::OnceLock;
use std::thread;
use std::time::{Duration, Instant};
// The active backend's kit handle — every engine call in the product layer
// goes through the WebviewKit trait (surface compile-enforced per backend).
// Only the boot lifecycle stays on backend::* free functions: it genuinely
// differs per platform (app_init/app_run vs run_main_loop).
static KIT: backend::Kit = backend::Kit;
use webviewkit::WebviewKit;
static T0: OnceLock<Instant> = OnceLock::new();
pub static PORT: OnceLock<u16> = OnceLock::new();
static TOKEN: OnceLock<String> = OnceLock::new();
// Extra Host headers accepted by the rebinding guard (--allow-host, repeatable).
static ALLOWED_HOSTS: OnceLock<Vec<String>> = OnceLock::new();
#[cfg(unix)]
extern "C" fn graceful_term(_sig: i32) {
std::process::exit(0);
}
#[cfg(unix)]
fn install_graceful_signals() {
unsafe {
libc::signal(libc::SIGTERM, graceful_term as usize);
libc::signal(libc::SIGINT, graceful_term as usize);
}
}
static LOGGED_FIRST_NAV: AtomicBool = AtomicBool::new(false);
// MARK: - JS snippets (shared across backends; keep in sync with the reference)
fn click_js(sel: &str) -> String {
format!(
r#"(function(sel){{
const el = document.querySelector(sel);
if (!el) return 'MISSING';
const r = el.getBoundingClientRect();
const base = {{bubbles:true, cancelable:true, view:window, clientX:r.x + r.width/2, clientY:r.y + r.height/2}};
const po = Object.assign({{pointerId:1, pointerType:'mouse', isPrimary:true, width:1, height:1, pressure:0}}, base);
// Pointer events first: Radix/HeadlessUI menus listen for pointerdown and
// never see a bare mousedown (found the hard way on daily.dev's kebab menu).
el.dispatchEvent(new PointerEvent('pointerover', po));
el.dispatchEvent(new PointerEvent('pointerdown', po));
el.dispatchEvent(new MouseEvent('mousedown', base));
el.dispatchEvent(new PointerEvent('pointerup', po));
el.dispatchEvent(new MouseEvent('mouseup', base));
if (el instanceof HTMLElement) {{ el.click(); }} else {{ el.dispatchEvent(new MouseEvent('click', base)); }}
return 'OK';
}})({sel})"#
)
}
fn type_js(sel: &str, val: &str) -> String {
format!(
r#"(function(sel, val){{
const el = document.querySelector(sel);
if (!el) return 'MISSING';
el.focus();
const proto = (el instanceof HTMLTextAreaElement) ? HTMLTextAreaElement.prototype
: (el instanceof HTMLInputElement) ? HTMLInputElement.prototype : null;
if (proto) {{
const d = Object.getOwnPropertyDescriptor(proto, 'value');
if (d && d.set) {{ d.set.call(el, val); }} else {{ el.value = val; }}
}} else {{ el.textContent = val; }}
el.dispatchEvent(new Event('input', {{bubbles:true}}));
el.dispatchEvent(new Event('change', {{bubbles:true}}));
return 'OK';
}})({sel}, {val})"#,
sel = sel,
val = val
)
}
// /login fill: finds the visible password field, the nearest text/email/tel
// input before it in the same form, and fills both with the React-safe
// native setter. The credentials arrive as JSON-escaped JS string literals
// and are never logged — the eval payload is not written anywhere.
fn login_fill_js(user: &str, pass: &str) -> String {
format!(
r#"(function(u,p){{
var vis = function(el){{ var r = el.getBoundingClientRect(); var s = getComputedStyle(el);
return !el.disabled && !el.readOnly && r.width > 0 && r.height > 0 && s.visibility !== 'hidden' && s.display !== 'none'; }};
var pw = Array.prototype.filter.call(document.querySelectorAll('input[type=password]'), vis)[0];
if (!pw) return JSON.stringify({{ok:false, reason:'no visible password field'}});
var scope = pw.closest('form') || document.body;
function set(el, val){{ el.focus();
var d = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value');
if (d && d.set) d.set.call(el, val); else el.value = val;
el.dispatchEvent(new Event('input', {{bubbles:true}}));
el.dispatchEvent(new Event('change', {{bubbles:true}})); }}
var filled = [];
var inputs = scope.querySelectorAll('input');
var user = null;
for (var i = Array.prototype.indexOf.call(inputs, pw) - 1; i >= 0; i--) {{
var t = (inputs[i].type || 'text').toLowerCase();
if ((t === 'text' || t === 'email' || t === 'tel') && vis(inputs[i])) {{ user = inputs[i]; break; }} }}
if (user) {{ set(user, u); filled.push('username'); }}
set(pw, p); filled.push('password');
return JSON.stringify({{ok:true, filled:filled}});
}})({u}, {p})"#,
u = user,
p = pass
)
}
// Two-step login flows (email → Continuer → password) split the screens:
// step 1 fills the one visible identifier field and clicks the continue
// control; the route then re-probes for the password step.
fn login_user_step_js(user: &str) -> String {
format!(
r#"(function(u){{
var vis = function(el){{ var r = el.getBoundingClientRect(); var s = getComputedStyle(el);
return !el.disabled && !el.readOnly && r.width > 0 && r.height > 0 && s.visibility !== 'hidden' && s.display !== 'none'; }};
function set(el, val){{ el.focus();
var d = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value');
if (d && d.set) d.set.call(el, val); else el.value = val;
el.dispatchEvent(new Event('input', {{bubbles:true}}));
el.dispatchEvent(new Event('change', {{bubbles:true}})); }}
var id = Array.prototype.filter.call(
document.querySelectorAll('input[type=email],input[type=text],input[type=tel]'), vis)[0];
if (!id) return JSON.stringify({{ok:false, reason:'no visible identifier field (and no password field) — 2FA or logged in already'}});
set(id, u);
var scope = id.closest('form') || document.body;
var btn = Array.prototype.filter.call(
scope.querySelectorAll('button[type=submit],input[type=submit],button:not([type])'),
function(b){{ var r = b.getBoundingClientRect(); return r.width > 0 && r.height > 0; }})[0];
if (!btn) {{
var re = /continuer|connexion|connecter|log[\s-]?in|sign[\s-]?in|submit|entrer|suivant|next/i;
btn = Array.prototype.filter.call(scope.querySelectorAll('button,input[type=button]'),
function(b){{ var t = b.textContent || b.value || ''; var r = b.getBoundingClientRect();
return r.width > 0 && r.height > 0 && re.test(t); }})[0];
}}
if (!btn) return JSON.stringify({{ok:false, reason:'identifier filled but no continue control found'}});
var r = btn.getBoundingClientRect();
var base = {{bubbles:true, cancelable:true, view:window, clientX:r.x + r.width/2, clientY:r.y + r.height/2}};
var po = Object.assign({{pointerId:1, pointerType:'mouse', isPrimary:true}}, base);
btn.dispatchEvent(new PointerEvent('pointerdown', po));
btn.dispatchEvent(new MouseEvent('mousedown', base));
btn.dispatchEvent(new PointerEvent('pointerup', po));
btn.dispatchEvent(new MouseEvent('mouseup', base));
if (btn instanceof HTMLElement) {{ btn.click(); }} else {{ btn.dispatchEvent(new MouseEvent('click', base)); }}
return JSON.stringify({{ok:true, filled:['username'], button:((btn.textContent||btn.value||'').trim().slice(0,40))}});
}})({u})"#,
u = user
)
}
fn login_password_step_js(pass: &str) -> String {
format!(
r#"(function(p){{
var vis = function(el){{ var r = el.getBoundingClientRect(); var s = getComputedStyle(el);
return !el.disabled && !el.readOnly && r.width > 0 && r.height > 0 && s.visibility !== 'hidden' && s.display !== 'none'; }};
var pw = Array.prototype.filter.call(document.querySelectorAll('input[type=password]'), vis)[0];
if (!pw) return JSON.stringify({{ok:false, reason:'still no visible password field — 2FA or wrong-credential page'}});
pw.focus();
var d = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value');
if (d && d.set) d.set.call(pw, p); else pw.value = p;
pw.dispatchEvent(new Event('input', {{bubbles:true}}));
pw.dispatchEvent(new Event('change', {{bubbles:true}}));
var scope = pw.closest('form') || document.body;
var btn = Array.prototype.filter.call(
scope.querySelectorAll('button[type=submit],input[type=submit],button:not([type])'),
function(b){{ var r = b.getBoundingClientRect(); return r.width > 0 && r.height > 0; }})[0];
if (!btn) {{
var re = /continuer|connexion|connecter|log[\s-]?in|sign[\s-]?in|submit|entrer/i;
btn = Array.prototype.filter.call(scope.querySelectorAll('button,input[type=button]'),
function(b){{ var t = b.textContent || b.value || ''; var r = b.getBoundingClientRect();
return r.width > 0 && r.height > 0 && re.test(t); }})[0];
}}
if (!btn) return JSON.stringify({{ok:true, filled:['password'], button:null, reason:'no submit control — click it yourself'}});
var r = btn.getBoundingClientRect();
var base = {{bubbles:true, cancelable:true, view:window, clientX:r.x + r.width/2, clientY:r.y + r.height/2}};
var po = Object.assign({{pointerId:1, pointerType:'mouse', isPrimary:true}}, base);
btn.dispatchEvent(new PointerEvent('pointerdown', po));
btn.dispatchEvent(new MouseEvent('mousedown', base));
btn.dispatchEvent(new PointerEvent('pointerup', po));
btn.dispatchEvent(new MouseEvent('mouseup', base));
if (btn instanceof HTMLElement) {{ btn.click(); }} else {{ btn.dispatchEvent(new MouseEvent('click', base)); }}
return JSON.stringify({{ok:true, filled:['password'], button:((btn.textContent||btn.value||'').trim().slice(0,40))}});
}})({p})"#,
p = pass
)
}
// /login submit: the form's first visible submit control, dispatched with
// the same pointer+mouse sequence as /click (Radix-style UIs included).
// Fallback for type="button" forms (leboncoin's auth uses "Continuer"):
// the first visible button whose text reads like a submit action.
fn login_submit_js() -> String {
r#"(function(){
var pw = document.querySelector('input[type=password]');
if (!pw) return JSON.stringify({ok:false, reason:'password field gone — the form may have submitted already'});
var scope = pw.closest('form') || document.body;
var btn = Array.prototype.filter.call(
scope.querySelectorAll('button[type=submit],input[type=submit],button:not([type])'),
function(b){ var r = b.getBoundingClientRect(); return r.width > 0 && r.height > 0; })[0];
if (!btn) {
var re = /continuer|connexion|connecter|log[\s-]?in|sign[\s-]?in|submit|entrer/i;
btn = Array.prototype.filter.call(scope.querySelectorAll('button,input[type=button]'),
function(b){ var t = b.textContent || b.value || ''; var r = b.getBoundingClientRect();
return r.width > 0 && r.height > 0 && re.test(t); })[0];
}
if (!btn) return JSON.stringify({ok:false, reason:'no visible submit control — click it yourself'});
var r = btn.getBoundingClientRect();
var base = {bubbles:true, cancelable:true, view:window, clientX:r.x + r.width/2, clientY:r.y + r.height/2};
var po = Object.assign({pointerId:1, pointerType:'mouse', isPrimary:true}, base);
btn.dispatchEvent(new PointerEvent('pointerdown', po));
btn.dispatchEvent(new MouseEvent('mousedown', base));
btn.dispatchEvent(new PointerEvent('pointerup', po));
btn.dispatchEvent(new MouseEvent('mouseup', base));
if (btn instanceof HTMLElement) { btn.click(); } else { btn.dispatchEvent(new MouseEvent('click', base)); }
return JSON.stringify({ok:true, button:((btn.textContent||btn.value||'').trim().slice(0,40))});
})()"#
.to_string()
}
/// eval_js results may arrive JSON-encoded or bare (bridge-dependent) —
/// accept both shapes and return the plain string.
fn eval_str<K: webviewkit::WebviewKit>(kit: &K, s: &K::SessionRef, js: &str) -> Option<String> {
kit.eval_js(s, js).ok().map(|r| {
serde_json::from_str::<Value>(&r)
.ok()
.and_then(|v| v.as_str().map(|x| x.to_string()))
.unwrap_or(r)
})
}
pub const MARKDOWN_JS: &str = r#"(function(){ document.querySelectorAll('script,style,noscript,svg,iframe,template').forEach(e => e.remove());
const txt = e => (e.innerText || '').replace(/\s+/g, ' ').trim();
const out = [];
const walk = el => {
for (const n of el.children) {
const t = n.tagName.toLowerCase();
if (t === 'h1') out.push('\n# ' + txt(n));
else if (t === 'h2') out.push('\n## ' + txt(n));
else if (t === 'h3') out.push('\n### ' + txt(n));
else if (t === 'h4' || t === 'h5' || t === 'h6') out.push('\n#### ' + txt(n));
else if (t === 'p') out.push('\n' + txt(n));
else if (t === 'li') out.push('- ' + txt(n));
else if (t === 'pre') out.push('\n```\n' + n.innerText + '\n```');
else if (t === 'blockquote') out.push('> ' + txt(n));
else if (t === 'a' && n.getAttribute('href')) out.push('[' + txt(n) + '](' + n.href + ')');
else if (n.children.length) walk(n);
else if (txt(n)) out.push(txt(n));
}
};
walk(document.body);
return out.join('\n').replace(/\n{3,}/g, '\n\n').trim();
})()"#;
fn combined_content_js(format: &str) -> String {
match format {
"text" => "(function(){return JSON.stringify({t:document.title,c:document.body.innerText});})()".into(),
_ => format!(
"(function(){{return JSON.stringify({{t:document.title,c:({MD})}});}})()",
MD = MARKDOWN_JS
),
}
}
fn jstr(s: &str) -> String {
serde_json::to_string(s).unwrap_or_else(|_| "\"\"".into())
}
/// Constant-time string equality for token checks — no early exit on the
/// first differing byte. (Length still leaks via iteration count, the
/// standard accepted residual.)
fn ct_eq(a: &str, b: &str) -> bool {
let (a, b) = (a.as_bytes(), b.as_bytes());
let n = a.len().max(b.len());
let mut acc = 0u8;
for i in 0..n {
acc |= a.get(i).copied().unwrap_or(0) ^ b.get(i).copied().unwrap_or(0);
}
acc == 0
}
/// Proxy URLs may carry credentials (http://user:pass@host) — never log them.
fn redact_proxy(u: &str) -> String {
match u.split_once("://") {
Some((scheme, rest)) => match rest.rsplit_once('@') {
Some((_, tail)) => format!("{scheme}://***@{tail}"),
None => u.to_string(),
},
None => u.to_string(),
}
}
// MARK: - HTTP plumbing
struct Req {
method: String,
path: String,
body: Vec<u8>,
headers: Vec<(String, String)>,
}
fn parse_request(data: &[u8]) -> Option<Req> {
let idx = data.windows(4).position(|w| w == b"\r\n\r\n")?;
let head = String::from_utf8_lossy(&data[..idx]).to_string();
let mut lines = head.split("\r\n");
let first = lines.next()?.to_string();
let mut cl = 0usize;
let mut headers: Vec<(String, String)> = Vec::new();
for l in lines {
let mut kv = l.splitn(2, ':');
if let (Some(k), Some(v)) = (kv.next(), kv.next()) {
headers.push((k.trim().to_ascii_lowercase(), v.trim().to_string()));
if k.trim().eq_ignore_ascii_case("content-length") {
cl = v.trim().parse().unwrap_or(0);
}
}
}
let body_start = idx + 4;
if data.len() < body_start + cl {
return None;
}
let mut parts = first.split_whitespace();
let method = parts.next()?.to_string();
let path = parts.next()?.to_string();
Some(Req {
method,
path,
body: data[body_start..body_start + cl].to_vec(),
headers,
})
}
fn respond(fd: &mut TcpStream, status: u16, reason: &str, content_type: &str, body: &[u8]) {
let head = format!(
"HTTP/1.1 {status} {reason}\r\nContent-Type: {ct}\r\nContent-Length: {n}\r\nConnection: close\r\n\r\n",
status = status,
reason = reason,
ct = content_type,
n = body.len()
);
let _ = fd.write_all(head.as_bytes());
let _ = fd.write_all(body);
let _ = fd.flush();
let _ = fd.shutdown(std::net::Shutdown::Both);
}
fn json_bytes(v: &Value) -> Vec<u8> {
serde_json::to_vec_pretty(v).unwrap_or_else(|_| b"{}".to_vec())
}
fn err_data(msg: &str) -> Value {
json!({ "ok": false, "error": msg })
}
fn serve_fd(mut stream: TcpStream) {
let mut buf: Vec<u8> = Vec::new();
let mut chunk = [0u8; 65536];
loop {
if let Some(req) = parse_request(&buf) {
route(&mut stream, req);
return;
}
if buf.len() > 10_000_000 {
return;
}
match stream.read(&mut chunk) {
Ok(0) | Err(_) => return,
Ok(n) => buf.extend_from_slice(&chunk[..n]),
}
}
}
// MARK: - Routes
fn route(fd: &mut TcpStream, req: Req) {
// Optional auth (--token): every route except /health requires
// `Authorization: Bearer <secret>` or `X-Navette-Token: <secret>`.
// DNS-rebinding hardening: this API is loopback-only; a public site
// that rebinds its DNS to 127.0.0.1 must not reach it. Only requests
// addressed to a local Host are served (browsers' Private Network
// Access blocks most of this already — this is the belt to that).
// --allow-host NAME extends the accepted Host headers for container
// topologies (n8n → navette across a docker network): opt-in per name,
// and the docs require pairing it with --token in that case.
let host_local = req
.headers
.iter()
.find(|(k, _)| k == "host")
.map(|(_, v)| {
let h = v.split(':').next().unwrap_or("").trim();
h == "127.0.0.1" || h == "localhost" || h == "[::1]" || ALLOWED_HOSTS.get().is_some_and(|a| a.iter().any(|x| x == h))
})
.unwrap_or(false);
let path_ok = req.path.split('?').next() == Some("/health");
if let Some(tok) = TOKEN.get() {
let presented = req
.headers
.iter()
.find(|(k, _)| k == "authorization" || k == "x-navette-token")
.map(|(_, v)| {
let v = v.trim();
v.strip_prefix("Bearer ").unwrap_or(v)
});
if !path_ok && !presented.is_some_and(|p| ct_eq(p, tok.as_str())) {
respond(
fd,
401,
"Unauthorized",
"application/json",
&json_bytes(&err_data("missing or invalid token — pass the --token value via Authorization: Bearer")),
);
return;
}
}
if !path_ok && !host_local {
respond(
fd,
403,
"Forbidden",
"application/json",
&json_bytes(&err_data("non-local Host header — this API is loopback-only (DNS-rebinding guard)")),
);
return;
}
let path = req.path.split('?').next().unwrap_or("/").to_string();
let j: Value = serde_json::from_slice(&req.body).unwrap_or(json!({}));
let name = j.get("session").and_then(|v| v.as_str()).unwrap_or("default").to_string();
match (req.method.as_str(), path.as_str()) {
("GET", "/health") => {
respond(fd, 200, "OK", "application/json",
&json_bytes(&json!({"ok": true, "name": "navette", "engine": "system WebView"})));
}
("GET", "/sessions") => {
respond(fd, 200, "OK", "application/json", &json_bytes(&KIT.list_sessions()));
}
("POST", "/sessions/close") => {
KIT.close_session(&name);
respond(fd, 200, "OK", "application/json", &json_bytes(&json!({"ok": true})));
}
("POST", "/navigate") => {
let url = j.get("url").and_then(|v| v.as_str()).unwrap_or("").to_string();
if url.is_empty() {
respond(fd, 400, "Bad Request", "application/json", &json_bytes(&err_data("bad url")));
return;
}
let with_content = j.get("with_content").and_then(|v| v.as_bool()).unwrap_or(false);
let format = j.get("format").and_then(|v| v.as_str()).unwrap_or("markdown").to_string();
let s = { let n = name.clone(); KIT.run_get_or_create(&n) };
// with_content: the extraction is FOLDED into the didFinish
// callback — one main-loop hop total, zero after the load.
let after = if with_content {
Some(combined_content_js(&format))
} else {
None
};
match KIT.navigate(&s, &url, after) {
Err(e) => respond(fd, 502, "Bad Gateway", "application/json", &json_bytes(&err_data(&e))),
Ok(out) => {
let mut payload = json!({"ok": true, "session": name, "url": url, "title": ""});
if with_content {
match serde_json::from_str::<Value>(&out) {
Ok(v) if v.is_string() => {
// wry serializes the fold result, which may
// itself be a JSON string — decode twice.
let inner = v.as_str().unwrap();
match serde_json::from_str::<Value>(inner) {
Ok(v2) => {
payload["title"] = v2.get("t").cloned().unwrap_or(json!(""));
payload["content"] = v2.get("c").cloned().unwrap_or(json!(""));
payload["format"] = json!(format);
}
Err(_) => payload["title"] = json!(out),
}
}
Ok(v) => {
payload["title"] = v.get("t").cloned().unwrap_or(json!(""));
payload["content"] = v.get("c").cloned().unwrap_or(json!(""));
payload["format"] = json!(format);
payload["raw_fold"] = json!(out);
if let Some(err) = v.get("__nav_error") {
payload["fold_error"] = err.clone();
}
}
Err(_) => payload["title"] = json!(out),
}
// A fold can come back empty when it landed in a stale
// page context (cold first navigate under headless CI,
// WebKitGTK web-process swap) or on a Chromium error
// page. Re-extract on the now-current page via the eval
// shim before giving up.
let t_empty = payload["title"].as_str().map(|s| s.is_empty()).unwrap_or(true);
let c_empty = payload["content"].as_str().map(|s| s.is_empty()).unwrap_or(true);
if t_empty && c_empty {
let deadline = std::time::Instant::now() + Duration::from_secs(15);
let snippet = combined_content_js(&format);
while std::time::Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(250));
let Ok(r) = KIT.eval_js(&s, &snippet) else { continue };
let decoded = serde_json::from_str::<Value>(&r).ok().and_then(|v| {
if v.is_string() {
serde_json::from_str::<Value>(v.as_str().unwrap()).ok()
} else {
Some(v)
}
});
if let Some(v2) = decoded {
let t = v2.get("t").and_then(|x| x.as_str()).unwrap_or("");
let c = v2.get("c").and_then(|x| x.as_str()).unwrap_or("");
if !t.is_empty() || !c.is_empty() {
payload["title"] = json!(t);
payload["content"] = json!(c);
payload["format"] = json!(format);
payload["retried"] = json!(true);
break;
}
}
}
}
} else if let Ok(t) = KIT.eval_js(&s, "document.title") {
payload["title"] = json!(t);
}
respond(fd, 200, "OK", "application/json", &json_bytes(&payload));
}
}
if !LOGGED_FIRST_NAV.swap(true, Ordering::Relaxed) {
if let Some(t0) = T0.get() {
eprintln!("[navette] +{} ms — first navigate complete", t0.elapsed().as_millis());
}
}
}
("POST", "/read") => {
let format = j.get("format").and_then(|v| v.as_str()).unwrap_or("markdown").to_string();
let s = { let n = name.clone(); KIT.run_get_or_create(&n) };
let js: String = match format.as_str() {
"text" => "document.body.innerText".into(),
"html" => "document.documentElement.outerHTML".into(),
_ => MARKDOWN_JS.into(),
};
match KIT.eval_js(&s, &js) {
Ok(text) => {
// eval_js returns the value JSON-encoded — unwrap strings
let content = serde_json::from_str::<Value>(&text)
.ok()
.and_then(|v| v.as_str().map(|s| s.to_string()))
.unwrap_or(text);
let body = if content.len() > 3_000_000 {
json!({"ok": true, "content": content.chars().take(1_000_000).collect::<String>(), "truncated": true})
} else {
json!({"ok": true, "format": format, "content": content})
};
respond(fd, 200, "OK", "application/json", &json_bytes(&body));
}
Err(e) => respond(fd, 500, "Internal Server Error", "application/json", &json_bytes(&err_data(&e))),
}
}
("POST", "/screenshot") => {
let s = { let n = name.clone(); KIT.run_get_or_create(&n) };
match KIT.screenshot(&s) {
Ok(png) => respond(fd, 200, "OK", "image/png", &png),
Err(e) => respond(fd, 500, "Internal Server Error", "application/json", &json_bytes(&err_data(&e))),
}
}
("POST", "/click") => {
let sel = j.get("selector").and_then(|v| v.as_str()).unwrap_or("").to_string();
let wait_nav = j.get("wait_navigation").and_then(|v| v.as_bool()).unwrap_or(false);
let s = { let n = name.clone(); KIT.run_get_or_create(&n) };
let clicked = KIT.eval_js(&s, &click_js(&jstr(&sel)));
if wait_nav {
// The click may have started a form-POST navigation: settle.
if clicked.is_ok() {
KIT.wait_settle(&s);
}
}
match clicked {
// eval_js returns the value JSON-encoded ("OK" arrives quoted)
Ok(v) => {
let dec: Value = serde_json::from_str(&v).unwrap_or(json!(v));
let hit = dec.as_str() == Some("OK");
respond(fd, 200, "OK", "application/json",
&json_bytes(&json!({"ok": hit, "result": v})))
}
Err(e) => respond(fd, 500, "Internal Server Error", "application/json", &json_bytes(&err_data(&e))),
}
}
("POST", "/type") => {
let sel = j.get("selector").and_then(|v| v.as_str()).unwrap_or("").to_string();
let val = j.get("value").and_then(|v| v.as_str()).unwrap_or("").to_string();
let s = { let n = name.clone(); KIT.run_get_or_create(&n) };
match KIT.eval_js(&s, &type_js(&jstr(&sel), &jstr(&val))) {
Ok(v) => {
let dec: Value = serde_json::from_str(&v).unwrap_or(json!(v));
let hit = dec.as_str() == Some("OK");
respond(fd, 200, "OK", "application/json",
&json_bytes(&json!({"ok": hit, "result": v})))
}
Err(e) => respond(fd, 500, "Internal Server Error", "application/json", &json_bytes(&err_data(&e))),
}
}
("POST", "/evaluate") => {
let js = j.get("js").and_then(|v| v.as_str()).unwrap_or("").to_string();
let s = { let n = name.clone(); KIT.run_get_or_create(&n) };
match KIT.eval_js(&s, &js) {
Ok(v) => respond(fd, 200, "OK", "application/json", &json_bytes(&json!({"ok": true, "result": v}))),
Err(e) => respond(fd, 500, "Internal Server Error", "application/json", &json_bytes(&err_data(&e))),
}
}
("POST", "/wait") => {
let sel = j.get("selector").and_then(|v| v.as_str()).unwrap_or("").to_string();
let ms = j.get("ms").and_then(|v| v.as_u64()).unwrap_or(10_000);
let s = { let n = name.clone(); KIT.run_get_or_create(&n) };
// String() coerces the bool: the macOS bridge stringifies an
// NSNumber bool as "1"/"0" (description), the wry IPC path as
// "true"/"false" — accept both shapes.
let probe = format!("String(!!document.querySelector({}))", jstr(&sel));
let deadline = Instant::now() + Duration::from_millis(ms);
let mut found = false;
while Instant::now() < deadline {
if let Ok(v) = KIT.eval_js(&s, &probe) {
if v == "true" || v == "1" {
found = true;
break;
}
}
std::thread::sleep(Duration::from_millis(150));
}
respond(fd, if found { 200 } else { 408 }, if found { "OK" } else { "Request Timeout" },
"application/json",
&json_bytes(&json!({"ok": found, "selector": sel})));
}
("POST", "/sessions/state") => {
let s = { let n = name.clone(); KIT.run_get_or_create(&n) };
match KIT.export_cookies(&s) {
Ok(v) => match j.get("store").and_then(|x| x.as_str()) {
// store mode: the jar goes to the OS keychain inside this
// process and never rides back on the wire — it IS the
// login (#8, stage 1). Only metadata returns.
Some(store) => {
// eval_js may return the value JSON-encoded or bare
// (bridge-dependent) — accept both shapes.
let origin = KIT.eval_js(&s, "location.origin")
.ok()
.map(|r| {
serde_json::from_str::<Value>(&r)
.ok()
.and_then(|v| v.as_str().map(|s| s.to_string()))
.unwrap_or(r)
})
.unwrap_or_default();
let n_cookies = v.get("cookies").and_then(|c| c.as_array()).map(|a| a.len()).unwrap_or(0);
match keystore::save(store, &origin, &v) {
Ok(_) => respond(fd, 200, "OK", "application/json", &json_bytes(&json!({
"ok": true, "stored": store, "origin": origin, "cookies": n_cookies,
}))),
Err(e) => respond(fd, 500, "Internal Server Error", "application/json", &json_bytes(&err_data(&e))),
}
}
None => respond(fd, 200, "OK", "application/json", &json_bytes(&v)),
},
Err(e) => respond(fd, 500, "Internal Server Error", "application/json", &json_bytes(&err_data(&e))),
}
}
("POST", "/sessions/load") => {
let s = { let n = name.clone(); KIT.run_get_or_create(&n) };
// store mode: the jar is resolved from the OS keychain inside
// this process — the request carries a name, never the secret.
let mut body = j.clone();
let mut stored_meta: Option<Value> = None;
if body.get("cookies").map(|c| c.is_null()).unwrap_or(true) {
match body.get("store").and_then(|x| x.as_str()).map(|x| x.to_string()) {
Some(store) => match keystore::load(&store) {
Ok(wrapper) => {
// /sessions/load's contract is FLAT: "cookies" is
// the array, not the {"cookies":[...]} jar.
body["cookies"] = wrapper
.pointer("/jar/cookies")
.cloned()
.unwrap_or(json!([]));
stored_meta = Some(wrapper);
}
Err(e) => {
respond(fd, 404, "Not Found", "application/json", &json_bytes(&err_data(&e)));
return;
}
},
// Was a silent "imported 0" before — now it says so.
None => {
respond(fd, 400, "Bad Request", "application/json",
&json_bytes(&err_data("either cookies or store is required")));
return;
}
}
}
match KIT.import_cookies(&s, &body) {
Ok(n_cookies) => {
let mut payload = json!({"ok": true, "imported": n_cookies});
if let Some(w) = stored_meta {
payload["origin"] = w.get("origin").cloned().unwrap_or(json!(""));
payload["saved_at"] = w.get("saved_at").cloned().unwrap_or(json!(null));
}
respond(fd, 200, "OK", "application/json", &json_bytes(&payload));
}
Err(e) => respond(fd, 500, "Internal Server Error", "application/json", &json_bytes(&err_data(&e))),
}
}
("GET", "/states") => {
match keystore::list() {
Ok(v) => respond(fd, 200, "OK", "application/json", &json_bytes(&v)),
Err(e) => respond(fd, 500, "Internal Server Error", "application/json", &json_bytes(&err_data(&e))),
}
}
("POST", "/states/delete") => {
let store = j.get("name").and_then(|v| v.as_str()).unwrap_or("").to_string();
if store.is_empty() {
respond(fd, 400, "Bad Request", "application/json", &json_bytes(&err_data("name is required")));
return;
}
match keystore::delete(&store) {
Ok(v) => respond(fd, 200, "OK", "application/json", &json_bytes(&v)),
Err(e) => respond(fd, 500, "Internal Server Error", "application/json", &json_bytes(&err_data(&e))),
}
}
// Stage 2 (#8): credentials are SET by a human (`navette creds set`,
// hidden stdin) — but the write goes through the daemon, which owns
// the keychain. No route ever returns a password; there is no
// read-back API at all.
("POST", "/creds/set") => {
let site = j.get("site").and_then(|v| v.as_str()).unwrap_or("").to_string();
let username = j.get("username").and_then(|v| v.as_str()).unwrap_or("").to_string();
let password = j.get("password").and_then(|v| v.as_str()).unwrap_or("").to_string();
if site.is_empty() || username.is_empty() || password.is_empty() {
respond(fd, 400, "Bad Request", "application/json",
&json_bytes(&err_data("site, username and password are required")));
return;
}
let s = { let n = name.clone(); KIT.run_get_or_create(&n) };
// The origin anchor is the session's CURRENT page — never free
// text, so a credential can only be saved while looking at the
// very site it will fill on.
let origin = eval_str(&KIT, &s, "location.origin").unwrap_or_default();
if !origin.starts_with("http") {
respond(fd, 400, "Bad Request", "application/json", &json_bytes(&err_data(
"the session is not on a page — navigate it to the site's login page first; \
the credential binds to that page's exact origin")));
return;
}
match keystore::set_cred(&site, &origin, &username, &password) {
Ok(v) => respond(fd, 200, "OK", "application/json", &json_bytes(&v)),
Err(e) => respond(fd, 500, "Internal Server Error", "application/json", &json_bytes(&err_data(&e))),
}
}
("GET", "/creds") => {
match keystore::list_creds() {
Ok(v) => respond(fd, 200, "OK", "application/json", &json_bytes(&v)),
Err(e) => respond(fd, 500, "Internal Server Error", "application/json", &json_bytes(&err_data(&e))),
}
}
("POST", "/creds/delete") => {
let site = j.get("site").and_then(|v| v.as_str()).unwrap_or("").to_string();
if site.is_empty() {
respond(fd, 400, "Bad Request", "application/json", &json_bytes(&err_data("site is required")));
return;
}
match keystore::delete_cred(&site) {
Ok(v) => respond(fd, 200, "OK", "application/json", &json_bytes(&v)),
Err(e) => respond(fd, 500, "Internal Server Error", "application/json", &json_bytes(&err_data(&e))),
}
}
// The stage-2 payoff: fill + submit the site's login form with the
// stored credential. The agent passes a site NAME; the password is
// resolved inside this process and injected into the page — it never
// appears in the request, the response, or a log line. Refused
// unless the session currently sits on the credential's exact origin
// (a hostile or wrong page can neither harvest it nor aim it).
("POST", "/login") => {
let site = j.get("site").and_then(|v| v.as_str()).unwrap_or("").to_string();
if site.is_empty() {
respond(fd, 400, "Bad Request", "application/json", &json_bytes(&err_data("site is required")));
return;
}
let submit = j.get("submit").and_then(|v| v.as_bool()).unwrap_or(true);
let cred = match keystore::load_cred(&site) {
Ok(c) => c,
Err(e) => {
respond(fd, 404, "Not Found", "application/json", &json_bytes(&err_data(&e)));
return;
}
};
let expected = cred.get("origin").and_then(|v| v.as_str()).unwrap_or("").to_string();
let s = { let n = name.clone(); KIT.run_get_or_create(&n) };
let current = eval_str(&KIT, &s, "location.origin").unwrap_or_default();
if current != expected {
respond(fd, 403, "Forbidden", "application/json", &json_bytes(&json!({
"ok": false,
"error": format!("credential {site:?} is origin-bound — navigate this session to the login page first"),
"expected": expected,
"current": current,
})));
return;
}
let username = cred.get("username").and_then(|v| v.as_str()).unwrap_or("").to_string();
let password = cred.get("password").and_then(|v| v.as_str()).unwrap_or("").to_string();
let mut filled: Vec<Value> = Vec::new();
let mut button = Value::Null;
let mut steps = 1;
// One-screen form first (both fields visible).
let fill = KIT.eval_js(&s, &login_fill_js(&jstr(&username), &jstr(&password)))
.ok()
.and_then(|v| serde_json::from_str::<Value>(&v).ok())
.unwrap_or(json!({}));
if fill.get("ok") == Some(&json!(true)) {
filled = fill.get("filled").and_then(|f| f.as_array()).cloned().unwrap_or_default();
if submit {
if let Ok(v) = KIT.eval_js(&s, &login_submit_js()) {
let sv: Value = serde_json::from_str(&v).unwrap_or(json!({}));
button = sv.get("button").cloned().unwrap_or(Value::Null);
}
KIT.wait_settle(&s);
}
} else {
// Two-step flow (email → Continuer → password): fill the
// identifier, click through, re-probe for the password step.
let step1 = KIT.eval_js(&s, &login_user_step_js(&jstr(&username)))
.ok()
.and_then(|v| serde_json::from_str::<Value>(&v).ok())
.unwrap_or(json!({}));
if step1.get("ok") != Some(&json!(true)) {
let mut payload = json!({"ok": false, "site": site, "origin": expected});
payload["reason"] = step1.get("reason").cloned().unwrap_or(json!("fill failed"));
respond(fd, 200, "OK", "application/json", &json_bytes(&payload));
return;
}
filled = step1.get("filled").and_then(|f| f.as_array()).cloned().unwrap_or_default();
button = step1.get("button").cloned().unwrap_or(Value::Null);
KIT.wait_settle(&s);
thread::sleep(Duration::from_millis(1200));
steps = 2;
if submit {
let step2 = KIT.eval_js(&s, &login_password_step_js(&jstr(&password)))
.ok()
.and_then(|v| serde_json::from_str::<Value>(&v).ok())
.unwrap_or(json!({}));
if step2.get("ok") == Some(&json!(true)) {
if let Some(f) = step2.get("filled").and_then(|f| f.as_array()) {
filled.extend(f.iter().cloned());
}
button = step2.get("button").cloned().unwrap_or(button);
KIT.wait_settle(&s);
} else {
// Honest stop: 2FA, wrong-credential page, etc. The
// username step went through; the human takes over
// via session_show if the page needs them.
let mut payload = json!({"ok": true, "site": site, "origin": expected,
"filled": filled, "submitted": true, "button": button,
"steps": steps, "password_step": false});
payload["reason"] = step2.get("reason").cloned().unwrap_or(json!("password step did not appear"));
payload["url"] = json!(eval_str(&KIT, &s, "location.href").unwrap_or_default());
respond(fd, 200, "OK", "application/json", &json_bytes(&payload));
return;
}
}
}
let url = eval_str(&KIT, &s, "location.href").unwrap_or_default();
respond(fd, 200, "OK", "application/json", &json_bytes(&json!({
"ok": true, "site": site, "origin": expected,
"filled": filled, "submitted": submit, "button": button, "steps": steps, "url": url,
})));
}
("POST", "/sessions/viewport") => {
let s = { let n = name.clone(); KIT.run_get_or_create(&n) };
let w = j.get("width").and_then(|v| v.as_u64()).unwrap_or(1280) as u32;
let h = j.get("height").and_then(|v| v.as_u64()).unwrap_or(800) as u32;
match KIT.set_viewport(&s, w, h) {
Ok(()) => respond(fd, 200, "OK", "application/json",
&json_bytes(&json!({"ok": true, "width": w, "height": h}))),
Err(e) => respond(fd, 500, "Internal Server Error", "application/json", &json_bytes(&err_data(&e))),
}
}
("POST", "/sessions/show") => {
let s = { let n = name.clone(); KIT.run_get_or_create(&n) };
match KIT.show_window(&s) {
Ok(()) => respond(fd, 200, "OK", "application/json",
&json_bytes(&json!({"ok": true, "visible": true}))),
Err(e) => respond(fd, 500, "Internal Server Error", "application/json", &json_bytes(&err_data(&e))),
}
}
("POST", "/sessions/hide") => {
let s = { let n = name.clone(); KIT.run_get_or_create(&n) };
match KIT.hide_window(&s) {
Ok(()) => respond(fd, 200, "OK", "application/json",
&json_bytes(&json!({"ok": true, "visible": false}))),
Err(e) => respond(fd, 500, "Internal Server Error", "application/json", &json_bytes(&err_data(&e))),
}
}
("POST", "/upload") => {
let s = { let n = name.clone(); KIT.run_get_or_create(&n) };
let sel = j.get("selector").and_then(|v| v.as_str()).unwrap_or("");
let filename = j.get("filename").and_then(|v| v.as_str()).unwrap_or("upload.bin");
let mime = j.get("mime").and_then(|v| v.as_str()).unwrap_or("application/octet-stream");
let b64 = j.get("content_base64").and_then(|v| v.as_str()).unwrap_or("");
if sel.is_empty() {
respond(fd, 400, "Bad Request", "application/json", &json_bytes(&err_data("selector is required")));
return;
}
let sel_esc = jstr(sel);
let name_esc = jstr(filename);
let mime_esc = jstr(mime);
// A FileList cannot be forged directly, but input.files IS
// assignable from a DataTransfer built in the page — the one
// engine-agnostic way to fill a file input without OS dialogs.
let js = format!(
"(function(){{var el=document.querySelector({sel});if(!el)return JSON.stringify({{ok:false,err:'no element'}});if(String(el.type).toLowerCase()!=='file')return JSON.stringify({{ok:false,err:'element is not an <input type=file>'}});var bin=atob('{b64}');var bytes=new Uint8Array(bin.length);for(var i=0;i<bin.length;i++)bytes[i]=bin.charCodeAt(i);var f=new File([bytes],{name},{{type:{mime}}});var dt=new DataTransfer();dt.items.add(f);el.files=dt.files;el.dispatchEvent(new Event('input',{{bubbles:true}}));el.dispatchEvent(new Event('change',{{bubbles:true}}));var names=Array.prototype.map.call(el.files,function(x){{return x.name+':'+x.size}}).join(',');return JSON.stringify({{ok:true,files:names}})}})()",
sel = sel_esc, b64 = b64, name = name_esc, mime = mime_esc
);
match KIT.eval_js(&s, &js) {
Ok(v) => respond(fd, 200, "OK", "application/json", &json_bytes(&json!({"ok": true, "result": v}))),
Err(e) => respond(fd, 500, "Internal Server Error", "application/json", &json_bytes(&err_data(&e))),
}
}
("POST", "/scroll") => {
let s = { let n = name.clone(); KIT.run_get_or_create(&n) };
let sel = j.get("selector").and_then(|v| v.as_str()).unwrap_or("");
let y = j.get("y").and_then(|v| v.as_f64()).unwrap_or(0.0);
let js = if !sel.is_empty() {
let sel_esc = jstr(sel);
format!(
"(function(){{var el=document.querySelector({sel});if(!el)return JSON.stringify({{ok:false,err:'no element'}});el.scrollIntoView({{block:'center'}});return JSON.stringify({{ok:true,y:window.scrollY}})}})()",
sel = sel_esc
)
} else {
format!(
"(function(){{window.scrollTo(0,{y});return JSON.stringify({{ok:true,y:window.scrollY,max:document.documentElement.scrollHeight-window.innerHeight}})}})()",
y = y
)
};
match KIT.eval_js(&s, &js) {
Ok(v) => respond(fd, 200, "OK", "application/json", &json_bytes(&json!({"ok": true, "result": v}))),
Err(e) => respond(fd, 500, "Internal Server Error", "application/json", &json_bytes(&err_data(&e))),
}
}
("POST", "/hover") => {
let s = { let n = name.clone(); KIT.run_get_or_create(&n) };
let sel = j.get("selector").and_then(|v| v.as_str()).unwrap_or("");
let sel_esc = jstr(sel);
let js = format!(
"(function(){{var el=document.querySelector({sel});if(!el)return JSON.stringify({{ok:false,err:'no element'}});var r=el.getBoundingClientRect();var o={{clientX:r.left+r.width/2,clientY:r.top+r.height/2,bubbles:true,cancelable:true,view:window,buttons:0}};['mouseover','mousemove'].forEach(function(t){{el.dispatchEvent(new MouseEvent(t,o))}});return JSON.stringify({{ok:true}})}})()",
sel = sel_esc
);
match KIT.eval_js(&s, &js) {
Ok(v) => respond(fd, 200, "OK", "application/json", &json_bytes(&json!({"ok": true, "result": v}))),
Err(e) => respond(fd, 500, "Internal Server Error", "application/json", &json_bytes(&err_data(&e))),
}