use std::{cell::Cell, rc::Rc};
use nsh_core::{js::Limits, time::Instant};
use rquickjs::Ctx;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Phase {
Load,
Call,
}
pub(crate) struct Budget {
limits: Limits,
deadline: Rc<Cell<Option<Instant>>>,
tripped: Rc<Cell<Option<Phase>>>,
phase: Rc<Cell<Phase>>,
}
impl Budget {
pub(crate) fn new(limits: Limits) -> Self {
Self {
limits,
deadline: Rc::default(),
tripped: Rc::default(),
phase: Rc::new(Cell::new(Phase::Call)),
}
}
pub(crate) fn limits(&self) -> &Limits {
&self.limits
}
pub(crate) fn begin(&self, phase: Phase) -> bool {
if self.deadline.get().is_some() {
return false;
}
let budget = match phase {
Phase::Load => self.limits.load_budget,
Phase::Call => self.limits.call_budget,
};
self.phase.set(phase);
self.tripped.set(None);
self.deadline.set(Instant::now().checked_add(budget));
true
}
pub(crate) fn end(&self, started: bool) {
if started {
self.deadline.set(None);
}
}
pub(crate) fn take_trip(&self) -> Option<String> {
self.tripped.take().map(|phase| {
let (what, budget) = match phase {
Phase::Load => ("loading the bundle", self.limits.load_budget),
Phase::Call => ("a call into JS", self.limits.call_budget),
};
format!(
"the script was interrupted: {what} exceeded its budget of {} ms",
budget.as_millis()
)
})
}
pub(crate) fn interrupt_handler(
&self,
stop: Option<std::sync::Arc<std::sync::atomic::AtomicBool>>,
) -> Box<dyn FnMut() -> bool> {
let deadline = self.deadline.clone();
let tripped = self.tripped.clone();
let phase = self.phase.clone();
Box::new(move || {
if stop
.as_ref()
.is_some_and(|s| s.load(std::sync::atomic::Ordering::Relaxed))
{
return true;
}
match deadline.get() {
Some(d) if Instant::now() > d => {
tripped.set(Some(phase.get()));
true
}
_ => false,
}
})
}
}
const HARDEN: &str = r#"
(() => {
const deny = (label) => function () {
throw new TypeError(label + " is disabled: nsh runs no code from strings (development builds allow it)");
};
const replace = (fn, value) => {
Object.defineProperty(Object.getPrototypeOf(fn), "constructor", {
value, writable: false, enumerable: false, configurable: false,
});
};
const blocked = deny("the Function constructor");
blocked.prototype = Function.prototype;
replace(function () {}, blocked);
replace(async function () {}, deny("the AsyncFunction constructor"));
replace(function* () {}, deny("the GeneratorFunction constructor"));
replace(async function* () {}, deny("the AsyncGeneratorFunction constructor"));
Object.defineProperty(globalThis, "Function", { value: blocked, writable: false, configurable: false });
delete globalThis.eval;
// Assigning a property an object inherits read-only fails (the
// "override mistake"): `Sub.prototype.constructor = Sub` or
// `obj.toString = …` would throw once these prototypes are frozen. Their
// commonly overridden members become accessors whose setter defines the
// property on the object assigned to, as on an unfrozen prototype (the
// prototype itself still cannot change).
const tamed = [
"constructor", "toString", "toLocaleString", "valueOf", "hasOwnProperty", "isPrototypeOf",
"propertyIsEnumerable", "toJSON",
];
const tame = (proto) => {
for (const name of tamed) {
const d = Object.getOwnPropertyDescriptor(proto, name);
if (!d || !("value" in d) || !d.writable) continue;
const value = d.value;
Object.defineProperty(proto, name, {
get() { return value; },
set(v) {
if (this === proto) throw new TypeError(`Cannot assign to read only property '${name}'`);
Object.defineProperty(this, name, { value: v, writable: true, enumerable: true, configurable: true });
},
enumerable: d.enumerable,
configurable: false,
});
}
};
// Not Error.prototype: `this.name = "MyError"` in a subclass constructor
// assigns a property it has.
for (const proto of [
Object.prototype, Array.prototype, Function.prototype, String.prototype, Number.prototype,
Boolean.prototype, Symbol.prototype, RegExp.prototype, Promise.prototype, Map.prototype,
Set.prototype, WeakMap.prototype, WeakSet.prototype, Date.prototype,
Object.getPrototypeOf(Uint8Array.prototype),
]) {
tame(proto);
Object.freeze(proto);
}
})();
"#;
pub(crate) fn harden(ctx: &Ctx<'_>) -> rquickjs::Result<()> {
ctx.eval::<(), _>(HARDEN)
}