Options.cs 15 KB

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