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
use std::sync::{Arc, Mutex};
use std::time::Instant;
use wasmtime::{Engine, Extern, Linker, Memory, Module, Store, TypedFunc};
use crate::bridge::Bridge;
use crate::config::SandboxConfig;
use crate::context::{ContextId, MessageBus};
use crate::error::{Error, Result};
use crate::observation::{Observation, ResourceLimitKind};
/// Embedded QuickJS WASM binary — compiled from stripped C source.
const QUICKJS_WASM: &[u8] = include_bytes!("../quickjs.wasm");
/// The pre-compiled QuickJS WASM module.
///
/// Created once, reused across executions. Thread-safe.
/// Each execution instantiates a fresh WASM instance from this module.
pub struct CompiledModule {
engine: Engine,
module: Module,
}
impl CompiledModule {
/// Compile the embedded `QuickJS` WASM binary.
///
/// This is the expensive operation (~10-50ms). Do it once at startup.
/// For repeated runs, use `load_cached()` with a serialized module.
///
/// # Errors
///
/// Returns an error if the WASM fails to compile or instantiate.
pub fn new() -> Result<Self> {
let mut engine_config = wasmtime::Config::new();
engine_config.consume_fuel(true);
engine_config.wasm_bulk_memory(true);
let engine =
Engine::new(&engine_config).map_err(|e| Error::WasmInit(format!("engine: {e}")))?;
let module = Module::new(&engine, QUICKJS_WASM)
.map_err(|e| Error::WasmInit(format!("module: {e}")))?;
Ok(Self { engine, module })
}
/// Serialize the compiled module to bytes for caching.
///
/// Save the result to disk. On next startup, use `load_cached()`
/// to skip compilation (~50ms → ~1ms).
///
/// # Errors
///
/// Returns an error if the underlying module serialization fails.
pub fn serialize(&self) -> Result<Vec<u8>> {
self.module
.serialize()
.map_err(|e| Error::WasmInit(format!("serialize: {e}")))
}
/// Load a pre-compiled module from serialized bytes.
///
/// # Safety
///
/// The serialized bytes must have been produced by `serialize()`
/// from the same wasmtime version. Loading tampered bytes is
/// memory-safe (wasmtime validates) but may produce unexpected behavior.
/// # Errors
///
/// Returns an error if the engine or module deserialization fails.
pub fn load_cached(bytes: &[u8]) -> Result<Self> {
let mut engine_config = wasmtime::Config::new();
engine_config.consume_fuel(true);
engine_config.wasm_bulk_memory(true);
let engine =
Engine::new(&engine_config).map_err(|e| Error::WasmInit(format!("engine: {e}")))?;
let module = unsafe {
Module::deserialize(&engine, bytes)
.map_err(|e| Error::WasmInit(format!("deserialize: {e}")))?
};
Ok(Self { engine, module })
}
/// Compile and cache to disk. On next call, loads from cache.
///
/// The cache file carries an 8-byte integrity tag so that trivially
/// tampered files are rejected before reaching the `unsafe` deserialize
/// path. On Unix, the file is created with mode `0o600`.
/// # Errors
///
/// Returns an error if compilation fails.
pub fn new_cached(cache_path: &std::path::Path) -> Result<Self> {
// For security, avoid calling the unsafe `Module::deserialize` on
// potentially attacker-controlled cache files. Always compile a
// fresh module; write a cache for performance but do NOT read it
// back via `deserialize` to prevent unsafe deserialization of
// untrusted bytes.
let module = Self::new()?;
if let Ok(serialized) = module.serialize() {
if let Some(parent) = cache_path.parent() {
let _ = std::fs::create_dir_all(parent);
}
let tagged = Self::tag_cache_bytes(&serialized);
let _ = std::fs::write(cache_path, &tagged);
Self::set_restrictive_permissions(cache_path);
}
Ok(module)
}
/// Compute a 64-bit integrity hash over `payload` and prepend it as an
/// 8-byte little-endian tag. Uses FNV-1a for determinism across processes
/// (DefaultHasher uses random seed, breaking cross-process cache sharing).
fn tag_cache_bytes(payload: &[u8]) -> Vec<u8> {
let tag = Self::fnv1a_hash(payload).to_le_bytes();
let mut out = Vec::with_capacity(8 + payload.len());
out.extend_from_slice(&tag);
out.extend_from_slice(payload);
out
}
/// Deterministic FNV-1a hash — same result across processes and restarts.
fn fnv1a_hash(data: &[u8]) -> u64 {
let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
for &byte in data {
hash ^= u64::from(byte);
hash = hash.wrapping_mul(0x0100_0000_01b3);
}
hash
}
/// Set restrictive permissions on the cache file (Unix: 0o600).
fn set_restrictive_permissions(path: &std::path::Path) {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600));
}
let _ = path;
}
/// Get a reference to the wasmtime Engine.
#[must_use]
pub fn engine(&self) -> &Engine {
&self.engine
}
/// Get a reference to the compiled WASM Module.
#[must_use]
pub fn module_ref(&self) -> &Module {
&self.module
}
/// Execute JavaScript in a fresh sandboxed instance.
///
/// Each call creates a new WASM instance with isolated memory.
/// No state leaks between executions.
/// # Errors
///
/// Returns an error if WASM execution traps or resources are exhausted.
pub fn execute(
&self,
scripts: &[String],
bridge: Arc<dyn Bridge>,
config: &SandboxConfig,
) -> Result<ExecutionResult> {
self.execute_in_context(scripts, bridge, config, &ContextId::background(), None)
}
/// Execute in a named context with access to the message bus.
///
/// # Errors
///
/// Returns an error if WASM execution traps or resources are exhausted.
#[allow(
clippy::too_many_lines,
clippy::needless_pass_by_value,
clippy::cast_possible_truncation,
clippy::cast_possible_wrap
)]
pub fn execute_in_context(
&self,
scripts: &[String],
bridge: Arc<dyn Bridge>,
config: &SandboxConfig,
context_id: &ContextId,
message_bus: Option<&Mutex<MessageBus>>,
) -> Result<ExecutionResult> {
let start = Instant::now();
let observations: Arc<Mutex<Vec<Observation>>> = Arc::new(Mutex::new(Vec::new()));
validate_scripts(scripts, config)?;
// Build host state.
let host = HostState {
bridge: bridge.clone(),
observations: observations.clone(),
context_id: context_id.clone(),
config: config.clone(),
};
let mut store = Store::new(&self.engine, host);
if config.max_fuel > 0 {
store
.set_fuel(config.max_fuel)
.map_err(|e| Error::WasmInit(format!("fuel: {e}")))?;
}
// Instantiate with host-imported functions.
let linker = build_linker(&self.engine, &bridge, &observations)?;
let instance = linker
.instantiate(&mut store, &self.module)
.map_err(|e| Error::WasmInit(format!("instantiate: {e}")))?;
// Get exports.
let jsdet_init: TypedFunc<(i32, i32), i32> = instance
.get_typed_func(&mut store, "jsdet_init")
.map_err(|e| Error::WasmInit(format!("missing jsdet_init export: {e}")))?;
let jsdet_eval: TypedFunc<(i32, i32), i32> = instance
.get_typed_func(&mut store, "jsdet_eval")
.map_err(|e| Error::WasmInit(format!("missing jsdet_eval export: {e}")))?;
let jsdet_alloc: TypedFunc<i32, i32> =
instance
.get_typed_func(&mut store, "jsdet_alloc")
.map_err(|e| Error::WasmInit(format!("missing jsdet_alloc export: {e}")))?;
let jsdet_free: TypedFunc<i32, ()> = instance
.get_typed_func(&mut store, "jsdet_free")
.map_err(|e| Error::WasmInit(format!("missing jsdet_free export: {e}")))?;
let jsdet_destroy: TypedFunc<(), ()> = instance
.get_typed_func(&mut store, "jsdet_destroy")
.map_err(|e| Error::WasmInit(format!("missing jsdet_destroy export: {e}")))?;
let memory = instance
.exports(&mut store)
.find_map(wasmtime::Export::into_memory)
.ok_or_else(|| Error::WasmInit("no memory export".into()))?;
// Initialize QuickJS runtime.
// Cap at i32::MAX to prevent overflow — WASM linear memory is 32-bit anyway.
let qjs_memory_limit = config.max_memory_bytes.min(i32::MAX as usize) as i32;
let qjs_stack_size = (config.max_memory_bytes / 4).min(i32::MAX as usize) as i32;
let init_result = jsdet_init
.call(&mut store, (qjs_memory_limit, qjs_stack_size))
.map_err(|e| Error::WasmInit(format!("jsdet_init trapped: {e}")))?;
if init_result != 0 {
return Err(Error::WasmInit(format!(
"jsdet_init returned error code {init_result}"
)));
}
// Run bootstrap JS (bridge API installation).
let bootstrap = bridge.bootstrap_js();
if !bootstrap.is_empty() {
eval_in_wasm(
&mut store,
&memory,
&jsdet_eval,
&jsdet_alloc,
&jsdet_free,
&bootstrap,
)?;
}
// Deliver pending messages from other contexts.
if let Some(bus) = message_bus
&& let Ok(mut bus) = bus.lock()
{
let pending = bus.receive(context_id);
for msg in pending {
let dispatch = format!(
"if(typeof __jsdet_dispatch_message==='function')__jsdet_dispatch_message({});",
serde_json::to_string(&msg.payload).unwrap_or_default()
);
let _ = eval_in_wasm(
&mut store,
&memory,
&jsdet_eval,
&jsdet_alloc,
&jsdet_free,
&dispatch,
);
}
}
// Execute user scripts.
let mut scripts_executed = 0;
let mut errors = Vec::new();
for (i, script) in scripts.iter().enumerate() {
if scripts_executed >= config.max_scripts {
push_observation(
&observations,
Observation::ResourceLimit {
kind: ResourceLimitKind::ScriptCount,
detail: format!("exceeded {} script limit", config.max_scripts),
},
);
break;
}
if u64::try_from(start.elapsed().as_millis()).unwrap_or(u64::MAX) >= config.timeout_ms {
push_observation(
&observations,
Observation::ResourceLimit {
kind: ResourceLimitKind::Timeout,
detail: format!("exceeded {}ms timeout", config.timeout_ms),
},
);
break;
}
match eval_in_wasm(
&mut store,
&memory,
&jsdet_eval,
&jsdet_alloc,
&jsdet_free,
script,
) {
Ok(()) => scripts_executed += 1,
Err(Error::FuelExhausted { budget }) => {
push_observation(
&observations,
Observation::ResourceLimit {
kind: ResourceLimitKind::Fuel,
detail: format!("exceeded {budget} fuel budget"),
},
);
break;
}
Err(e) => {
errors.push(format!("script[{i}]: {e}"));
push_observation(
&observations,
Observation::Error {
message: format!("{e}"),
script_index: Some(i),
},
);
scripts_executed += 1;
}
}
}
// Drain timers if configured.
if config.drain_timers {
for _ in 0..config.max_timer_drains {
if u64::try_from(start.elapsed().as_millis()).unwrap_or(u64::MAX)
>= config.timeout_ms
{
break;
}
let drain_result = eval_in_wasm(
&mut store,
&memory,
&jsdet_eval,
&jsdet_alloc,
&jsdet_free,
"if(typeof __jsdet_drain_timer==='function')__jsdet_drain_timer()",
);
if drain_result.is_err() {
break;
}
}
}
// Probe forms — after all scripts and timers, find credential forms
// and simulate submission to observe where data goes.
let _ = eval_in_wasm(
&mut store,
&memory,
&jsdet_eval,
&jsdet_alloc,
&jsdet_free,
"if(typeof __jsdet_probe_forms==='function')__jsdet_probe_forms()",
);
// Second timer drain — catch timers set by form submit handlers.
// Phishing kits commonly do: form.onsubmit → fetch(c2) → setTimeout(redirect, 500)
// The redirect fires in the setTimeout AFTER form submission.
if config.drain_timers {
for _ in 0..5 {
if u64::try_from(start.elapsed().as_millis()).unwrap_or(u64::MAX)
>= config.timeout_ms
{
break;
}
let drain_result = eval_in_wasm(
&mut store,
&memory,
&jsdet_eval,
&jsdet_alloc,
&jsdet_free,
"if(typeof __jsdet_drain_timer==='function')__jsdet_drain_timer()",
);
if drain_result.is_err() {
break;
}
}
}
// Clean up QuickJS state.
let _ = jsdet_destroy.call(&mut store, ());
let duration_us = u64::try_from(start.elapsed().as_micros()).unwrap_or(u64::MAX);
let collected = observations
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clone();
Ok(ExecutionResult {
observations: collected,
scripts_executed,
errors,
duration_us,
timed_out: u64::try_from(start.elapsed().as_millis()).unwrap_or(u64::MAX)
>= config.timeout_ms,
})
}
/// Snapshot the WASM linear memory for state save/restore.
///
/// Returns a byte vector that can be restored later.
/// Cost: ~1μs for a 4MB instance (just memcpy).
#[must_use]
pub fn snapshot_memory(store: &Store<HostState>, memory: &Memory) -> Vec<u8> {
memory.data(store).to_vec()
}
/// Restore WASM linear memory from a snapshot.
pub fn restore_memory(store: &mut Store<HostState>, memory: &Memory, snapshot: &[u8]) {
let data = memory.data_mut(store);
let len = snapshot.len().min(data.len());
data[..len].copy_from_slice(&snapshot[..len]);
}
}
/// The result of executing JavaScript in the sandbox.
#[derive(Debug, Clone)]
pub struct ExecutionResult {
/// All observations collected during execution, in order.
pub observations: Vec<Observation>,
/// Number of scripts that executed (including those that errored).
pub scripts_executed: usize,
/// Errors encountered during execution.
pub errors: Vec<String>,
/// Total wall-clock time in microseconds.
pub duration_us: u64,
/// Whether execution was terminated by a resource limit.
pub timed_out: bool,
}
/// Host state accessible from WASM imported functions.
///
/// The `bridge` and `observations` fields are accessed via `Arc` clones
/// captured by the linker closures, not through the struct directly.
/// The struct owns them to keep them alive for the store's lifetime.
#[allow(dead_code)]
pub struct HostState {
pub bridge: Arc<dyn Bridge>,
pub observations: Arc<Mutex<Vec<Observation>>>,
pub context_id: ContextId,
pub config: SandboxConfig,
}
fn validate_scripts(scripts: &[String], config: &SandboxConfig) -> Result<()> {
let total_bytes: usize = scripts.iter().map(String::len).sum();
if total_bytes > config.max_total_script_bytes {
return Err(Error::Internal(format!(
"total script size {} exceeds limit {}",
total_bytes, config.max_total_script_bytes
)));
}
for (i, script) in scripts.iter().enumerate() {
if script.len() > config.max_script_bytes {
return Err(Error::Internal(format!(
"script[{i}] size {} exceeds limit {}",
script.len(),
config.max_script_bytes
)));
}
}
Ok(())
}
pub fn push_observation(observations: &Arc<Mutex<Vec<Observation>>>, obs: Observation) {
if let Ok(mut guard) = observations.lock() {
guard.push(obs);
}
}
/// Build the linker with host-imported functions.
///
/// These are the ONLY functions the WASM module can call.
/// The `jsdet` import module provides `bridge_call` and observe.
/// WASI imports are stubbed to satisfy wasi-libc dependencies.
///
/// # Errors
/// Returns an error if the exports cannot be resolved.
#[allow(
clippy::too_many_lines,
clippy::cast_sign_loss,
clippy::cast_possible_truncation
)]
pub fn build_linker(
engine: &Engine,
bridge: &Arc<dyn Bridge>,
observations: &Arc<Mutex<Vec<Observation>>>,
) -> Result<Linker<HostState>> {
let mut linker = Linker::new(engine);
// Stub the 4 WASI imports QuickJS needs. No real I/O — these satisfy
// wasi-libc link requirements without granting any capabilities.
// clock_time_get: returns monotonic nanoseconds from fuel counter.
linker
.func_wrap(
"wasi_snapshot_preview1",
"clock_time_get",
|mut caller: wasmtime::Caller<'_, HostState>,
_clock_id: i32,
_precision: i64,
result_ptr: i32|
-> i32 {
// Return a plausible fixed timestamp to defeat timing-based sandbox detection.
// Date.now() returning 0 (epoch) is a dead giveaway. Instead, return
// a recent-looking timestamp (2025-01-01T00:00:00Z in nanoseconds).
// Deterministic: same value every time, no real clock access.
const FAKE_TIME_NS: u64 = 1_735_689_600_000_000_000; // 2025-01-01 UTC
if let Some(memory) = caller.get_export("memory").and_then(Extern::into_memory) {
let ptr = result_ptr as usize;
let data = memory.data_mut(&mut caller);
if ptr.checked_add(8).is_some_and(|end| end <= data.len()) {
data[ptr..ptr + 8].copy_from_slice(&FAKE_TIME_NS.to_le_bytes());
}
}
0 // success
},
)
.map_err(|e| Error::WasmInit(format!("wasi clock: {e}")))?;
// fd_close: no-op, return success.
linker
.func_wrap(
"wasi_snapshot_preview1",
"fd_close",
|_caller: wasmtime::Caller<'_, HostState>, _fd: i32| -> i32 { 0 },
)
.map_err(|e| Error::WasmInit(format!("wasi fd_close: {e}")))?;
// fd_fdstat_get: return regular file stats for stdout/stderr.
linker
.func_wrap(
"wasi_snapshot_preview1",
"fd_fdstat_get",
|_: wasmtime::Caller<'_, HostState>, _: i32, _: i32| -> i32 { 0 },
)
.map_err(|e| Error::WasmInit(format!("wasi fd_fdstat_get: {e}")))?;
// fd_seek: not supported, return errno 76 (ENOTSUP).
linker
.func_wrap(
"wasi_snapshot_preview1",
"fd_seek",
|_caller: wasmtime::Caller<'_, HostState>,
_fd: i32,
_offset: i64,
_whence: i32,
_newoffset: i32|
-> i32 { 76 },
)
.map_err(|e| Error::WasmInit(format!("wasi fd_seek: {e}")))?;
// fd_write: capture stderr/stdout output as observations.
linker
.func_wrap(
"wasi_snapshot_preview1",
"fd_write",
move |mut caller: wasmtime::Caller<'_, HostState>,
_fd: i32,
iovs_ptr: i32,
iovs_len: i32,
nwritten_ptr: i32|
-> i32 {
// Read iovec structures from WASM memory to capture output.
let memory = caller.get_export("memory").and_then(Extern::into_memory);
let Some(memory) = memory else { return 8 }; // EBADF
let data = memory.data(&caller);
let mut total = 0u32;
for i in 0..iovs_len {
let Some(iov_offset) =
(iovs_ptr as usize).checked_add((i as usize).saturating_mul(8))
else {
break;
};
let Some(iov_end) = iov_offset.checked_add(8) else {
break;
};
if iov_end > data.len() {
break;
}
// Safe: bounds checked on line above (iov_offset + 8 <= data.len())
// Read the 4-byte fields safely and return EINVAL (22) on conversion failure instead of panicking.
let _buf_ptr = match data[iov_offset..iov_offset + 4].try_into() {
Ok(b) => u32::from_le_bytes(b),
Err(_) => return 22, // EINVAL
};
let buf_len = match data[iov_offset + 4..iov_offset + 8].try_into() {
Ok(b) => u32::from_le_bytes(b),
Err(_) => return 22, // EINVAL
};
total += buf_len;
}
// Write nwritten.
let nw_offset = nwritten_ptr as usize;
if nw_offset
.checked_add(4)
.is_some_and(|end| end <= memory.data(&caller).len())
{
let bytes = total.to_le_bytes();
memory.data_mut(&mut caller)[nw_offset..nw_offset + 4].copy_from_slice(&bytes);
}
0 // success (output is silently consumed)
},
)
.map_err(|e| Error::WasmInit(format!("wasi fd_write: {e}")))?;
// jsdet.bridge_call — the bridge function dispatcher.
// Routes JS API calls through the Bridge trait to the consumer's implementation.
let bridge_clone = bridge.clone();
let obs_clone = observations.clone();
linker
.func_wrap(
"jsdet",
"bridge_call",
move |mut caller: wasmtime::Caller<'_, HostState>,
api_ptr: i32,
api_len: i32,
args_ptr: i32,
args_len: i32|
-> i32 {
let memory = caller.get_export("memory").and_then(Extern::into_memory);
let Some(memory) = memory else { return 0 };
let data = memory.data(&caller);
let api = read_string(data, api_ptr as usize, api_len as usize);
let args_json = read_string(data, args_ptr as usize, args_len as usize);
// Parse args from JSON.
let args: Vec<crate::observation::Value> = serde_json::from_str(&args_json)
.unwrap_or_else(|_| {
if args_json.is_empty() {
vec![]
} else {
vec![crate::observation::Value::string(args_json.clone())]
}
});
// Dispatch through the Bridge trait.
let result = bridge_clone.call(&api, &args);
// Record the observation.
let result_value = match &result {
Ok(v) => v.clone(),
Err(e) => crate::observation::Value::string(format!("Error: {e}")),
};
if let Ok(mut guard) = obs_clone.lock() {
guard.push(Observation::ApiCall {
api: api.clone(),
args,
result: result_value.clone(),
});
}
// Write return value to WASM memory via dynamic allocation.
// The C glue reads it back and converts to a JSValue.
if let Ok(ref value) = result {
let json = value_to_json(value);
let json_bytes = json.as_bytes();
let write_len = json_bytes.len();
// Allocate a return buffer in WASM memory.
if let Ok(alloc_ret) = caller
.get_export("jsdet_alloc_return")
.and_then(Extern::into_func)
.ok_or(())
.and_then(|f| f.typed::<i32, i32>(&caller).map_err(|_| ()))
&& let Ok(buf_ptr) = alloc_ret.call(&mut caller, write_len as i32)
&& buf_ptr != 0
{
let buf_ptr = buf_ptr as usize;
let mem = caller.get_export("memory").and_then(Extern::into_memory);
if let Some(mem) = mem {
let data = mem.data_mut(&mut caller);
if buf_ptr
.checked_add(write_len)
.is_some_and(|end| end < data.len())
{
data[buf_ptr..buf_ptr + write_len].copy_from_slice(json_bytes);
}
}
if let Ok(set_len) = caller
.get_export("jsdet_set_return_len")
.and_then(Extern::into_func)
.ok_or(())
.and_then(|f| f.typed::<i32, ()>(&caller).map_err(|_| ()))
{
let _ = set_len.call(&mut caller, write_len as i32);
}
}
}
if result.is_ok() { 0 } else { -1 }
},
)
.map_err(|e| Error::WasmInit(format!("bridge_call link: {e}")))?;
// jsdet.observe — direct observation recording from WASM.
let obs_clone2 = observations.clone();
linker
.func_wrap(
"jsdet",
"observe",
move |mut caller: wasmtime::Caller<'_, HostState>,
kind: i32,
data_ptr: i32,
data_len: i32| {
let memory = caller.get_export("memory").and_then(Extern::into_memory);
let Some(memory) = memory else { return };
let mem_data = memory.data(&caller);
let detail = read_string(mem_data, data_ptr as usize, data_len as usize);
let observation = match kind {
9 => Observation::Error {
message: detail,
script_index: None,
},
_ => Observation::ApiCall {
api: format!("__observe_kind_{kind}"),
args: vec![crate::observation::Value::string(detail)],
result: crate::observation::Value::Undefined,
},
};
if let Ok(mut guard) = obs_clone2.lock() {
guard.push(observation);
}
},
)
.map_err(|e| Error::WasmInit(format!("observe link: {e}")))?;
Ok(linker)
}
/// Evaluate a script by writing it to WASM memory and calling jsdet_eval.
pub fn eval_in_wasm(
store: &mut Store<HostState>,
memory: &Memory,
jsdet_eval: &TypedFunc<(i32, i32), i32>,
jsdet_alloc: &TypedFunc<i32, i32>,
jsdet_free: &TypedFunc<i32, ()>,
script: &str,
) -> Result<()> {
let bytes = script.as_bytes();
if bytes.len() >= i32::MAX as usize {
return Err(Error::Trap(
"script exceeds WASM 32-bit address space".into(),
));
}
// Allocate +1 for null terminator — QuickJS may read past the length
// in some internal string functions.
let alloc_len = (bytes.len() as i32) + 1;
// Allocate WASM memory for the script.
let ptr = jsdet_alloc
.call(&mut *store, alloc_len)
.map_err(|e| Error::Trap(format!("alloc: {e}")))?;
if ptr == 0 {
return Err(Error::MemoryExceeded {
limit_bytes: store.data().config.max_memory_bytes,
});
}
// Write script bytes + null terminator to WASM memory.
{
let mem_data = memory.data_mut(&mut *store);
let start = ptr as usize;
let Some(end) = start.checked_add(bytes.len()) else {
return Err(Error::MemoryExceeded {
limit_bytes: mem_data.len(),
});
};
if end < mem_data.len() {
mem_data[start..end].copy_from_slice(bytes);
mem_data[end] = 0; // null terminator
} else {
return Err(Error::MemoryExceeded {
limit_bytes: mem_data.len(),
});
}
}
// Call jsdet_eval with the actual script length (not including null terminator).
let len = bytes.len() as i32;
let result = jsdet_eval.call(&mut *store, (ptr, len));
// Free the script memory.
let _ = jsdet_free.call(&mut *store, ptr);
match result {
Ok(0) => Ok(()),
Ok(code) => Err(Error::Trap(format!("jsdet_eval returned error {code}"))),
Err(e) => {
let msg = e.to_string();
if msg.contains("fuel") {
Err(Error::FuelExhausted {
budget: store.data().config.max_fuel,
})
} else {
Err(Error::Trap(msg))
}
}
}
}
/// Convert a Value to JSON for the bridge return buffer.
fn value_to_json(value: &crate::observation::Value) -> String {
match value {
crate::observation::Value::Undefined => "undefined".into(),
crate::observation::Value::Null => "null".into(),
crate::observation::Value::Bool(b) => if *b { "true" } else { "false" }.into(),
crate::observation::Value::Int(n) => n.to_string(),
crate::observation::Value::Float(n) => n.to_string(),
crate::observation::Value::String(s, _) => serde_json::to_string(s).unwrap_or_default(),
crate::observation::Value::Json(j, _) => j.clone(),
crate::observation::Value::Bytes(_) => "null".into(),
}
}
/// Read a UTF-8 string from WASM linear memory.
fn read_string(data: &[u8], ptr: usize, len: usize) -> String {
let Some(end) = ptr.checked_add(len) else {
return String::new(); // overflow guard
};
if end > data.len() {
return String::new();
}
String::from_utf8_lossy(&data[ptr..end]).into_owned()
}