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
// Copyright (c) 2020-2023 js-sandbox contributors. Zlib license.

use std::borrow::Cow;
use std::path::Path;
use std::rc::Rc;
use std::{thread, time::Duration};

use deno_core::{op, Extension, FastString, JsBuffer, JsRuntime, Op, OpState};
use serde::de::DeserializeOwned;

use crate::{AnyError, CallArgs, JsError, JsValue};

pub trait JsApi<'a> {
	/// Generate an API from a script
	fn from_script(script: &'a mut Script) -> Self
	where
		Self: Sized;
}

/// Represents a single JavaScript file that can be executed.
///
/// The code can be loaded from a file or from a string in memory.
/// A typical usage pattern is to load a file with one or more JS function definitions, and then call those functions from Rust.
pub struct Script {
	runtime: JsRuntime,
	last_rid: u32,
	timeout: Option<Duration>,
}

impl Script {
	const DEFAULT_FILENAME: &'static str = "sandboxed.js";

	// ----------------------------------------------------------------------------------------------------------------------------------------------
	// Constructors and builders

	/// Initialize a script with the given JavaScript source code.
	///
	/// Returns a new object on success, and an error in case of syntax or initialization error with the code.
	pub fn from_string(js_code: &str) -> Result<Self, JsError> {
		// console.log() is not available by default -- add the most basic version with single argument (and no warn/info/... variants)
		let all_code =
			"const console = { log: function(expr) { Deno.core.print(expr + '\\n', false); } };"
				.to_string() + js_code;

		Self::create_script(all_code)
	}

	/// Initialize a script by loading it from a .js file.
	///
	/// To load a file at compile time, you can use [`Self::from_string()`] in combination with the [`include_str!`] macro.
	/// At the moment, a script is limited to a single file, and you will need to do bundling yourself (e.g. with `esbuild`).
	///
	/// Returns a new object on success. Fails if the file cannot be opened or in case of syntax or initialization error with the code.
	pub fn from_file(file: impl AsRef<Path>) -> Result<Self, JsError> {
		// let filename = file
		// 	.as_ref()
		// 	.file_name()
		// 	.and_then(|s| s.to_str())
		// 	.unwrap_or(Self::DEFAULT_FILENAME)
		// 	.to_owned();

		match std::fs::read_to_string(file) {
			Ok(js_code) => Self::create_script(js_code),
			Err(e) => Err(JsError::Runtime(AnyError::from(e))),
		}
	}

	/// Equips this script with a timeout, meaning that any function call is aborted after the specified duration.
	///
	/// This requires creating a separate thread for each function call, which tracks time and pulls the plug
	/// if the JS function does not return in time. Use this for untrusted 3rd-party code, not if you know that
	/// your functions always return.
	///
	/// Panics with invalid timeouts or if this script already has a timeout set.
	pub fn with_timeout(mut self, timeout: Duration) -> Self {
		assert!(self.timeout.is_none());
		assert!(timeout > Duration::ZERO);

		self.timeout = Some(timeout);
		self
	}

	// ----------------------------------------------------------------------------------------------------------------------------------------------
	// Call API

	/// Invokes a JavaScript function.
	///
	/// Blocks on asynchronous functions until completion.
	///
	/// `args_tuple` needs to be a tuple.
	///
	/// Each tuple element is converted to JSON (using serde_json) and passed as a distinct argument to the JS function.
	pub fn call<A, R>(&mut self, fn_name: &str, args_tuple: A) -> Result<R, JsError>
	where
		A: CallArgs,
		R: DeserializeOwned,
	{
		let json_args = args_tuple.into_arg_string()?;
		let json_result = self.call_impl(fn_name, json_args)?;
		let result: R = serde_json::from_value(json_result)?;

		Ok(result)
	}

	pub fn bind_api<'a, A>(&'a mut self) -> A
	where
		A: JsApi<'a>,
	{
		A::from_script(self)
	}

	pub(crate) fn call_json(&mut self, fn_name: &str, args: &JsValue) -> Result<JsValue, JsError> {
		self.call_impl(fn_name, args.to_string())
	}

	fn call_impl(&mut self, fn_name: &str, json_args: String) -> Result<JsValue, JsError> {
		// Note: ops() is required to initialize internal state
		// Wrap everything in scoped block

		// 'undefined' will cause JSON serialization error, so it needs to be treated as null
		let js_code = format!(
			"(async () => {{
				let __rust_result = {fn_name}.constructor.name === 'AsyncFunction'
					? await {fn_name}({json_args})
					: {fn_name}({json_args});

				if (typeof __rust_result === 'undefined')
					__rust_result = null;

				Deno.core.ops.op_return(__rust_result);
			}})()"
		)
		.into();

		if let Some(timeout) = self.timeout {
			let handle = self.runtime.v8_isolate().thread_safe_handle();

			thread::spawn(move || {
				thread::sleep(timeout);
				handle.terminate_execution();
			});
		}

		// syncing ops is required cause they sometimes change while preparing the engine
		// self.runtime.sync_ops_cache();

		// TODO use strongly typed JsError here (downcast)
		self.runtime
			.execute_script(Self::DEFAULT_FILENAME, js_code)?;
		deno_core::futures::executor::block_on(self.runtime.run_event_loop(false))?;

		let state_rc = self.runtime.op_state();
		let mut state = state_rc.borrow_mut();
		let table = &mut state.resource_table;

		// Get resource, and free slot (no longer needed)
		let entry: Rc<ResultResource> = table
			.take(self.last_rid)
			.expect("Resource entry must be present");
		let extracted =
			Rc::try_unwrap(entry).expect("Rc must hold single strong ref to resource entry");
		self.last_rid += 1;

		Ok(extracted.json_value)
	}

	fn create_script<S>(js_code: S) -> Result<Self, JsError>
	where
		S: Into<FastString>,
	{
		let ext = Extension {
			ops: Cow::Owned(vec![op_return::DECL]),
			..Default::default()
		};

		let mut runtime = JsRuntime::new(deno_core::RuntimeOptions {
			module_loader: Some(Rc::new(deno_core::FsModuleLoader)),
			extensions: vec![ext],
			..Default::default()
		});

		// We cannot provide a dynamic filename because execute_script() requires a &'static str
		runtime.execute_script(Self::DEFAULT_FILENAME, js_code.into())?;

		Ok(Script {
			runtime,
			last_rid: 0,
			timeout: None,
		})
	}
}

#[derive(Debug)]
struct ResultResource {
	json_value: JsValue,
}

// Type that is stored inside Deno's resource table
impl deno_core::Resource for ResultResource {
	fn name(&self) -> Cow<str> {
		"__rust_Result".into()
	}
}

#[op]
fn op_return(
	state: &mut OpState,
	args: JsValue,
	_buf: Option<JsBuffer>,
) -> Result<JsValue, deno_core::error::AnyError> {
	let entry = ResultResource { json_value: args };
	let resource_table = &mut state.resource_table;
	let _rid = resource_table.add(entry);
	Ok(serde_json::Value::Null)
}