Options.cs 17 KB

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