1use oxc_allocator::Allocator;
3use oxc_codegen::Codegen;
4use oxc_parser::Parser;
5use oxc_semantic::SemanticBuilder;
6use oxc_span::SourceType;
7use oxc_transformer::{TransformOptions, Transformer};
8use rquickjs::{
9 function::Func, CatchResultExt, CaughtError, Constructor, Context, Ctx, Exception, Object,
10 Promise, Runtime,
11};
12use serde::{Deserialize, Serialize};
13use sha2::{Digest, Sha256};
14use std::cell::RefCell;
15use std::path::Path;
16use std::rc::Rc;
17use std::time::{Duration, Instant};
18
19#[derive(Debug, thiserror::Error)]
20#[error("Script rejected: {0}")]
21pub struct ScriptError(pub String);
22
23#[derive(Debug)]
26pub struct HostFailure {
27 pub message: String,
28 pub origin: Option<u64>,
29}
30
31#[derive(Debug, thiserror::Error)]
35#[error("{error}")]
36pub struct ExecutionFailure {
37 pub error: ScriptError,
38 pub host_origin: Option<u64>,
39}
40
41impl From<ScriptError> for ExecutionFailure {
42 fn from(error: ScriptError) -> Self {
43 Self {
44 error,
45 host_origin: None,
46 }
47 }
48}
49
50#[derive(Clone, Debug)]
51pub struct Limits {
52 pub source_bytes: usize,
53 pub memory_bytes: usize,
54 pub result_bytes: usize,
55 pub host_calls: usize,
56 pub pending_jobs: usize,
57 pub timeout: Duration,
58}
59impl Default for Limits {
60 fn default() -> Self {
61 Self {
62 source_bytes: 1024 * 1024,
63 memory_bytes: 64 * 1024 * 1024,
64 result_bytes: 1024 * 1024,
65 host_calls: 1000,
66 pending_jobs: 10_000,
67 timeout: Duration::from_secs(10),
68 }
69 }
70}
71
72#[derive(Clone, Debug, Serialize, Deserialize)]
75pub struct CompiledScript {
76 pub javascript: String,
77 pub source_sha256: String,
78 pub compiler: String,
79}
80
81pub fn compile_typescript(source: &str, limits: &Limits) -> Result<CompiledScript, ScriptError> {
82 if source.len() > limits.source_bytes || limits.memory_bytes == 0 {
83 return Err(ScriptError("source limit exceeded".into()));
84 }
85 let allocator = Allocator::default();
86 let parsed = Parser::new(&allocator, source, SourceType::ts().with_module(false)).parse();
87 if !parsed.diagnostics.is_empty() {
88 return Err(ScriptError(format!(
89 "TypeScript syntax: {:?}",
90 parsed.diagnostics
91 )));
92 }
93 let mut program = parsed.program;
94 let semantic = SemanticBuilder::new().with_enum_eval(true).build(&program);
95 if !semantic.diagnostics.is_empty() {
96 return Err(ScriptError(format!(
97 "TypeScript bindings: {:?}",
98 semantic.diagnostics
99 )));
100 }
101 let transformed = Transformer::new(
102 &allocator,
103 Path::new("workflow.ts"),
104 &TransformOptions::default(),
105 )
106 .build_with_scoping(semantic.semantic.into_scoping(), &mut program);
107 if !transformed.diagnostics.is_empty() {
108 return Err(ScriptError(format!(
109 "TypeScript transformation: {:?}",
110 transformed.diagnostics
111 )));
112 }
113 let javascript = Codegen::new().build(&program).code;
114 if javascript.len() > limits.source_bytes {
115 return Err(ScriptError("compiled source limit exceeded".into()));
116 }
117 let runtime = Runtime::new().map_err(|e| ScriptError(e.to_string()))?;
119 runtime.set_memory_limit(limits.memory_bytes);
120 let context = Context::full(&runtime).map_err(|e| ScriptError(e.to_string()))?;
121 context.with(|ctx| {
122 ctx.eval::<rquickjs::Function, _>(format!("(function() {{\n{javascript}\n}})"))
123 .catch(&ctx)
124 .map(|_| ())
125 .map_err(|e| ScriptError(e.to_string()))
126 })?;
127 Ok(CompiledScript {
128 javascript,
129 source_sha256: format!("{:x}", Sha256::digest(source.as_bytes())),
130 compiler: "oxc/0.152.0".into(),
131 })
132}
133
134pub fn execute(
138 javascript: &str,
139 event: &serde_json::Value,
140 limits: &Limits,
141 host: impl FnMut(&str, serde_json::Value) -> Result<serde_json::Value, String> + 'static,
142) -> Result<serde_json::Value, ScriptError> {
143 execute_entry(javascript, "workflow", event, limits, host)
144}
145
146pub fn is_entry_name(name: &str) -> bool {
148 let mut bytes = name.bytes();
149 name.len() <= 128
150 && bytes
151 .next()
152 .is_some_and(|byte| byte.is_ascii_alphabetic() || matches!(byte, b'_' | b'$'))
153 && bytes.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'$'))
154 && !matches!(
155 name,
156 "event" | "call" | "sql" | "db" | "http" | "secrets" | "jobs" | "json" | "eval"
157 )
158}
159
160pub fn execute_entry(
163 javascript: &str,
164 entry: &str,
165 event: &serde_json::Value,
166 limits: &Limits,
167 mut host: impl FnMut(&str, serde_json::Value) -> Result<serde_json::Value, String> + 'static,
168) -> Result<serde_json::Value, ScriptError> {
169 execute_entry_with_host_origins(javascript, entry, event, limits, move |method, args| {
170 host(method, args).map_err(|message| HostFailure {
171 message,
172 origin: None,
173 })
174 })
175 .map_err(|failure| failure.error)
176}
177
178pub fn execute_entry_with_host_origins(
181 javascript: &str,
182 entry: &str,
183 event: &serde_json::Value,
184 limits: &Limits,
185 host: impl FnMut(&str, serde_json::Value) -> Result<serde_json::Value, HostFailure> + 'static,
186) -> Result<serde_json::Value, ExecutionFailure> {
187 if !is_entry_name(entry) {
188 return Err(ScriptError("invalid entry function name".into()).into());
189 }
190 if javascript.len() > limits.source_bytes
191 || limits.memory_bytes == 0
192 || limits.timeout.is_zero()
193 || limits.host_calls == 0
194 || limits.pending_jobs == 0
195 {
196 return Err(ScriptError("invalid limits or oversized source".into()).into());
197 }
198 let deadline = Instant::now()
199 .checked_add(limits.timeout)
200 .ok_or_else(|| ScriptError("invalid timeout".into()))?;
201 let runtime = Runtime::new().map_err(|e| ScriptError(e.to_string()))?;
202 runtime.set_memory_limit(limits.memory_bytes);
203 runtime.set_max_stack_size(512 * 1024);
204 runtime.set_interrupt_handler(Some(Box::new(move || Instant::now() >= deadline)));
205 let context = Context::full(&runtime).map_err(|e| ScriptError(e.to_string()))?;
206 let host = RefCell::new(host);
207 let event = serde_json::to_string(event).map_err(|e| ScriptError(e.to_string()))?;
208 if event.len() > limits.result_bytes {
209 return Err(ScriptError("event limit exceeded".into()).into());
210 }
211 context
212 .with(|ctx| execute_entry_context(ctx, javascript, entry, &event, limits, deadline, host))
213}
214
215fn execute_entry_context<'js>(
216 ctx: Ctx<'js>,
217 javascript: &str,
218 entry: &str,
219 event: &str,
220 limits: &Limits,
221 deadline: Instant,
222 host: RefCell<
223 impl FnMut(&str, serde_json::Value) -> Result<serde_json::Value, HostFailure> + 'static,
224 >,
225) -> Result<serde_json::Value, ExecutionFailure> {
226 let callback_limits = limits.clone();
227 let origins: Rc<RefCell<Vec<(Exception<'js>, u64)>>> = Rc::new(RefCell::new(Vec::new()));
228 let callback_origins = origins.clone();
229 let error_constructor: Rc<RefCell<Option<Constructor<'js>>>> = Rc::new(RefCell::new(None));
230 let callback_constructor = error_constructor.clone();
231 let run = || -> rquickjs::Result<serde_json::Value> {
232 *error_constructor.borrow_mut() = Some(ctx.globals().get("Error")?);
236 ctx.globals().set("__event", event)?;
237 let calls = RefCell::new(0usize);
238 ctx.globals().set(
239 "__host",
240 Func::new(
241 move |method: String, arguments: String| -> rquickjs::Result<String> {
242 let invoke = || -> Result<serde_json::Value, HostFailure> {
243 *calls.borrow_mut() += 1;
244 if *calls.borrow() > callback_limits.host_calls
245 || Instant::now() >= deadline
246 {
247 return Err(HostFailure {
248 message: "host call limit exceeded".into(),
249 origin: None,
250 });
251 }
252 if arguments.len() > callback_limits.result_bytes {
253 return Err(HostFailure {
254 message: "host argument limit exceeded".into(),
255 origin: None,
256 });
257 }
258 let value = (host.borrow_mut())(
259 &method,
260 serde_json::from_str(&arguments).map_err(|e| HostFailure {
261 message: e.to_string(),
262 origin: None,
263 })?,
264 )?;
265 if serde_json::to_vec(&value)
266 .map_err(|e| HostFailure {
267 message: e.to_string(),
268 origin: None,
269 })?
270 .len()
271 > callback_limits.result_bytes
272 {
273 return Err(HostFailure {
274 message: "host response limit exceeded".into(),
275 origin: None,
276 });
277 }
278 Ok(value)
279 };
280 match invoke() {
281 Ok(value) => Ok(serde_json::json!({"value":value}).to_string()),
282 Err(error) => {
283 let object: Object<'js> = callback_constructor
284 .borrow()
285 .as_ref()
286 .ok_or(rquickjs::Error::Unknown)?
287 .construct((&error.message,))?;
288 let exception =
289 Exception::from_object(object).ok_or(rquickjs::Error::Unknown)?;
290 if let Some(origin) = error.origin {
291 callback_origins
292 .borrow_mut()
293 .push((exception.clone(), origin));
294 }
295 Err(exception.throw())
296 }
297 }
298 },
299 ),
300 )?;
301 ctx.eval::<(), _>(include_str!("bindings.js"))?;
302 ctx.eval::<(), _>(javascript.as_bytes())?;
303 let promise: Promise = ctx.eval(format!(
304 "Promise.resolve().then(() => {entry}(event)).then(value => JSON.stringify(value))"
305 ))?;
306 for _ in 0..limits.pending_jobs {
307 if Instant::now() >= deadline {
308 break;
309 }
310 if let Some(result) = promise.result::<String>() {
311 let result = result?;
312 if result.len() > limits.result_bytes {
313 return Err(rquickjs::Error::Unknown);
314 }
315 return serde_json::from_str(&result).map_err(|_| rquickjs::Error::Unknown);
316 }
317 if !ctx.execute_pending_job() {
318 break;
319 }
320 }
321 Err(rquickjs::Error::Unknown)
322 };
323 let result = run().catch(&ctx).map_err(|error| {
324 let host_origin = match &error {
325 CaughtError::Exception(exception) => origins
326 .borrow()
327 .iter()
328 .find_map(|(original, origin)| (original == exception).then_some(*origin)),
329 _ => None,
330 };
331 ExecutionFailure {
332 error: ScriptError(if host_origin.is_some() {
335 "native host call failed".into()
336 } else {
337 error.to_string()
338 }),
339 host_origin,
340 }
341 });
342 origins.borrow_mut().clear();
345 error_constructor.borrow_mut().take();
346 result
347}