Options.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. using System.Dynamic;
  2. using System.Globalization;
  3. using System.Linq;
  4. using System.Reflection;
  5. using Jint.Native;
  6. using Jint.Native.Object;
  7. using Jint.Runtime;
  8. using Jint.Runtime.Interop;
  9. using Jint.Runtime.Debugger;
  10. using Jint.Runtime.Descriptors;
  11. using Jint.Runtime.Modules;
  12. namespace Jint
  13. {
  14. public delegate JsValue? MemberAccessorDelegate(Engine engine, object target, string member);
  15. public delegate ObjectInstance? WrapObjectDelegate(Engine engine, object target);
  16. public delegate bool ExceptionHandlerDelegate(Exception exception);
  17. public class Options
  18. {
  19. private ITimeSystem? _timeSystem;
  20. internal List<Action<Engine>> _configurations { get; } = new();
  21. /// <summary>
  22. /// Execution constraints for the engine.
  23. /// </summary>
  24. public ConstraintOptions Constraints { get; } = new();
  25. /// <summary>
  26. /// CLR interop related options.
  27. /// </summary>
  28. public InteropOptions Interop { get; } = new();
  29. /// <summary>
  30. /// Debugger configuration.
  31. /// </summary>
  32. public DebuggerOptions Debugger { get; } = new();
  33. /// <summary>
  34. /// Host options.
  35. /// </summary>
  36. internal HostOptions Host { get; } = new();
  37. /// <summary>
  38. /// Module options
  39. /// </summary>
  40. public ModuleOptions Modules { get; } = new();
  41. /// <summary>
  42. /// Whether the code should be always considered to be in strict mode. Can improve performance.
  43. /// </summary>
  44. public bool Strict { get; set; }
  45. /// <summary>
  46. /// The culture the engine runs on, defaults to current culture.
  47. /// </summary>
  48. public CultureInfo Culture { get; set; } = CultureInfo.CurrentCulture;
  49. /// <summary>
  50. /// Configures a time system to use. Defaults to DefaultTimeSystem using local time.
  51. /// </summary>
  52. public ITimeSystem TimeSystem
  53. {
  54. get => _timeSystem ??= new DefaultTimeSystem(TimeZone, Culture);
  55. set => _timeSystem = value;
  56. }
  57. /// <summary>
  58. /// The time zone the engine runs on, defaults to local. Same as setting DefaultTimeSystem with the time zone.
  59. /// </summary>
  60. public TimeZoneInfo TimeZone { get; set; } = TimeZoneInfo.Local;
  61. /// <summary>
  62. /// Reference resolver allows customizing behavior for reference resolving. This can be useful in cases where
  63. /// you want to ignore long chain of property accesses that might throw if anything is null or undefined.
  64. /// An example of such is <code>var a = obj.field.subField.value</code>. Custom resolver could accept chain to return
  65. /// null/undefined on first occurrence.
  66. /// </summary>
  67. public IReferenceResolver ReferenceResolver { get; set; } = DefaultReferenceResolver.Instance;
  68. /// <summary>
  69. /// Whether calling 'eval' with custom code and function constructors taking function code as string is allowed.
  70. /// Defaults to true.
  71. /// </summary>
  72. /// <remarks>
  73. /// https://tc39.es/ecma262/#sec-hostensurecancompilestrings
  74. /// </remarks>
  75. public bool StringCompilationAllowed { get; set; } = true;
  76. /// <summary>
  77. /// Options for the built-in JSON (de)serializer which
  78. /// gets used using <c>JSON.parse</c> or <c>JSON.stringify</c>
  79. /// </summary>
  80. public JsonOptions Json { get; set; } = new();
  81. /// <summary>
  82. /// Called by the <see cref="Engine"/> instance that loads this <see cref="Options" />
  83. /// once it is loaded.
  84. /// </summary>
  85. internal void Apply(Engine engine)
  86. {
  87. foreach (var configuration in _configurations)
  88. {
  89. configuration?.Invoke(engine);
  90. }
  91. // add missing bits if needed
  92. if (Interop.Enabled)
  93. {
  94. engine.Realm.GlobalObject.SetProperty("System",
  95. new PropertyDescriptor(new NamespaceReference(engine, "System"), PropertyFlag.AllForbidden));
  96. engine.Realm.GlobalObject.SetProperty("importNamespace", new PropertyDescriptor(new ClrFunctionInstance(
  97. engine,
  98. "importNamespace",
  99. (thisObj, arguments) =>
  100. new NamespaceReference(engine, TypeConverter.ToString(arguments.At(0)))),
  101. PropertyFlag.AllForbidden));
  102. }
  103. if (Interop.ExtensionMethodTypes.Count > 0)
  104. {
  105. AttachExtensionMethodsToPrototypes(engine);
  106. }
  107. if (Modules.RegisterRequire)
  108. {
  109. // Node js like loading of modules
  110. engine.Realm.GlobalObject.SetProperty("require", new PropertyDescriptor(new ClrFunctionInstance(
  111. engine,
  112. "require",
  113. (thisObj, arguments) =>
  114. {
  115. var specifier = TypeConverter.ToString(arguments.At(0));
  116. return engine.ImportModule(specifier);
  117. }),
  118. PropertyFlag.AllForbidden));
  119. }
  120. engine.ModuleLoader = Modules.ModuleLoader;
  121. // ensure defaults
  122. engine.ClrTypeConverter ??= new DefaultTypeConverter(engine);
  123. }
  124. private static void AttachExtensionMethodsToPrototypes(Engine engine)
  125. {
  126. AttachExtensionMethodsToPrototype(engine, engine.Realm.Intrinsics.Array.PrototypeObject, typeof(Array));
  127. AttachExtensionMethodsToPrototype(engine, engine.Realm.Intrinsics.Boolean.PrototypeObject, typeof(bool));
  128. AttachExtensionMethodsToPrototype(engine, engine.Realm.Intrinsics.Date.PrototypeObject, typeof(DateTime));
  129. AttachExtensionMethodsToPrototype(engine, engine.Realm.Intrinsics.Number.PrototypeObject, typeof(double));
  130. AttachExtensionMethodsToPrototype(engine, engine.Realm.Intrinsics.Object.PrototypeObject, typeof(ExpandoObject));
  131. AttachExtensionMethodsToPrototype(engine, engine.Realm.Intrinsics.RegExp.PrototypeObject, typeof(System.Text.RegularExpressions.Regex));
  132. AttachExtensionMethodsToPrototype(engine, engine.Realm.Intrinsics.String.PrototypeObject, typeof(string));
  133. }
  134. private static void AttachExtensionMethodsToPrototype(Engine engine, ObjectInstance prototype, Type objectType)
  135. {
  136. if (!engine._extensionMethods.TryGetExtensionMethods(objectType, out var methods))
  137. {
  138. return;
  139. }
  140. foreach (var overloads in methods.GroupBy(x => x.Name))
  141. {
  142. PropertyDescriptor CreateMethodInstancePropertyDescriptor(ClrFunctionInstance? function)
  143. {
  144. var instance = function is null
  145. ? new MethodInfoFunctionInstance(engine, MethodDescriptor.Build(overloads.ToList()))
  146. : new MethodInfoFunctionInstance(engine, MethodDescriptor.Build(overloads.ToList()), function);
  147. return new PropertyDescriptor(instance, PropertyFlag.AllForbidden);
  148. }
  149. JsValue key = overloads.Key;
  150. PropertyDescriptor? descriptorWithFallback = null;
  151. PropertyDescriptor? descriptorWithoutFallback = null;
  152. if (prototype.HasOwnProperty(key) &&
  153. prototype.GetOwnProperty(key).Value is ClrFunctionInstance clrFunctionInstance)
  154. {
  155. descriptorWithFallback = CreateMethodInstancePropertyDescriptor(clrFunctionInstance);
  156. prototype.SetOwnProperty(key, descriptorWithFallback);
  157. }
  158. else
  159. {
  160. descriptorWithoutFallback = CreateMethodInstancePropertyDescriptor(null);
  161. prototype.SetOwnProperty(key, descriptorWithoutFallback);
  162. }
  163. // make sure we register both lower case and upper case
  164. if (char.IsUpper(overloads.Key[0]))
  165. {
  166. key = char.ToLower(overloads.Key[0]) + overloads.Key.Substring(1);
  167. if (prototype.HasOwnProperty(key) &&
  168. prototype.GetOwnProperty(key).Value is ClrFunctionInstance lowerclrFunctionInstance)
  169. {
  170. descriptorWithFallback ??= CreateMethodInstancePropertyDescriptor(lowerclrFunctionInstance);
  171. prototype.SetOwnProperty(key, descriptorWithFallback);
  172. }
  173. else
  174. {
  175. descriptorWithoutFallback ??= CreateMethodInstancePropertyDescriptor(null);
  176. prototype.SetOwnProperty(key, descriptorWithoutFallback);
  177. }
  178. }
  179. }
  180. }
  181. }
  182. public class DebuggerOptions
  183. {
  184. /// <summary>
  185. /// Whether debugger functionality is enabled, defaults to false.
  186. /// </summary>
  187. public bool Enabled { get; set; }
  188. /// <summary>
  189. /// Configures the statement handling strategy, defaults to Ignore.
  190. /// </summary>
  191. public DebuggerStatementHandling StatementHandling { get; set; } = DebuggerStatementHandling.Ignore;
  192. /// <summary>
  193. /// Configures the step mode used when entering the script.
  194. /// </summary>
  195. public StepMode InitialStepMode { get; set; } = StepMode.None;
  196. }
  197. public class InteropOptions
  198. {
  199. /// <summary>
  200. /// Whether accessing CLR and it's types and methods is allowed from JS code, defaults to false.
  201. /// </summary>
  202. public bool Enabled { get; set; }
  203. /// <summary>
  204. /// Whether to expose <see cref="object.GetType"></see> which can allow bypassing allow lists and open a way to reflection.
  205. /// Defaults to false.
  206. /// </summary>
  207. public bool AllowGetType { get; set; }
  208. /// <summary>
  209. /// Whether Jint should allow wrapping objects from System.Reflection namespace.
  210. /// Defaults to false.
  211. /// </summary>
  212. public bool AllowSystemReflection { get; set; }
  213. /// <summary>
  214. /// Whether writing to CLR objects is allowed (set properties), defaults to true.
  215. /// </summary>
  216. public bool AllowWrite { get; set; } = true;
  217. /// <summary>
  218. /// Whether operator overloading resolution is allowed, defaults to false.
  219. /// </summary>
  220. public bool AllowOperatorOverloading { get; set; }
  221. /// <summary>
  222. /// Types holding extension methods that should be considered when resolving methods.
  223. /// </summary>
  224. public List<Type> ExtensionMethodTypes { get; } = new();
  225. /// <summary>
  226. /// Object converters to try when build-in conversions.
  227. /// </summary>
  228. public List<IObjectConverter> ObjectConverters { get; } = new();
  229. /// <summary>
  230. /// Whether identity map is persisted for object wrappers in order to maintain object identity. This can cause
  231. /// memory usage to grow when targeting large set and freeing of memory can be delayed due to ConditionalWeakTable semantics.
  232. /// Defaults to false.
  233. /// </summary>
  234. public bool TrackObjectWrapperIdentity { get; set; } = false;
  235. /// <summary>
  236. /// If no known type could be guessed, objects are by default wrapped as an
  237. /// ObjectInstance using class ObjectWrapper. This function can be used to
  238. /// change the behavior.
  239. /// </summary>
  240. public WrapObjectDelegate WrapObjectHandler { get; set; } = static (engine, target) => new ObjectWrapper(engine, target);
  241. /// <summary>
  242. ///
  243. /// </summary>
  244. public MemberAccessorDelegate MemberAccessor { get; set; } = static (engine, target, member) => null;
  245. /// <summary>
  246. /// Exceptions that thrown from CLR code are converted to JavaScript errors and
  247. /// can be used in at try/catch statement. By default these exceptions are bubbled
  248. /// to the CLR host and interrupt the script execution. If handler returns true these exceptions are converted
  249. /// to JS errors that can be caught by the script.
  250. /// </summary>
  251. public ExceptionHandlerDelegate ExceptionHandler { get; set; } = static exception => false;
  252. /// <summary>
  253. /// Assemblies to allow scripts to call CLR types directly like <example>System.IO.File</example>.
  254. /// </summary>
  255. public List<Assembly> AllowedAssemblies { get; set; } = new();
  256. /// <summary>
  257. /// Type and member resolving strategy, which allows filtering allowed members and configuring member
  258. /// name matching comparison.
  259. /// </summary>
  260. /// <remarks>
  261. /// As this object holds caching state same instance should be shared between engines, if possible.
  262. /// </remarks>
  263. public TypeResolver TypeResolver { get; set; } = TypeResolver.Default;
  264. /// <summary>
  265. /// When writing values to CLR objects, how should JS values be coerced to CLR types.
  266. /// Defaults to only coercing to string values when writing to string targets.
  267. /// </summary>
  268. public ValueCoercionType ValueCoercion { get; set; } = ValueCoercionType.String;
  269. /// <summary>
  270. /// Strategy to create a CLR object to hold converted <see cref="ObjectInstance"/>.
  271. /// </summary>
  272. public Func<ObjectInstance, IDictionary<string, object?>> CreateClrObject = _ => new ExpandoObject();
  273. /// <summary>
  274. /// Strategy to create a CLR object from TypeReference.
  275. /// Defaults to retuning null which makes TypeReference attempt to find suitable constructor.
  276. /// </summary>
  277. public Func<Engine, Type, JsValue[], object?> CreateTypeReferenceObject = (_, _, _) => null;
  278. /// <summary>
  279. /// When not null, is used to serialize any CLR object in an
  280. /// <see cref="IObjectWrapper"/> passing through 'JSON.stringify'.
  281. /// </summary>
  282. public Func<object, string>? SerializeToJson { get; set; }
  283. /// <summary>
  284. /// What kind of date time should be produced when JavaScript date is converted to DateTime. If Local, uses <see cref="Options.TimeZone"/>.
  285. /// Defaults to <see cref="System.DateTimeKind.Utc"/>.
  286. /// </summary>
  287. public DateTimeKind DateTimeKind { get; set; } = DateTimeKind.Utc;
  288. }
  289. /// <summary>
  290. /// Rules for writing values to CLR fields.
  291. /// </summary>
  292. [Flags]
  293. public enum ValueCoercionType
  294. {
  295. /// <summary>
  296. /// No coercion will be done. If there's no type converter, and error will be thrown.
  297. /// </summary>
  298. None = 0,
  299. /// <summary>
  300. /// JS coercion using boolean rules "dog" == true, "" == false, 1 == true, 3 == true, 0 == false, { "prop": 1 } == true etc.
  301. /// </summary>
  302. Boolean = 1,
  303. /// <summary>
  304. /// JS coercion to numbers, false == 0, true == 1. valueOf functions will be used when available for object instances.
  305. /// Valid against targets of type: Decimal, Double, Int32, Int64.
  306. /// </summary>
  307. Number = 2,
  308. /// <summary>
  309. /// JS coercion to strings, toString function will be used when available for objects.
  310. /// </summary>
  311. String = 4,
  312. /// <summary>
  313. /// All coercion rules enabled.
  314. /// </summary>
  315. All = Boolean | Number | String
  316. }
  317. public class ConstraintOptions
  318. {
  319. /// <summary>
  320. /// Registered constraints.
  321. /// </summary>
  322. public List<Constraint> Constraints { get; } = new();
  323. /// <summary>
  324. /// Maximum recursion depth allowed, defaults to -1 (no checks).
  325. /// </summary>
  326. public int MaxRecursionDepth { get; set; } = -1;
  327. /// <summary>
  328. /// Maximum time a Regex is allowed to run, defaults to 10 seconds.
  329. /// </summary>
  330. public TimeSpan RegexTimeout { get; set; } = TimeSpan.FromSeconds(10);
  331. /// <summary>
  332. /// The maximum size for JavaScript array, defaults to <see cref="uint.MaxValue"/>.
  333. /// </summary>
  334. public uint MaxArraySize { get; set; } = uint.MaxValue;
  335. }
  336. /// <summary>
  337. /// Host related customization, still work in progress.
  338. /// </summary>
  339. public class HostOptions
  340. {
  341. internal Func<Engine, Host> Factory { get; set; } = _ => new Host();
  342. }
  343. /// <summary>
  344. /// Module related customization
  345. /// </summary>
  346. public class ModuleOptions
  347. {
  348. /// <summary>
  349. /// Whether to register require function to engine which will delegate to module loader, defaults to false.
  350. /// </summary>
  351. public bool RegisterRequire { get; set; }
  352. /// <summary>
  353. /// Module loader implementation, by default exception will be thrown if module loading is not enabled.
  354. /// </summary>
  355. public IModuleLoader ModuleLoader { get; set; } = FailFastModuleLoader.Instance;
  356. }
  357. /// <summary>
  358. /// JSON.parse / JSON.stringify related customization
  359. /// </summary>
  360. public class JsonOptions
  361. {
  362. /// <summary>
  363. /// The maximum depth allowed when parsing JSON files using "JSON.parse",
  364. /// defaults to 64.
  365. /// </summary>
  366. public int MaxParseDepth { get; set; } = 64;
  367. }
  368. }