From 9d4dccad5fe10063d5f314bf6a7f4a283383fab4 Mon Sep 17 00:00:00 2001 From: Florian Rappl Date: Mon, 16 Nov 2026 22:53:38 +0100 Subject: [PATCH 01/19] Add DOM registration as an alternative to reflection WithJs(JsDomRegistration) declares the DOM surface exposed to script with typed delegates (types, mixins, constructors, members, overloads, statics, constants, indexers, collections, event handlers, literals, named constructors and instances). A registration is authoritative: nothing is reflected over, which makes the surface usable for trimming and native AoT. The registration produces the same shapes, constructor definitions and collections as the reflection path, so both share one engine code path. Registered calls are wrapped like reflected ones: the reactions of custom elements wait for the call, and scripts it inserts run before it returns. --- CHANGELOG.md | 6 + .../DomRegistrationTests.cs | 421 +++++++++ .../Cache/CollectionTypeCache.cs | 4 + src/AngleSharp.Js/Cache/CreatorCache.cs | 12 + src/AngleSharp.Js/Cache/DomShapeCache.cs | 2 +- src/AngleSharp.Js/Cache/PrototypeCache.cs | 6 +- src/AngleSharp.Js/EngineInstance.cs | 70 +- .../Extensions/EngineExtensions.cs | 7 +- .../Extensions/JsValueExtensions.cs | 9 +- .../Extensions/OverloadResolution.cs | 49 ++ src/AngleSharp.Js/InsertedScripts.cs | 29 +- .../JsConfigurationExtensions.cs | 15 + src/AngleSharp.Js/JsScriptingOptions.cs | 10 + src/AngleSharp.Js/JsScriptingService.cs | 14 +- .../Proxies/DomConstructorFunctionInstance.cs | 16 + .../Proxies/DomConstructorInstance.cs | 44 +- .../Proxies/DomEventDefinition.cs | 31 +- src/AngleSharp.Js/Proxies/Indexer.cs | 16 + .../Registration/IJsDomRegistry.cs | 316 +++++++ src/AngleSharp.Js/Registration/JsCallback.cs | 71 ++ .../Registration/JsDomArguments.cs | 75 ++ .../Registration/JsDomRegistration.cs | 43 + .../Registration/JsDomSignature.cs | 74 ++ .../Registration/JsDomSurface.cs | 830 ++++++++++++++++++ .../Registration/RegisteredMembers.cs | 413 +++++++++ 25 files changed, 2531 insertions(+), 52 deletions(-) create mode 100644 src/AngleSharp.Js.Tests/DomRegistrationTests.cs create mode 100644 src/AngleSharp.Js/Registration/IJsDomRegistry.cs create mode 100644 src/AngleSharp.Js/Registration/JsCallback.cs create mode 100644 src/AngleSharp.Js/Registration/JsDomArguments.cs create mode 100644 src/AngleSharp.Js/Registration/JsDomRegistration.cs create mode 100644 src/AngleSharp.Js/Registration/JsDomSignature.cs create mode 100644 src/AngleSharp.Js/Registration/JsDomSurface.cs create mode 100644 src/AngleSharp.Js/Registration/RegisteredMembers.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index af0f8de3..c7ee29ef 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,9 @@ +# 1.3.0 + +(tbd) + +- Added `WithJs(JsDomRegistration)` (and `JsScriptingOptions.DomRegistration`) to declare the DOM surface exposed to script with typed delegates instead of discovering it by reflection, which makes it usable for trimmed and native AoT applications + # 1.2.2 Released on Sunday, November 15 2026. diff --git a/src/AngleSharp.Js.Tests/DomRegistrationTests.cs b/src/AngleSharp.Js.Tests/DomRegistrationTests.cs new file mode 100644 index 00000000..79396786 --- /dev/null +++ b/src/AngleSharp.Js.Tests/DomRegistrationTests.cs @@ -0,0 +1,421 @@ +namespace AngleSharp.Js.Tests +{ + using AngleSharp.Dom; + using AngleSharp.Dom.Events; + using AngleSharp.Html.Dom; + using AngleSharp.Scripting; + using NUnit.Framework; + using System; + using System.Threading.Tasks; + + [TestFixture] + public class DomRegistrationTests + { + public sealed class Thing + { + public Int32 Value => 42; + } + + private static void RegisterDom(IJsDomRegistry registry) + { + registry.Type("Window") + .Property("document", window => window.Document); + + registry.Mixin("ParentNode") + .Property("childElementCount", node => node.ChildElementCount); + + registry.Type("Node") + .Constant("ELEMENT_NODE", 1) + .Property("textContent", node => node.TextContent, (node, value) => node.TextContent = value) + .Property("childNodes", node => node.ChildNodes, flags: JsDomPropertyFlags.SameObject) + .Method("forEachChild", (node, args) => + { + var callback = args.GetCallback(0); + + foreach (var child in node.ChildNodes) + { + callback?.Invoke(child); + } + }, length: 1) + .Method("kind", (node, args) => "number", new JsDomSignature(typeof(Double))) + .Method("kind", (node, args) => "string", new JsDomSignature(typeof(String))) + .Method("kind", (node, args) => "none", new JsDomSignature()); + + registry.Type("Element") + .Inherits() + .Includes() + .Alias("Elem") + .Method("getAttribute", (element, args) => element.GetAttribute(args.Get(0)), length: 1) + .ForwardingProperty("self", element => element, "textContent") + .EventHandler("onping", (element, handler) => element.AddEventListener("ping", handler), (element, handler) => element.RemoveEventListener("ping", handler)) + .Static("twice", args => args.Get(0) * 2, length: 1) + .StaticProperty("answer", () => 42); + + registry.Type("HTMLElement") + .Inherits() + .Property("dataset", element => element.Dataset, flags: JsDomPropertyFlags.SameObject); + + registry.Type("Document") + .Inherits() + .Includes() + .Property("readyState", document => document.ReadyState) + .Method("isState", (document, args) => args.Get(0) == document.ReadyState, length: 1) + .Method("querySelector", (document, args) => document.QuerySelector(args.Get(0)), length: 1); + + registry.Type("NodeList") + .Collection(list => list.Length, (list, index) => list[index]); + + registry.Type("DOMStringMap") + .NamedIndexer((map, name) => map[name], (map, name, value) => map[name] = value); + + registry.Type("Event") + .Constructor(args => new Event(args.Get(0)), length: 1) + .Property("type", ev => ev.Type); + + registry.Type("Thing") + .Property("value", thing => thing.Value); + + registry.Literals() + .Literal(DocumentReadyState.Loading, "loading") + .Literal(DocumentReadyState.Interactive, "interactive") + .Literal(DocumentReadyState.Complete, "complete"); + + registry.Constants("NodeFilter") + .Constant("SHOW_ALL", 0xFFFFFFFF); + + registry.ConstructorFunction("Para", args => args.Window.Document.CreateElement("p")); + registry.Instance("thing", window => new Thing()); + } + + private static async Task<(JsScriptingService Service, IDocument Document)> OpenAsync(JsDomRegistration registration, String html) + { + var context = BrowsingContext.New(Configuration.Default.WithJs(registration)); + var document = await context.OpenAsync(m => m.Content(html)); + return (context.GetService(), document); + } + + private static async Task EvalAsync(String html, String source) + { + var (service, document) = await OpenAsync(RegisterDom, html); + return Eval(service, document, source); + } + + private static Object Eval(JsScriptingService service, IDocument document, String source) => + service.EvaluateScript(document, source, "text/javascript", null); + + [Test] + public async Task RegisteredMembersAreReachableFromScript() + { + Assert.AreEqual("Hello", await EvalAsync("

Hello

", "document.querySelector('p').textContent")); + Assert.AreEqual("a", await EvalAsync("

Hello

", "document.querySelector('p').getAttribute('id')")); + } + + [Test] + public async Task RegisteredSetterWritesThroughToTheDom() + { + var (service, document) = await OpenAsync(RegisterDom, "

Hello

"); + Eval(service, document, "document.querySelector('p').textContent = 'Bye'"); + Assert.AreEqual("Bye", document.QuerySelector("p").TextContent); + } + + [Test] + public async Task NothingIsDiscoveredByReflectionBesideTheRegistration() + { + Assert.AreEqual("undefined", await EvalAsync("

Hello

", "typeof document.createElement")); + Assert.AreEqual("undefined", await EvalAsync("

Hello

", "typeof HTMLDivElement")); + } + + [Test] + public async Task PrototypesFollowTheRegisteredInheritance() + { + Assert.AreEqual("[object HTMLElement]", await EvalAsync("

Hello

", "Object.prototype.toString.call(document.querySelector('p'))")); + Assert.AreEqual(true, await EvalAsync("

Hello

", "Object.getPrototypeOf(HTMLElement.prototype) === Element.prototype")); + Assert.AreEqual(true, await EvalAsync("

Hello

", "document.querySelector('p') instanceof Node")); + } + + [Test] + public async Task InterfaceObjectsArePublishedUnderTheirNamesAndAliases() + { + Assert.AreEqual("function", await EvalAsync("", "typeof Element")); + Assert.AreEqual(true, await EvalAsync("", "Elem === Element")); + Assert.AreEqual(true, await EvalAsync("

", "document.querySelector('p').constructor === HTMLElement")); + } + + [Test] + public async Task ConstructorsCreateRegisteredObjects() + { + Assert.AreEqual("ping", await EvalAsync("", "new Event('ping').type")); + Assert.AreEqual(true, await EvalAsync("", "new Event('ping') instanceof Event")); + Assert.AreEqual(1.0, await EvalAsync("", "Event.length")); + } + + [Test] + public async Task TypesWithoutConstructorAreIllegalToConstruct() + { + Assert.AreEqual("TypeError", await EvalAsync("", "try { new Element(); } catch (e) { e.name }")); + } + + [Test] + public async Task OverloadsArePickedByTheArguments() + { + Assert.AreEqual("number", await EvalAsync("

", "document.querySelector('p').kind(1)")); + Assert.AreEqual("string", await EvalAsync("

", "document.querySelector('p').kind('a')")); + Assert.AreEqual("none", await EvalAsync("

", "document.querySelector('p').kind()")); + } + + [Test] + public async Task ConstantsAreOnInterfaceObjectAndPrototype() + { + Assert.AreEqual(1.0, await EvalAsync("

", "Node.ELEMENT_NODE")); + Assert.AreEqual(1.0, await EvalAsync("

", "document.querySelector('p').ELEMENT_NODE")); + Assert.AreEqual((Double)0xFFFFFFFF, await EvalAsync("", "NodeFilter.SHOW_ALL")); + } + + [Test] + public async Task StaticMembersAreOnTheInterfaceObject() + { + Assert.AreEqual(8.0, await EvalAsync("", "Element.twice(4)")); + Assert.AreEqual(42.0, await EvalAsync("", "Element.answer")); + Assert.AreEqual("undefined", await EvalAsync("

", "typeof document.querySelector('p').twice")); + } + + [Test] + public async Task MixinMembersAreOnTheIncludingTypes() + { + Assert.AreEqual(2.0, await EvalAsync("
", "document.querySelector('div').childElementCount")); + Assert.AreEqual(1.0, await EvalAsync("", "document.childElementCount")); + Assert.AreEqual("[object Document]", await EvalAsync("", "Object.prototype.toString.call(document)")); + } + + [Test] + public async Task CollectionsAreArrayLike() + { + const String html = "
12
"; + Assert.AreEqual(2.0, await EvalAsync(html, "document.querySelector('div').childNodes.length")); + Assert.AreEqual("2", await EvalAsync(html, "document.querySelector('div').childNodes[1].textContent")); + Assert.AreEqual("12", await EvalAsync(html, "[...document.querySelector('div').childNodes].map(n => n.textContent).join('')")); + Assert.AreEqual(true, await EvalAsync(html, "document.querySelector('div').childNodes === document.querySelector('div').childNodes")); + } + + [Test] + public async Task NamedIndexerReadsAndWritesTheDataset() + { + var (service, document) = await OpenAsync(RegisterDom, "

"); + Assert.AreEqual("x", Eval(service, document, "document.querySelector('p').dataset.fooBar")); + Eval(service, document, "document.querySelector('p').dataset.otherValue = 'y'"); + Assert.AreEqual("y", document.QuerySelector("p").GetAttribute("data-other-value")); + } + + [Test] + public async Task EventHandlersSubscribeAndUnsubscribe() + { + var (service, document) = await OpenAsync(RegisterDom, "

0

"); + var p = document.QuerySelector("p"); + Eval(service, document, "var p = document.querySelector('p'); p.onping = function () { p.textContent = 'pinged'; }"); + p.Dispatch(new Event("ping")); + Assert.AreEqual("pinged", p.TextContent); + Eval(service, document, "p.textContent = '0'; p.onping = null"); + p.Dispatch(new Event("ping")); + Assert.AreEqual("0", p.TextContent); + } + + [Test] + public async Task PutForwardsAssignsTheAttributeOfTheValue() + { + var (service, document) = await OpenAsync(RegisterDom, "

0

"); + Eval(service, document, "document.querySelector('p').self = 'forwarded'"); + Assert.AreEqual("forwarded", document.QuerySelector("p").TextContent); + } + + [Test] + public async Task LiteralsAreStringsBothWays() + { + Assert.AreEqual("complete", await EvalAsync("", "document.readyState")); + Assert.AreEqual(true, await EvalAsync("", "document.isState('complete')")); + Assert.AreEqual(false, await EvalAsync("", "document.isState('loading')")); + } + + [Test] + public async Task ConstructorFunctionsAndInstancesArePublished() + { + Assert.AreEqual("[object HTMLElement]", await EvalAsync("", "Object.prototype.toString.call(new Para())")); + Assert.AreEqual(true, await EvalAsync("", "new Para() instanceof Element")); + Assert.AreEqual(0.0, await EvalAsync("", "Para.length")); + Assert.AreEqual(42.0, await EvalAsync("", "thing.value")); + Assert.AreEqual(true, await EvalAsync("", "thing instanceof Thing")); + } + + [Test] + public async Task NodeIdentityIsPreserved() + { + Assert.AreEqual(true, await EvalAsync("

Hello

", "document.querySelector('p') === document.querySelector('p')")); + } + + [Test] + public async Task CallbacksArePassedWithoutCompiledDelegates() + { + Assert.AreEqual("12", await EvalAsync("
12
", + "var s = ''; document.querySelector('div').forEachChild(function (c) { s += c.textContent; }); s")); + } + + [Test] + public async Task ClrErrorsBecomeScriptErrors() + { + JsDomRegistration registration = registry => registry + .Type("Window") + .Method("fail", (window, args) => throw new InvalidOperationException("nope")); + var (service, document) = await OpenAsync(registration, ""); + Assert.AreEqual("nope", Eval(service, document, "try { fail(); } catch (e) { e.message }")); + } + + [Test] + public async Task RegistrationRunsOncePerServiceAndIsCombinable() + { + var calls = 0; + var registration = JsDomRegistrations.Combine(RegisterDom, registry => + { + calls++; + registry.Type("Element").Property("tag", element => element.LocalName); + }); + var context = BrowsingContext.New(Configuration.Default.WithJs(registration)); + var service = context.GetService(); + var first = await context.OpenAsync(m => m.Content("

1

")); + Assert.AreEqual("p", Eval(service, first, "document.querySelector('p').tag")); + var second = await context.OpenAsync(m => m.Content("2")); + Assert.AreEqual("b", Eval(service, second, "document.querySelector('b').tag")); + Assert.AreEqual(1, calls); + } + + private static void RegisterPageDom(IJsDomRegistry registry) + { + registry.Type("Window") + .Property("document", window => window.Document) + .Property("customElements", window => window.CustomElements()); + + registry.Type("CustomElementRegistry") + .Method("define", (customElements, args) => customElements.Define(args.Get(0), args.Get(1), null), length: 2); + + registry.Type("Node") + .Method("appendChild", (node, args) => node.AppendChild(args.Get(0)), length: 1); + + registry.Type("Element") + .Inherits() + .Property("id", element => element.Id) + .Property("localName", element => element.LocalName) + .Property("nextElementSibling", element => element.NextElementSibling) + .Property("innerHTML", element => element.InnerHtml, (element, value) => element.InnerHtml = value) + .Method("remove", (element, args) => element.Remove()); + + registry.Type("HTMLElement") + .Inherits(); + + registry.Type("HTMLScriptElement") + .Inherits() + .Property("text", script => script.Text, (script, value) => script.Text = value); + + registry.Type("Document") + .Inherits() + .Property("documentElement", document => document.DocumentElement) + .Property("head", document => document.Head) + .Property("body", document => document.Body) + .Method("createElement", (document, args) => document.CreateElement(args.Get(0)), length: 1); + } + + private static async Task RunPageAsync(String script, String result) + { + var context = BrowsingContext.New(Configuration.Default.WithJs(RegisterPageDom).WithEventLoop()); + var document = await context.OpenAsync(m => m.Content("")); + return Eval(context.GetService(), document, result); + } + + [Test] + public async Task InsertedScriptRunsBeforeAppendChildReturns() + { + Assert.AreEqual("1,2,3", await RunPageAsync( + "var order = []; var s = document.createElement('script'); s.text = 'order.push(1)'; document.head.appendChild(s); order.push(2); s.remove(); document.body.appendChild(s); order.push(3);", + "order.join()")); + } + + [Test] + public async Task CallbacksSeeWhatTheCallOfTheScriptDidCompletely() + { + Assert.AreEqual("a:my-b,b:", await RunPageAsync(@" + var log = []; + class Item extends HTMLElement { + connectedCallback() { log.push(this.id + ':' + (this.nextElementSibling ? this.nextElementSibling.localName : '')); } + } + customElements.define('my-a', class extends Item {}); + customElements.define('my-b', class extends Item {}); + var parent = document.createElement('div'); + document.body.appendChild(parent); + parent.innerHTML = '';", + "log.join()")); + } + + [Test] + public async Task ThrowingMemberStillRunsTheReactionsOfItsCall() + { + Assert.AreEqual("connected,caught", await RunPageAsync(@" + var log = []; + class MyEl extends HTMLElement { connectedCallback() { log.push('connected'); } } + customElements.define('my-el', MyEl); + var el = new MyEl(); + document.body.appendChild(el); + try { document.body.appendChild(document.documentElement); } catch (e) { log.push('caught'); }", + "log.join()")); + } + + [Test] + public async Task TypesWithoutInterfaceObjectAreNotPublished() + { + JsDomRegistration registration = registry => + { + RegisterDom(registry); + registry.Mixin("ParentNode").WithoutInterfaceObject(); + registry.Type("Thing").WithoutInterfaceObject().Constant("ANSWER", 42); + }; + var (service, document) = await OpenAsync(registration, "
"); + Assert.AreEqual("undefined", Eval(service, document, "typeof ParentNode")); + Assert.AreEqual(1.0, Eval(service, document, "document.querySelector('div').childElementCount")); + Assert.AreEqual("undefined", Eval(service, document, "typeof Thing")); + Assert.AreEqual(42.0, Eval(service, document, "thing.value")); + Assert.AreEqual(42.0, Eval(service, document, "thing.ANSWER")); + Assert.AreEqual(false, Eval(service, document, "Object.getPrototypeOf(thing).hasOwnProperty('constructor')")); + } + + [Test] + public void ConstructorWithoutInterfaceObjectIsRejected() => + AssertRejected(registry => registry.Type("Event").WithoutInterfaceObject().Constructor(args => new Event("x"))); + + [Test] + public void InheritingFromAnUnregisteredTypeIsRejected() => + AssertRejected(registry => registry.Type("Element").Inherits()); + + [Test] + public void IncludingWhatIsNoMixinIsRejected() => + AssertRejected(registry => + { + registry.Type("ParentNode"); + registry.Type("Element").Includes(); + }); + + [Test] + public void ConstructibleMixinIsRejected() => + AssertRejected(registry => registry.Mixin("ParentNode").Constructor(args => null)); + + [Test] + public void RegisteringATypeUnderTwoNamesIsRejected() => + AssertRejected(registry => + { + registry.Type("Element"); + registry.Type("Other"); + }); + + private static void AssertRejected(JsDomRegistration registration) + { + var context = BrowsingContext.New(Configuration.Default.WithJs(registration)); + var document = context.OpenNewAsync().Result; + Assert.Throws(() => Eval(context.GetService(), document, "1")); + } + } +} diff --git a/src/AngleSharp.Js/Cache/CollectionTypeCache.cs b/src/AngleSharp.Js/Cache/CollectionTypeCache.cs index c9257802..717ec919 100644 --- a/src/AngleSharp.Js/Cache/CollectionTypeCache.cs +++ b/src/AngleSharp.Js/Cache/CollectionTypeCache.cs @@ -104,6 +104,10 @@ private IndexedCollection(Func length, Func length, Func item) => + new IndexedCollection(length, item); + public static IndexedCollection TryCreate(Type type, MethodInfo indexer, MethodInfo length) { // What carries the DOM attributes and what can actually be called are not always the diff --git a/src/AngleSharp.Js/Cache/CreatorCache.cs b/src/AngleSharp.Js/Cache/CreatorCache.cs index 1635fc7d..91137504 100644 --- a/src/AngleSharp.Js/Cache/CreatorCache.cs +++ b/src/AngleSharp.Js/Cache/CreatorCache.cs @@ -342,6 +342,18 @@ public ConstructorDefinition(Type type, String[] names, ConstructorInfo[] overlo Overloads = overloads; } + public ConstructorDefinition(Type type, String[] names, RegisteredInterface registered) + : this(type, names, Array.Empty()) + { + Registered = registered; + } + + /// + /// Gets what a registration declared of the interface object, or null if it is found by + /// reflection - in which case the overloads and the static members are reflected. + /// + public RegisteredInterface Registered { get; } + /// /// Gets the type the constructor creates instances of. /// diff --git a/src/AngleSharp.Js/Cache/DomShapeCache.cs b/src/AngleSharp.Js/Cache/DomShapeCache.cs index 27d96043..d49b3ccf 100644 --- a/src/AngleSharp.Js/Cache/DomShapeCache.cs +++ b/src/AngleSharp.Js/Cache/DomShapeCache.cs @@ -208,7 +208,7 @@ private IReadOnlyDictionary GetInheritedMembers(Engine engine) /// script reads off the window under the type's name, which is what keeps naming a type /// and asking one of its instances for its constructor the same answer. /// - private static JsValue CreateConstructor(ObjectInstance prototype) + internal static JsValue CreateConstructor(ObjectInstance prototype) { var state = DomPrototypeState.Of(prototype); return state != null ? state.GetConstructor(state.Shape.Constructor) : JsValue.Undefined; diff --git a/src/AngleSharp.Js/Cache/PrototypeCache.cs b/src/AngleSharp.Js/Cache/PrototypeCache.cs index 29dae361..e12adec1 100644 --- a/src/AngleSharp.Js/Cache/PrototypeCache.cs +++ b/src/AngleSharp.Js/Cache/PrototypeCache.cs @@ -13,8 +13,9 @@ sealed class PrototypeCache private readonly ConcurrentDictionary _prototypes; private readonly ConcurrentDictionary _canonicalTypes; private readonly LibrarySet _libs; + private readonly JsDomSurface _surface; - public PrototypeCache(Engine engine, LibrarySet libs) + public PrototypeCache(Engine engine, LibrarySet libs, JsDomSurface surface = null) { _prototypes = new ConcurrentDictionary { @@ -22,6 +23,7 @@ public PrototypeCache(Engine engine, LibrarySet libs) }; _canonicalTypes = new ConcurrentDictionary(); _libs = libs; + _surface = surface; } public ObjectInstance GetOrCreate(Type type, Func creator) => @@ -30,6 +32,6 @@ public ObjectInstance GetOrCreate(Type type, Func creator) // Memoized per engine rather than globally: the set of libraries a document uses is what // decides the outcome, and that is fixed for an engine but not for the process. public Type Canonicalize(Type type) => - _canonicalTypes.GetOrAdd(type, m => m.GetDomPrototypeType(_libs.Assemblies)); + _canonicalTypes.GetOrAdd(type, m => _surface != null ? _surface.Canonicalize(m) : m.GetDomPrototypeType(_libs.Assemblies)); } } diff --git a/src/AngleSharp.Js/EngineInstance.cs b/src/AngleSharp.Js/EngineInstance.cs index fd42850e..04c9aae3 100644 --- a/src/AngleSharp.Js/EngineInstance.cs +++ b/src/AngleSharp.Js/EngineInstance.cs @@ -60,6 +60,7 @@ sealed class EngineInstance private readonly ReferenceCache _references; private readonly ConditionalWeakTable _sameObjects; private readonly LibrarySet _libs; + private readonly JsDomSurface _surface; private readonly DomNodeInstance _window; private readonly IDocument _document; private readonly JsImportMap _importMap; @@ -75,7 +76,7 @@ sealed class EngineInstance #region ctor - public EngineInstance(IWindow window, IDictionary assignments, IEnumerable libs, JsScriptingOptions options) + public EngineInstance(IWindow window, IDictionary assignments, IEnumerable libs, JsScriptingOptions options, JsDomSurface surface = null) { _importMap = new JsImportMap(); var engineOptions = new Options(); @@ -95,7 +96,8 @@ public EngineInstance(IWindow window, IDictionary assignments, I ?? throw new InvalidOperationException("The engine creator must return a Jint engine."); _regexTimeout = engineOptions.Constraints.RegexTimeout; _libs = new LibrarySet(libs); - _prototypes = new PrototypeCache(_engine, _libs); + _surface = surface; + _prototypes = new PrototypeCache(_engine, _libs, surface); _references = new ReferenceCache(); _sameObjects = new ConditionalWeakTable(); @@ -115,6 +117,7 @@ public EngineInstance(IWindow window, IDictionary assignments, I this.AddInstances(_window, lib); } + _surface?.Publish(this, _window); _window.FastSetProperty("DOMException", CreateDomExceptionProperty()); foreach (var property in _window.GetOwnProperties()) @@ -145,6 +148,11 @@ public EngineInstance(IWindow window, IDictionary assignments, I public DomNodeInstance Window => _window; + /// + /// Gets the registered DOM surface, or null if the surface is found by reflection. + /// + public JsDomSurface Surface => _surface; + /// /// Gets the document the engine runs the scripts of. /// @@ -476,29 +484,10 @@ public JsValue GetSameObject(Object owner, MethodInfo getter) { var current = getter.Invoke(owner, Array.Empty()); - if (current == null) - { - return JsValue.Null; - } - - // Nodes and windows already have a canonical proxy. Preserve its identity, - // concrete prototype and script-owned properties across SameObject getters. - if (IsOutOfReach(current)) - { - return JsValue.Null; - } - - if (current is INode || current is IWindow) - { - return GetDomNode(current); - } - - var cache = _sameObjects.GetValue(owner, _ => new SameObjectCache()); - // The interface of a collection doesn't tell that it is one, the class does: script // iterates over document.links or element.children like any other. - var type = current is ITokenList || current.GetType().GetGenericInterface(typeof(IHtmlCollection<>)) != null ? current.GetType() : getter.ReturnType; - return cache.GetOrUpdate(getter, current, () => CreateInstance(current, type)); + var type = current != null && (current is ITokenList || current.GetType().GetGenericInterface(typeof(IHtmlCollection<>)) != null) ? current.GetType() : getter.ReturnType; + return GetSameObject(owner, getter, current, type); } catch (TargetInvocationException ex) { @@ -506,6 +495,33 @@ public JsValue GetSameObject(Object owner, MethodInfo getter) } } + /// + /// Gets the object script sees for what a [SameObject] attribute read, which is the one it + /// saw before - kept per owner and per attribute, the key standing for the latter. + /// + public JsValue GetSameObject(Object owner, Object key, Object current, Type type) + { + if (current == null) + { + return JsValue.Null; + } + + // Nodes and windows already have a canonical proxy. Preserve its identity, + // concrete prototype and script-owned properties across SameObject getters. + if (IsOutOfReach(current)) + { + return JsValue.Null; + } + + if (current is INode || current is IWindow) + { + return GetDomNode(current); + } + + var cache = _sameObjects.GetValue(owner, _ => new SameObjectCache()); + return cache.GetOrUpdate(key, current, () => CreateInstance(current, type)); + } + /// /// Gets the constructor object of the given type, building it on first ask. The /// prototype keeps it, so that naming the type and reading "constructor" off one of @@ -859,7 +875,7 @@ private ObjectInstance CreateInstance(Object obj) private ObjectInstance CreateInstance(Object obj, Type type) { - var collection = type.GetIndexedCollection(); + var collection = _surface != null ? _surface.GetCollection(_prototypes.Canonicalize(type)) : type.GetIndexedCollection(); if (collection != null) { @@ -876,7 +892,7 @@ private ObjectInstance CreateInstance(Object obj, Type type) /// private ObjectInstance CreatePrototype(Type type) { - var shape = DomShapeCache.GetOrCreate(type, _libs, _engine); + var shape = _surface != null ? _surface.GetShape(type) : DomShapeCache.GetOrCreate(type, _libs, _engine); var prototype = shape.Shape.Instantiate(_engine, GetParentPrototype(type, shape.BaseType)); JsObjectShape.SetHostState(prototype, new DomPrototypeState(this, prototype, shape)); SetIterator(prototype, shape); @@ -907,9 +923,9 @@ private ObjectInstance WrapObject(Engine engine, Object target, Type type) => private sealed class SameObjectCache { - private readonly Dictionary _entries = new Dictionary(); + private readonly Dictionary _entries = new Dictionary(); - public ObjectInstance GetOrUpdate(MethodInfo getter, Object value, Func create) + public ObjectInstance GetOrUpdate(Object getter, Object value, Func create) { lock (_entries) { diff --git a/src/AngleSharp.Js/Extensions/EngineExtensions.cs b/src/AngleSharp.Js/Extensions/EngineExtensions.cs index 18ec69f8..69269efe 100644 --- a/src/AngleSharp.Js/Extensions/EngineExtensions.cs +++ b/src/AngleSharp.Js/Extensions/EngineExtensions.cs @@ -66,7 +66,8 @@ public static JsValue ToJsValue(this Object obj, EngineInstance engine) } else if (obj is Enum literal) { - var name = literal.GetLiteralName(); + // a registration is all there is, see JsDomRegistration + var name = engine.Surface != null ? engine.Surface.GetLiteral(literal) : literal.GetLiteralName(); if (name != null) { @@ -281,7 +282,7 @@ public static void AddConstructors(this EngineInstance engine, ObjectInstance ct } } - private static void SetEnumLiteral(EngineInstance engine, ObjectInstance obj, EnumLiteralDefinition enumDefinition) + internal static void SetEnumLiteral(EngineInstance engine, ObjectInstance obj, EnumLiteralDefinition enumDefinition) { var target = obj.Get(enumDefinition.Name) as ObjectInstance; @@ -406,7 +407,7 @@ public static void AddConstructor(this EngineInstance engine, ObjectInstance obj /// learn that a custom value became a constant. A type name is exactly the sort of global a /// script reads over and over. /// - private static PropertyDescriptor CreateConstructorProperty(EngineInstance engine, ConstructorDefinition definition) => + internal static PropertyDescriptor CreateConstructorProperty(EngineInstance engine, ConstructorDefinition definition) => PropertyDescriptor.CreateLazy( new ConstructorRequest(engine, definition), static request => request.Instance.GetDomConstructor(request.Definition), diff --git a/src/AngleSharp.Js/Extensions/JsValueExtensions.cs b/src/AngleSharp.Js/Extensions/JsValueExtensions.cs index 870d0294..b7a42bed 100644 --- a/src/AngleSharp.Js/Extensions/JsValueExtensions.cs +++ b/src/AngleSharp.Js/Extensions/JsValueExtensions.cs @@ -358,7 +358,14 @@ public static Object As(this JsValue value, Type targetType, EngineInstance engi } else if (targetType.GetTypeInfo().IsEnum) { - if (value.IsString()) + if (value.IsString() && engine?.Surface != null) + { + if (engine.Surface.TryParseLiteral(targetType, TypeConverter.ToString(value), out var parsed)) + { + return parsed; + } + } + else if (value.IsString()) { var literal = TypeConverter.ToString(value); var member = targetType diff --git a/src/AngleSharp.Js/Extensions/OverloadResolution.cs b/src/AngleSharp.Js/Extensions/OverloadResolution.cs index f49959e2..f74b17ab 100644 --- a/src/AngleSharp.Js/Extensions/OverloadResolution.cs +++ b/src/AngleSharp.Js/Extensions/OverloadResolution.cs @@ -44,6 +44,55 @@ public static T SelectOverload(this T[] overloads, JsValue[] arguments) return best; } + /// + /// Picks one of several registered overloads, by the same rules as for reflected ones. + /// + public static Int32 SelectSignature(this JsDomSignature[] signatures, JsValue[] arguments) + { + var count = CountPassed(arguments); + var best = 0; + var bestScore = Int32.MinValue; + + for (var i = 0; i < signatures.Length; i++) + { + var signature = signatures[i]; + var parameters = signature.Parameters; + var score = count < signature.Required + ? -1000 + count - signature.Required + : count > parameters.Count && !signature.IsVariadic ? parameters.Count - count : 0; + + if (count >= signature.Required) + { + for (var j = 0; j < Math.Min(count, parameters.Count); j++) + { + var type = parameters[j]; + var isRest = signature.IsVariadic && j == parameters.Count - 1; + score += Match(arguments[j], isRest ? type.GetElementType() : type); + } + } + + if (score > bestScore) + { + best = i; + bestScore = score; + } + } + + return best; + } + + private static Int32 CountPassed(JsValue[] arguments) + { + var count = arguments.Length; + + while (count > 0 && arguments[count - 1].IsUndefined()) + { + count--; + } + + return count; + } + private static Int32 Score(MethodBase method, JsValue[] arguments, Int32 count) { var parameters = method.GetParameters(); diff --git a/src/AngleSharp.Js/InsertedScripts.cs b/src/AngleSharp.Js/InsertedScripts.cs index efe45bf2..c55615d3 100644 --- a/src/AngleSharp.Js/InsertedScripts.cs +++ b/src/AngleSharp.Js/InsertedScripts.cs @@ -3,6 +3,7 @@ namespace AngleSharp.Js using AngleSharp.Dom; using AngleSharp.Html.Dom; using AngleSharp.Io; + using Jint.Native; using Jint.Runtime; using System; using System.Collections.Generic; @@ -59,7 +60,33 @@ public static List FindUnstarted(Object target, Object[] arg } /// - /// Runs the scripts AngleSharp prepared during the call (see ), + /// Finds the scripts a call of a registered member may insert, from the arguments as + /// script passed them: what is inserted is a node, so it arrives as its proxy and needs + /// no conversion to be found. + /// + public static List FindUnstarted(Object target, JsValue[] arguments) + { + if (StartedField is null) + { + return null; + } + + var found = default(List); + Add(target, ref found); + + for (var i = 0; i < arguments.Length; i++) + { + if (arguments[i] is IDomProxy proxy) + { + Add(proxy.Value, ref found); + } + } + + return found; + } + + /// + /// Runs the scripts AngleSharp prepared during the call (see ), /// which are of the document of the engine and have their text. AngleSharp's evaluation of /// them later is skipped (see ). /// diff --git a/src/AngleSharp.Js/JsConfigurationExtensions.cs b/src/AngleSharp.Js/JsConfigurationExtensions.cs index 98e80bc8..b7d7f4f6 100644 --- a/src/AngleSharp.Js/JsConfigurationExtensions.cs +++ b/src/AngleSharp.Js/JsConfigurationExtensions.cs @@ -65,6 +65,21 @@ public static IConfiguration WithEventLoop(this IConfiguration configuration, Fu public static IConfiguration WithJs(this IConfiguration configuration) => configuration.WithJs(new JsScriptingOptions()); + /// + /// Sets scripting to true, registers the JavaScript engine exposing the + /// DOM surface the given registration declares instead of the one found + /// by reflection, and returns a new configuration with the scripting + /// service and possible auxiliary services, if not yet registered. + /// + /// The configuration to use. + /// Declares the DOM types exposed to script. + /// The new configuration. + public static IConfiguration WithJs(this IConfiguration configuration, JsDomRegistration registration) => + configuration.WithJs(new JsScriptingOptions + { + DomRegistration = registration ?? throw new ArgumentNullException(nameof(registration)), + }); + /// /// Sets scripting to true, registers the JavaScript engine with the /// given options and returns a new configuration with the scripting diff --git a/src/AngleSharp.Js/JsScriptingOptions.cs b/src/AngleSharp.Js/JsScriptingOptions.cs index 5c53356f..52bcdc79 100644 --- a/src/AngleSharp.Js/JsScriptingOptions.cs +++ b/src/AngleSharp.Js/JsScriptingOptions.cs @@ -26,6 +26,15 @@ public sealed class JsScriptingOptions /// public Boolean RetainFunctionSourceText { get; set; } = true; + /// + /// Gets or sets what declares the DOM surface exposed to script. Defaults to null, which + /// discovers the surface by reflecting over the AngleSharp libraries behind the services + /// of the browsing context. Given one, nothing is reflected over and the engine exposes + /// exactly what it registers - which is what a trimmed or natively compiled application + /// needs. + /// + public JsDomRegistration DomRegistration { get; set; } + // An engine is built per window, long after the options were handed over, so // reading them then would let a later edit of the caller's object decide how // the next document behaves. The service takes this copy instead. @@ -33,6 +42,7 @@ public sealed class JsScriptingOptions { MaxCallStackDepth = MaxCallStackDepth, RetainFunctionSourceText = RetainFunctionSourceText, + DomRegistration = DomRegistration, }; } } diff --git a/src/AngleSharp.Js/JsScriptingService.cs b/src/AngleSharp.Js/JsScriptingService.cs index aa486f05..4fe8f6eb 100644 --- a/src/AngleSharp.Js/JsScriptingService.cs +++ b/src/AngleSharp.Js/JsScriptingService.cs @@ -5,6 +5,7 @@ namespace AngleSharp.Scripting using AngleSharp.Dom; using AngleSharp.Io; using AngleSharp.Js; + using AngleSharp.Js.Cache; using AngleSharp.Js.Dom; using AngleSharp.Text; using Jint; @@ -29,6 +30,7 @@ public class JsScriptingService : IScriptingService private readonly ConditionalWeakTable _contexts; private readonly Dictionary _external; private readonly JsScriptingOptions _options; + private readonly Lazy _surface; #endregion @@ -52,6 +54,13 @@ public JsScriptingService(JsScriptingOptions options) _contexts = new ConditionalWeakTable(); _external = new Dictionary(); _options = (options ?? throw new ArgumentNullException(nameof(options))).Clone(); + + // Built on the first document that runs a script, once for every one after it: what a + // registration declares does not depend on the document, and it may declare a lot. + var registration = _options.DomRegistration; + _surface = registration != null + ? new Lazy(() => JsDomSurface.Create(registration), LazyThreadSafetyMode.ExecutionAndPublication) + : null; } #endregion @@ -219,8 +228,9 @@ internal EngineInstance GetOrCreateInstance(IDocument document) if (!_contexts.TryGetValue(objectContext, out var instance)) { - var libs = GetAssemblies(document.Context).ToArray(); - instance = new EngineInstance(objectContext, _external, libs, _options); + var surface = _surface?.Value; + var libs = surface != null ? Array.Empty() : GetAssemblies(document.Context).ToArray(); + instance = new EngineInstance(objectContext, _external, libs, _options, surface); _contexts.Add(objectContext, instance); } diff --git a/src/AngleSharp.Js/Proxies/DomConstructorFunctionInstance.cs b/src/AngleSharp.Js/Proxies/DomConstructorFunctionInstance.cs index 6a95c26d..4320e106 100644 --- a/src/AngleSharp.Js/Proxies/DomConstructorFunctionInstance.cs +++ b/src/AngleSharp.Js/Proxies/DomConstructorFunctionInstance.cs @@ -4,12 +4,14 @@ namespace AngleSharp.Js.Proxies using Jint.Native.Object; using Jint.Runtime; using Jint.Runtime.Descriptors; + using System; using System.Reflection; sealed class DomConstructorFunctionInstance : Constructor { private readonly EngineInstance _instance; private readonly MethodInfo _constructorFunction; + private readonly Func _create; public DomConstructorFunctionInstance(EngineInstance instance, MethodInfo constructorFunction, string name) : base(instance.Jint, name) { @@ -27,8 +29,22 @@ public DomConstructorFunctionInstance(EngineInstance instance, MethodInfo constr instance.GetDomPrototype(constructorFunction.ReturnType), false, false, false)); } + // for a registered named constructor, see JsDomRegistration + public DomConstructorFunctionInstance(EngineInstance instance, String name, Type returnType, Func create) : base(instance.Jint, name) + { + _instance = instance; + _create = create; + Prototype = (ObjectInstance)instance.Jint.Intrinsics.Function.Get("prototype"); + SetOwnProperty("prototype", new PropertyDescriptor(instance.GetDomPrototype(returnType), false, false, false)); + } + public override ObjectInstance Construct(JsValue[] arguments, JsValue newTarget) { + if (_create != null) + { + return _instance.GetDomNode(_create.Invoke(_instance, arguments)); + } + try { return _instance.Call(_constructorFunction, _instance.Window, arguments) as ObjectInstance; diff --git a/src/AngleSharp.Js/Proxies/DomConstructorInstance.cs b/src/AngleSharp.Js/Proxies/DomConstructorInstance.cs index 84152aaf..82a4f726 100644 --- a/src/AngleSharp.Js/Proxies/DomConstructorInstance.cs +++ b/src/AngleSharp.Js/Proxies/DomConstructorInstance.cs @@ -15,6 +15,7 @@ namespace AngleSharp.Js sealed class DomConstructorInstance : Constructor { private readonly ConstructorInfo[] _constructors; + private readonly RegisteredInterface _registered; private readonly EngineInstance _instance; private readonly ObjectInstance _objectPrototype; private readonly Type _type; @@ -26,6 +27,7 @@ public DomConstructorInstance(EngineInstance engine, ConstructorDefinition defin _objectPrototype = engine.GetDomPrototype(definition.Type); _instance = engine; _constructors = definition.Overloads; + _registered = definition.Registered; _type = definition.Type; // Jint's Constructor leaves the prototype at Object.prototype, which would make a @@ -39,9 +41,18 @@ public DomConstructorInstance(EngineInstance engine, ConstructorDefinition defin // two directions still meet at one object without this end having to reach over. SetOwnProperty("prototype", new PropertyDescriptor(_objectPrototype, false, false, false)); - AddStaticMembers(definition.Type.GetStaticMembers()); + if (_registered != null) + { + _registered.AddStaticMembers(engine, this); + } + else + { + AddStaticMembers(definition.Type.GetStaticMembers()); + } } + private Boolean IsConstructible => _constructors.Length > 0 || (_registered != null && _registered.IsConstructible); + private void AddStaticMembers(StaticMember[] members) { foreach (var member in members) @@ -172,25 +183,23 @@ public override ObjectInstance Construct(JsValue[] arguments, JsValue newTarget) return _instance.ConstructCustomElement(newTarget); } - if (_constructors.Length == 0) + if (!IsConstructible) { throw new JavaScriptException(_instance.Jint.Intrinsics.TypeError, "Illegal constructor."); } + if (_registered != null) + { + // outside the try below, which would turn the error a script sees into a bare one + return WithPrototypeOf(_instance.GetDomNode(_registered.Construct(_instance, arguments)), newTarget); + } + try { var constructor = _constructors.Length == 1 ? _constructors[0] : _constructors.SelectOverload(arguments); var parameters = _instance.BuildArgs(constructor, arguments); var obj = constructor.Invoke(parameters); - var node = _instance.GetDomNode(obj); - - // A class deriving from it has the instance on its prototype chain. - if (newTarget is ObjectInstance derived && !ReferenceEquals(derived, this) && derived.Get("prototype") is ObjectInstance prototype) - { - node.Prototype = prototype; - } - - return node; + return WithPrototypeOf(_instance.GetDomNode(obj), newTarget); } catch (TargetInvocationException ex) { @@ -202,9 +211,20 @@ public override ObjectInstance Construct(JsValue[] arguments, JsValue newTarget) } } + // A class deriving from it has the instance on its prototype chain. + private ObjectInstance WithPrototypeOf(ObjectInstance node, JsValue newTarget) + { + if (newTarget is ObjectInstance derived && !ReferenceEquals(derived, this) && derived.Get("prototype") is ObjectInstance prototype) + { + node.Prototype = prototype; + } + + return node; + } + protected override JsValue Call(JsValue thisObject, JsValue[] arguments) { - if (_constructors.Length > 0) + if (IsConstructible) { throw new JavaScriptException("Only call the constructor with the new keyword."); } diff --git a/src/AngleSharp.Js/Proxies/DomEventDefinition.cs b/src/AngleSharp.Js/Proxies/DomEventDefinition.cs index aa6d35e6..5c79cc34 100644 --- a/src/AngleSharp.Js/Proxies/DomEventDefinition.cs +++ b/src/AngleSharp.Js/Proxies/DomEventDefinition.cs @@ -22,6 +22,8 @@ sealed class DomEventDefinition { private readonly MethodInfo _addHandler; private readonly MethodInfo _removeHandler; + private readonly Action _add; + private readonly Action _remove; public DomEventDefinition(MethodInfo addHandler, MethodInfo removeHandler) { @@ -29,8 +31,16 @@ public DomEventDefinition(MethodInfo addHandler, MethodInfo removeHandler) _removeHandler = removeHandler; } + // for a registered event handler, see JsDomRegistration + public DomEventDefinition(Action add, Action remove) + { + _add = add; + _remove = remove; + } + public Boolean IsSameAs(DomEventDefinition other) => - _addHandler == other._addHandler && _removeHandler == other._removeHandler; + _addHandler == other._addHandler && _removeHandler == other._removeHandler && + _add == other._add && _remove == other._remove; public JsValue GetHandler(JsValue thisObject, JsValue[] arguments) { @@ -50,7 +60,14 @@ public JsValue SetHandler(JsValue thisObject, JsValue[] arguments) if (previous != null) { - _removeHandler?.Invoke(node.Value, new Object[] { previous.Handler }); + if (_remove != null) + { + _remove.Invoke(node.Value, previous.Handler); + } + else + { + _removeHandler?.Invoke(node.Value, new Object[] { previous.Handler }); + } } var engine = node.Instance; @@ -61,7 +78,15 @@ public JsValue SetHandler(JsValue thisObject, JsValue[] arguments) var handler = function.ToEventHandler(engine); node.SetEventHandler(this, new Registration(value, handler)); - _addHandler?.Invoke(node.Value, new Object[] { handler }); + + if (_add != null) + { + _add.Invoke(node.Value, handler); + } + else + { + _addHandler?.Invoke(node.Value, new Object[] { handler }); + } } } diff --git a/src/AngleSharp.Js/Proxies/Indexer.cs b/src/AngleSharp.Js/Proxies/Indexer.cs index 12f135ff..08a42cbc 100644 --- a/src/AngleSharp.Js/Proxies/Indexer.cs +++ b/src/AngleSharp.Js/Proxies/Indexer.cs @@ -19,6 +19,7 @@ sealed class Indexer { private readonly MethodInfo _declared; private readonly ConcurrentDictionary _resolved; + private readonly Func _invoke; public Indexer(MethodInfo declared) { @@ -29,8 +30,23 @@ public Indexer(MethodInfo declared) _resolved = declared.IsPublic ? null : new ConcurrentDictionary(); } + /// + /// Creates an indexer from a registered accessor, see . It + /// has to fail the way a reflected one does - with a TargetInvocationException - as that + /// is what the callers tell an index out of range by. + /// + public Indexer(Func invoke) + { + _invoke = invoke; + } + public Object Invoke(Object target, Object[] arguments, EngineInstance engine = null) { + if (_invoke != null) + { + return _invoke.Invoke(target, arguments, engine); + } + var method = Resolve(target.GetType()); if (engine != null) diff --git a/src/AngleSharp.Js/Registration/IJsDomRegistry.cs b/src/AngleSharp.Js/Registration/IJsDomRegistry.cs new file mode 100644 index 00000000..56641a66 --- /dev/null +++ b/src/AngleSharp.Js/Registration/IJsDomRegistry.cs @@ -0,0 +1,316 @@ +namespace AngleSharp.Js +{ + using AngleSharp.Dom; + using System; + + /// + /// Takes the DOM surface a exposes to script. + /// + /// + /// The API is shaped for a source generator rather than for hand-written code: everything is + /// a strongly typed delegate, so nothing the engine does with a registered member needs + /// reflection, and what is registered is exactly what the trimmer keeps. It covers what the + /// reflection path derives from the DOM attributes, so a generator can translate those one + /// to one. + /// + public interface IJsDomRegistry + { + /// + /// Declares a DOM interface, or returns the declaration made of it before, so that a later + /// registration (e.g. of another library) can add members to it. Its interface object is + /// published on the window under the name. + /// + /// + /// The CLR type whose instances the prototype is for - usually the exported interface, + /// e.g. IElement. An object gets the prototype of the most derived type it implements. + /// + /// The DOM name, e.g. "Element". + /// The declaration to add members to. + IJsTypeRegistration Type(String name) where T : class; + + /// + /// Declares an interface mixin (e.g. ParentNode), whose members are added to every type + /// including it. Its interface object is published like the one of a type, unless + /// declared as browsers have + /// it, but an object never gets its prototype: a mixin is not a link of the prototype chain. + /// + /// The CLR type the members are invoked on, e.g. IParentNode. + /// The DOM name, e.g. "ParentNode". + /// The declaration to add members to. + IJsTypeRegistration Mixin(String name) where T : class; + + /// + /// Declares an object of constants published on the window, as the reflection path does + /// for a numeric DOM enum. Named like an interface, the constants are added to its + /// interface object instead (e.g. Node.ELEMENT_NODE). + /// + /// The name the object is published under. + /// The declaration to add constants to. + IJsConstantsRegistration Constants(String name); + + /// + /// Declares a WebIDL enumeration: values of the enum are given to script as the + /// registered strings, and the strings are accepted for the enum. + /// + /// The CLR enum. + /// The declaration to add the literals to. + IJsLiteralsRegistration Literals() where TEnum : struct, Enum; + + /// + /// Declares a named constructor (e.g. Image or Option), which is another way of creating + /// a registered type rather than a type of its own. + /// + /// The registered type it creates. + /// The name the constructor is published under. + /// Creates the object from the arguments script passed. + /// The number of required arguments, as Function.length reports. + void ConstructorFunction(String name, Func create, Int32 length = 0) where T : class; + + /// + /// Declares an object every window gets one of under the given name. + /// + /// The name the object is published under. + /// Creates the object for a window. + void Instance(String name, Func create); + } + + /// + /// The declaration of one DOM interface or mixin. + /// + /// + /// Declaring a member again under the same name replaces the earlier declaration, so a + /// later library wins. The exception are declarations carrying a + /// : those of the same name accumulate as overloads, picked per + /// call by WebIDL's overload resolution. + /// + /// The CLR type the members are invoked on. + public interface IJsTypeRegistration where T : class + { + /// + /// Chains the prototype of this type to the one of the given type, which also has to be + /// registered, as Element.prototype is chained to Node.prototype. + /// + /// The registered type to inherit from. + /// The declaration. + IJsTypeRegistration Inherits() where TBase : class; + + /// + /// Adds the members of a registered mixin to this type. Members of the type itself take + /// precedence over those of the mixin. + /// + /// The registered mixin. + /// The declaration. + IJsTypeRegistration Includes() where TMixin : class; + + /// + /// Publishes no interface object on the window ([LegacyNoInterfaceObject]), so script cannot + /// name the type, and the prototype carries no "constructor". The type can then have + /// neither an alias, a constructor nor static members; its constants stay on the prototype. + /// + /// The declaration. + IJsTypeRegistration WithoutInterfaceObject(); + + /// + /// Publishes the interface object under another name as well, e.g. a legacy one. + /// + /// The additional name. + /// The declaration. + IJsTypeRegistration Alias(String name); + + /// + /// Makes the interface object constructible with "new". Without a constructor, it throws + /// "Illegal constructor", as HTMLElement does. + /// + /// Creates the object from the arguments script passed. + /// The number of required arguments, as Function.length reports. + /// The declaration. + IJsTypeRegistration Constructor(Func create, Int32 length = 0); + + /// + /// Adds a constructor overload. + /// + /// Creates the object from the arguments script passed. + /// What the overload takes, which picks it for a call. + /// The declaration. + IJsTypeRegistration Constructor(Func create, JsDomSignature signature); + + /// + /// Declares an attribute, which is read-only without a setter. + /// + /// The type of the attribute. + /// The DOM name of the attribute. + /// Reads the attribute. + /// Writes the attribute, if it can be written. + /// The WebIDL extended attributes of the attribute. + /// The declaration. + IJsTypeRegistration Property(String name, Func getter, Action setter = null, JsDomPropertyFlags flags = JsDomPropertyFlags.None); + + /// + /// Declares a read-only attribute an assignment to which is forwarded to an attribute of + /// its value ([PutForwards]), as element.style = '...' sets element.style.cssText. + /// + /// The type of the attribute. + /// The DOM name of the attribute. + /// Reads the attribute. + /// The DOM name of the attribute of the value to assign. + /// The declaration. + IJsTypeRegistration ForwardingProperty(String name, Func getter, String forwardTo); + + /// + /// Declares an operation giving a result. + /// + /// The DOM name of the operation. + /// Runs the operation with the arguments script passed. + /// The number of required arguments, as Function.length reports. + /// The declaration. + IJsTypeRegistration Method(String name, Func invoke, Int32 length = 0); + + /// + /// Declares an operation giving undefined. + /// + /// The DOM name of the operation. + /// Runs the operation with the arguments script passed. + /// The number of required arguments, as Function.length reports. + /// The declaration. + IJsTypeRegistration Method(String name, Action invoke, Int32 length = 0); + + /// + /// Adds an overload of an operation giving a result. + /// + /// The DOM name of the operation. + /// Runs the operation with the arguments script passed. + /// What the overload takes, which picks it for a call. + /// The declaration. + IJsTypeRegistration Method(String name, Func invoke, JsDomSignature signature); + + /// + /// Adds an overload of an operation giving undefined. + /// + /// The DOM name of the operation. + /// Runs the operation with the arguments script passed. + /// What the overload takes, which picks it for a call. + /// The declaration. + IJsTypeRegistration Method(String name, Action invoke, JsDomSignature signature); + + /// + /// Declares an event handler attribute (e.g. onclick): assigning a function subscribes + /// it, assigning another one or null unsubscribes it again. + /// + /// The DOM name of the attribute. + /// Subscribes the handler. + /// Unsubscribes the handler. + /// The declaration. + IJsTypeRegistration EventHandler(String name, Action add, Action remove); + + /// + /// Declares a constant, which is found on the interface object and on the prototype. + /// + /// The DOM name of the constant. + /// The value of the constant. + /// The declaration. + IJsTypeRegistration Constant(String name, Double value); + + /// + /// Declares a static operation, which is found on the interface object. + /// + /// The DOM name of the operation. + /// Runs the operation with the arguments script passed. + /// The number of required arguments, as Function.length reports. + /// The declaration. + IJsTypeRegistration Static(String name, Func invoke, Int32 length = 0); + + /// + /// Adds an overload of a static operation. + /// + /// The DOM name of the operation. + /// Runs the operation with the arguments script passed. + /// What the overload takes, which picks it for a call. + /// The declaration. + IJsTypeRegistration Static(String name, Func invoke, JsDomSignature signature); + + /// + /// Declares a static attribute, which is found on the interface object. + /// + /// The type of the attribute. + /// The DOM name of the attribute. + /// Reads the attribute. + /// Writes the attribute, if it can be written. + /// The declaration. + IJsTypeRegistration StaticProperty(String name, Func getter, Action setter = null); + + /// + /// Declares an indexed property getter: obj[0] reads it. An index out of range is told + /// by throwing an . + /// + /// Reads the item at the index. + /// The declaration. + IJsTypeRegistration Indexer(Func getter); + + /// + /// Declares the type an array-like collection (e.g. NodeList): indices and length are + /// read from these two, and the object is iterable. + /// + /// Gets the number of items. + /// Gets the item at an index below the length. + /// The declaration. + IJsTypeRegistration Collection(Func length, Func item); + + /// + /// Declares a named property getter and, optionally, setter: obj.foo reads a name that is + /// no member of the prototype through it. A null result means there is no such entry. + /// For an (a dataset) the camel-cased property name is turned + /// into the dashed attribute name first. + /// + /// The type of an entry. + /// Reads the entry of the name. + /// Writes the entry of the name, if entries can be written. + /// The declaration. + IJsTypeRegistration NamedIndexer(Func getter, Action setter = null); + } + + /// + /// The declaration of an object of constants. + /// + public interface IJsConstantsRegistration + { + /// + /// Declares a constant. + /// + /// The name of the constant. + /// The value of the constant. + /// The declaration. + IJsConstantsRegistration Constant(String name, Double value); + } + + /// + /// The declaration of a WebIDL enumeration. + /// + /// The CLR enum. + public interface IJsLiteralsRegistration where TEnum : struct, Enum + { + /// + /// Declares the string standing for a value of the enum. + /// + /// The value of the enum. + /// The string script sees and passes. + /// The declaration. + IJsLiteralsRegistration Literal(TEnum value, String literal); + } + + /// + /// The WebIDL extended attributes of a registered attribute. + /// + [Flags] + public enum JsDomPropertyFlags + { + /// + /// An ordinary attribute. + /// + None = 0, + /// + /// [SameObject]: script gets the same object each time, even if the CLR getter creates a + /// new one per read. + /// + SameObject = 1, + } +} diff --git a/src/AngleSharp.Js/Registration/JsCallback.cs b/src/AngleSharp.Js/Registration/JsCallback.cs new file mode 100644 index 00000000..54541fa9 --- /dev/null +++ b/src/AngleSharp.Js/Registration/JsCallback.cs @@ -0,0 +1,71 @@ +namespace AngleSharp.Js +{ + using Jint; + using Jint.Native; + using Jint.Native.Function; + using Jint.Runtime; + using System; + + /// + /// A function script passed to a registered operation. + /// + /// + /// The reflection path turns a callback into whatever delegate type the parameter has by + /// compiling an expression tree, which native AoT cannot do. A registration adapts this object + /// to its delegate type instead, in code the generator writes: + /// args.GetCallback(0) is JsCallback cb ? (a, b) => cb.Invoke(a, b) : null. + /// + public sealed class JsCallback + { + private readonly Function _function; + private readonly EngineInstance _engine; + + internal JsCallback(Function function, EngineInstance engine) + { + _function = function; + _engine = engine; + } + + /// + /// Calls the function with undefined as this. + /// + /// The arguments to pass. + /// The result of the function, or null if it threw. + public Object Invoke(params Object[] arguments) => Call(null, arguments); + + /// + /// Calls the function. What it throws is reported to the window like an error of a + /// listener, as nothing on the CLR side could catch it meaningfully. + /// + /// The receiver of the call. + /// The arguments to pass. + /// The result of the function, or null if it threw. + public Object Call(Object thisArgument, params Object[] arguments) + { + arguments = arguments ?? Array.Empty(); + var values = new JsValue[arguments.Length]; + + for (var i = 0; i < values.Length; i++) + { + values[i] = arguments[i].ToJsValue(_engine); + } + + _engine.EnterScript(); + + try + { + var receiver = thisArgument != null ? thisArgument.ToJsValue(_engine) : JsValue.Undefined; + return _function.Call(receiver, values).FromJsValue(); + } + catch (JavaScriptException error) + { + _engine.ReportError(error); + return null; + } + finally + { + _engine.LeaveScript(); + } + } + } +} diff --git a/src/AngleSharp.Js/Registration/JsDomArguments.cs b/src/AngleSharp.Js/Registration/JsDomArguments.cs new file mode 100644 index 00000000..3cfd5950 --- /dev/null +++ b/src/AngleSharp.Js/Registration/JsDomArguments.cs @@ -0,0 +1,75 @@ +namespace AngleSharp.Js +{ + using AngleSharp.Dom; + using Jint; + using Jint.Native; + using System; + + /// + /// The arguments script passed to a registered operation, converted on request. + /// + /// + /// A struct handed by value, so a call costs no allocation beyond what Jint made already. The + /// conversion is the one the reflection path applies to a parameter of the same type, which + /// keeps both paths agreeing on what e.g. a number passed for a string becomes. + /// + public readonly struct JsDomArguments + { + private readonly EngineInstance _engine; + private readonly JsValue[] _values; + + internal JsDomArguments(EngineInstance engine, JsValue[] values) + { + _engine = engine; + _values = values ?? Array.Empty(); + } + + /// + /// Gets the number of arguments passed. + /// + public Int32 Length => _values.Length; + + /// + /// Gets the window of the engine, which some operations take implicitly. + /// + public IWindow Window => _engine.Window.Value as IWindow; + + /// + /// Gets if the argument was passed, and is not undefined - the test WebIDL applies to an + /// optional argument. + /// + /// The position of the argument. + /// True if there is a value for it. + public Boolean Has(Int32 index) => index >= 0 && index < _values.Length && !_values[index].IsUndefined(); + + /// + /// Gets the argument converted to the given type, or the default of the type if none was + /// passed. + /// + /// The type of the parameter. + /// The position of the argument. + /// The converted argument. + public TValue Get(Int32 index) => Get(index, default(TValue)); + + /// + /// Gets the argument converted to the given type, or the fallback if it was not passed. + /// + /// The type of the parameter. + /// The position of the argument. + /// The default value of an optional parameter. + /// The converted argument. + public TValue Get(Int32 index, TValue fallback) => + Has(index) && _values[index].As(typeof(TValue), _engine) is TValue value ? value : fallback; + + /// + /// Gets the argument as a callback, or null if it is not callable. + /// + /// The position of the argument. + /// The callback to invoke. + public JsCallback GetCallback(Int32 index) + { + var function = Has(index) ? _values[index].AsFunction(_engine) : null; + return function != null ? new JsCallback(function, _engine) : null; + } + } +} diff --git a/src/AngleSharp.Js/Registration/JsDomRegistration.cs b/src/AngleSharp.Js/Registration/JsDomRegistration.cs new file mode 100644 index 00000000..8f2112bd --- /dev/null +++ b/src/AngleSharp.Js/Registration/JsDomRegistration.cs @@ -0,0 +1,43 @@ +namespace AngleSharp.Js +{ + using System; + + /// + /// Describes the DOM surface exposed to script, in place of discovering it by reflection. + /// + /// + /// Given one, the engine exposes exactly what it registers: no assembly is scanned and no + /// attribute is read, which is what makes the surface known to the trimmer and usable under + /// native AoT. It is invoked once per scripting service, on first use, and the outcome is + /// shared by every document the service runs scripts of. Several libraries can contribute by + /// combining their registrations into one, see . + /// + /// The registry to declare the DOM types on. + public delegate void JsDomRegistration(IJsDomRegistry registry); + + /// + /// Helpers for composing instances. + /// + public static class JsDomRegistrations + { + /// + /// Combines several registrations, e.g. the ones of AngleSharp and AngleSharp.Css, into one. + /// They run in the given order, so a later one adds to or replaces what an earlier one + /// declared of the same type. + /// + /// The registrations to run. + /// The combined registration. + public static JsDomRegistration Combine(params JsDomRegistration[] registrations) + { + registrations = registrations ?? throw new ArgumentNullException(nameof(registrations)); + + return registry => + { + for (var i = 0; i < registrations.Length; i++) + { + registrations[i]?.Invoke(registry); + } + }; + } + } +} diff --git a/src/AngleSharp.Js/Registration/JsDomSignature.cs b/src/AngleSharp.Js/Registration/JsDomSignature.cs new file mode 100644 index 00000000..b1e2cb62 --- /dev/null +++ b/src/AngleSharp.Js/Registration/JsDomSignature.cs @@ -0,0 +1,74 @@ +namespace AngleSharp.Js +{ + using System; + using System.Collections.Generic; + + /// + /// What an overload of an operation or constructor takes. The parameter types are the CLR + /// types the arguments would be converted to, which is what WebIDL's overload resolution + /// matches the arguments of a call against. + /// + public sealed class JsDomSignature + { + private readonly Type[] _parameters; + + /// + /// Creates a signature whose parameters are all required. + /// + /// The types of the parameters. + public JsDomSignature(params Type[] parameters) + : this(parameters?.Length ?? 0, false, parameters) + { + } + + /// + /// Creates a signature whose leading parameters are required. + /// + /// How many of the parameters are required. + /// The types of the parameters. + public JsDomSignature(Int32 required, params Type[] parameters) + : this(required, false, parameters) + { + } + + /// + /// Creates a signature whose leading parameters are required, and whose last one may + /// take any number of arguments. + /// + /// How many of the parameters are required. + /// If the last parameter takes the remaining arguments. + /// The types of the parameters, the variadic one by its array type. + public JsDomSignature(Int32 required, Boolean variadic, params Type[] parameters) + { + _parameters = parameters ?? Array.Empty(); + + if (required < 0 || required > _parameters.Length) + { + throw new ArgumentOutOfRangeException(nameof(required)); + } + + if (variadic && (_parameters.Length == 0 || !_parameters[_parameters.Length - 1].IsArray)) + { + throw new ArgumentException("A variadic signature ends with an array type.", nameof(variadic)); + } + + Required = required; + IsVariadic = variadic; + } + + /// + /// Gets how many of the parameters are required. + /// + public Int32 Required { get; } + + /// + /// Gets if the last parameter takes the remaining arguments. + /// + public Boolean IsVariadic { get; } + + /// + /// Gets the types of the parameters. + /// + public IReadOnlyList Parameters => _parameters; + } +} diff --git a/src/AngleSharp.Js/Registration/JsDomSurface.cs b/src/AngleSharp.Js/Registration/JsDomSurface.cs new file mode 100644 index 00000000..70749c31 --- /dev/null +++ b/src/AngleSharp.Js/Registration/JsDomSurface.cs @@ -0,0 +1,830 @@ +namespace AngleSharp.Js.Cache +{ + using AngleSharp.Dom; + using AngleSharp.Js.Proxies; + using Jint.Native; + using Jint.Native.Object; + using Jint.Runtime.Descriptors; + using Jint.Runtime.Interop; + using System; + using System.Collections.Concurrent; + using System.Collections.Generic; + using System.Reflection; + + /// + /// The DOM surface a declared, standing in for the libraries + /// otherwise reflected over. + /// + /// + /// It produces the same , and + /// the reflection path does, so prototypes, receivers and the + /// engine's per-realm handling stay one code path; only where they come from differs. Like + /// it is shared by every engine of the service that built it: + /// what is filled in by the registration is only read afterwards, and what is computed on + /// demand sits in concurrent caches. + /// + sealed class JsDomSurface + { + private const String ConstructorName = "constructor"; + + private readonly Registry _registry; + private readonly ConcurrentDictionary _canonical; + private readonly ConcurrentDictionary _shapes; + private readonly Func _canonicalize; + private readonly Func _build; + + private JsDomSurface(Registry registry) + { + _registry = registry; + _canonical = new ConcurrentDictionary(); + _shapes = new ConcurrentDictionary(); + + // cached once, so that a lookup - hit or miss - allocates no delegate + _canonicalize = FindCanonical; + _build = BuildShape; + } + + public static JsDomSurface Create(JsDomRegistration registration) + { + var registry = new Registry(); + registration.Invoke(registry); + registry.Complete(); + return new JsDomSurface(registry); + } + + /// + /// Gets the registered type the prototype of an object of the given type is built from: + /// the most derived registered type it is assignable to, or Object if there is none. + /// + public Type Canonicalize(Type type) => _canonical.GetOrAdd(type, _canonicalize); + + public DomShape GetShape(Type type) => _shapes.GetOrAdd(type, _build); + + public IndexedCollection GetCollection(Type type) => + _registry.Types.TryGetValue(type, out var registered) ? registered.Collection : null; + + public String GetLiteral(Enum value) => + _registry.LiteralNames.TryGetValue(value, out var literal) ? literal : null; + + public Boolean TryParseLiteral(Type type, String literal, out Object value) + { + value = null; + return _registry.LiteralValues.TryGetValue(type, out var values) && values.TryGetValue(literal, out value); + } + + /// + /// Publishes on the window what the reflection path finds in the exported types of the + /// libraries, in the same order: interface objects and constants, named constructors, + /// instances. + /// + public void Publish(EngineInstance engine, ObjectInstance window) + { + foreach (var registered in _registry.Ordered) + { + if (registered.Definition == null) + { + continue; + } + + foreach (var name in registered.Definition.Names) + { + window.FastSetProperty(name, EngineExtensions.CreateConstructorProperty(engine, registered.Definition)); + } + } + + foreach (var constants in _registry.ConstantObjects) + { + EngineExtensions.SetEnumLiteral(engine, window, constants); + } + + foreach (var function in _registry.ConstructorFunctions) + { + var instance = new DomConstructorFunctionInstance(engine, function.Name, function.Type, function.Create); + instance.DefineOwnProperty("length", new PropertyDescriptor(function.Length, false, false, true)); + window.FastSetProperty(function.Name, new PropertyDescriptor(instance, false, true, false)); + } + + foreach (var instance in _registry.Instances) + { + var value = instance.Value.Invoke((IWindow)engine.Window.Value); + + if (value != null) + { + window.FastSetProperty(instance.Key, new PropertyDescriptor(engine.GetDomNode(value), false, true, false)); + } + } + } + + private Type FindCanonical(Type type) + { + if (_registry.Types.ContainsKey(type)) + { + return type; + } + + var best = default(Type); + var ordered = _registry.Ordered; + + // Registration order breaks a tie between unrelated interfaces, so the outcome does + // not depend on the order reflection happens to list them in. A mixin is no link of + // the prototype chain, so it never is the prototype of an object. + for (var i = 0; i < ordered.Count; i++) + { + var candidate = ordered[i]; + + if (!candidate.IsMixin && candidate.Type.IsAssignableFrom(type) && + (best == null || best.IsAssignableFrom(candidate.Type) && best != candidate.Type)) + { + best = candidate.Type; + } + } + + return best ?? typeof(Object); + } + + private DomShape BuildShape(Type type) + { + var registered = _registry.Types[type]; + var builder = new JsObjectShape.Builder(); + var members = new Dictionary(StringComparer.Ordinal); + + // the window's members are called bare, see DomShapeBuilder + var perRealm = typeof(IWindow).IsAssignableFrom(type); + builder.ToStringTag(registered.Name); + Declare(builder, registered, members, perRealm); + + foreach (var mixin in registered.Includes) + { + Declare(builder, _registry.Types[mixin], members, perRealm); + } + + if (perRealm) + { + DeclareInherited(builder, registered, members); + } + + foreach (var constant in registered.Interface.Constants) + { + if (!members.ContainsKey(constant.Key)) + { + builder.Constant(constant.Key, JsNumber.Create(constant.Value), true); + } + } + + // the very object script reads off the window under the type's name, if there is one + if (registered.Definition != null) + { + builder.PerRealmSlot(ConstructorName, DomShapeBuilder.CreateConstructor, enumerable: false, writable: true, configurable: true); + } + + return new DomShape(type, registered.BaseType ?? typeof(Object), registered.Name, builder.Build(), registered.Indexers, registered.Definition, members); + } + + private static void Declare(JsObjectShape.Builder builder, RegisteredType registered, Dictionary members, Boolean perRealm) + { + for (var i = 0; i < registered.Order.Count; i++) + { + var name = registered.Order[i]; + + if (!members.ContainsKey(name) && !String.Equals(name, ConstructorName, StringComparison.Ordinal)) + { + var member = registered.Members[name]; + member.Declare(builder, name, perRealm); + members.Add(name, member); + } + } + } + + // A bare addEventListener(...) on the window has to work even though EventTarget declares it. + private void DeclareInherited(JsObjectShape.Builder builder, RegisteredType registered, Dictionary members) + { + for (var baseType = registered.BaseType; baseType != null && _registry.Types.TryGetValue(baseType, out var ancestor); baseType = ancestor.BaseType) + { + DeclareInheritedOf(builder, ancestor, members); + + foreach (var mixin in ancestor.Includes) + { + DeclareInheritedOf(builder, _registry.Types[mixin], members); + } + } + } + + private static void DeclareInheritedOf(JsObjectShape.Builder builder, RegisteredType ancestor, Dictionary members) + { + for (var i = 0; i < ancestor.Order.Count; i++) + { + var name = ancestor.Order[i]; + + if (!members.ContainsKey(name) && !String.Equals(name, ConstructorName, StringComparison.Ordinal)) + { + var member = ancestor.Members[name]; + member.DeclareInherited(builder, name); + members.Add(name, member); + } + } + } + + private sealed class RegisteredType + { + public RegisteredType(Type type, String name, Boolean isMixin) + { + Type = type; + Name = name; + IsMixin = isMixin; + Names = new List { name }; + Includes = new List(); + Order = new List(); + Members = new Dictionary(StringComparer.Ordinal); + Interface = new RegisteredInterface(); + } + + public Type Type { get; } + + public String Name { get; } + + public Boolean IsMixin { get; } + + public Boolean HasInterfaceObject { get; set; } = true; + + public Type BaseType { get; set; } + + public List Names { get; } + + public List Includes { get; } + + public List Order { get; } + + public Dictionary Members { get; } + + public RegisteredInterface Interface { get; } + + public Indexer NumericIndexer { get; set; } + + public Indexer NamedGetter { get; set; } + + public Indexer NamedSetter { get; set; } + + public IndexedCollection Collection { get; set; } + + public DomIndexers Indexers { get; private set; } + + public ConstructorDefinition Definition { get; private set; } + + // a member declared again replaces the earlier one in place, as a later library wins + public void Define(String name, DomShapeBuilder.Member member) + { + Registry.CheckName(name); + + if (!Members.ContainsKey(name)) + { + Order.Add(name); + } + + Members[name] = member; + } + + public void Complete() + { + if (NumericIndexer != null || NamedGetter != null || NamedSetter != null) + { + Indexers = new DomIndexers(NumericIndexer, NamedGetter, NamedSetter, + typeof(IStringMap).IsAssignableFrom(Type) ? DomIndexers.ToDatasetName : null); + } + + Interface.Complete(); + Definition = HasInterfaceObject ? new ConstructorDefinition(Type, Names.ToArray(), Interface) : null; + } + } + + private sealed class RegisteredConstructorFunction + { + public RegisteredConstructorFunction(String name, Type type, Func create, Int32 length) + { + Name = name; + Type = type; + Create = create; + Length = length; + } + + public String Name { get; } + + public Type Type { get; } + + public Func Create { get; } + + public Int32 Length { get; } + } + + private sealed class Registry : IJsDomRegistry + { + private readonly Dictionary> _constants = new Dictionary>(StringComparer.Ordinal); + private readonly List _constantOrder = new List(); + + public Dictionary Types { get; } = new Dictionary(); + + public List Ordered { get; } = new List(); + + public List ConstantObjects { get; } = new List(); + + public List ConstructorFunctions { get; } = new List(); + + public List>> Instances { get; } = new List>>(); + + // keyed by the boxed value, whose equality is the one of the enum + public Dictionary LiteralNames { get; } = new Dictionary(); + + public Dictionary> LiteralValues { get; } = new Dictionary>(); + + public static void CheckName(String name) + { + if (String.IsNullOrEmpty(name)) + { + throw new ArgumentException("A DOM name must not be empty.", nameof(name)); + } + } + + public IJsTypeRegistration Type(String name) where T : class => Declare(name, false); + + public IJsTypeRegistration Mixin(String name) where T : class => Declare(name, true); + + public IJsConstantsRegistration Constants(String name) + { + CheckName(name); + + if (!_constants.TryGetValue(name, out var members)) + { + members = new List(); + _constants.Add(name, members); + _constantOrder.Add(name); + } + + return new ConstantsRegistration(members); + } + + public IJsLiteralsRegistration Literals() where TEnum : struct, Enum + { + if (!LiteralValues.TryGetValue(typeof(TEnum), out var values)) + { + values = new Dictionary(StringComparer.Ordinal); + LiteralValues.Add(typeof(TEnum), values); + } + + return new LiteralsRegistration(this, values); + } + + public void ConstructorFunction(String name, Func create, Int32 length = 0) where T : class + { + CheckName(name); + create = create ?? throw new ArgumentNullException(nameof(create)); + ConstructorFunctions.Add(new RegisteredConstructorFunction(name, typeof(T), (instance, arguments) => + { + using (var scope = RegisteredScope.Enter(instance, null, arguments)) + { + try + { + var result = create.Invoke(new JsDomArguments(instance, arguments)); + scope.Complete(); + return result; + } + catch (Exception error) when (RegisteredCall.IsHostError(error)) + { + throw RegisteredCall.ToScriptError(instance, error); + } + } + }, length)); + } + + public void Instance(String name, Func create) + { + CheckName(name); + Instances.Add(new KeyValuePair>(name, create ?? throw new ArgumentNullException(nameof(create)))); + } + + private IJsTypeRegistration Declare(String name, Boolean isMixin) where T : class + { + CheckName(name); + + if (Types.TryGetValue(typeof(T), out var existing)) + { + if (!String.Equals(existing.Name, name, StringComparison.Ordinal) || existing.IsMixin != isMixin) + { + throw new InvalidOperationException($"{typeof(T)} is already registered as {(existing.IsMixin ? "mixin" : "type")} '{existing.Name}'."); + } + } + else + { + existing = new RegisteredType(typeof(T), name, isMixin); + Types.Add(typeof(T), existing); + Ordered.Add(existing); + } + + return new TypeRegistration(existing); + } + + // Checked once everything is registered, as a base may be declared after its heir. + public void Complete() + { + foreach (var registered in Ordered) + { + if (registered.BaseType != null && (!Types.TryGetValue(registered.BaseType, out var baseType) || baseType.IsMixin)) + { + throw new InvalidOperationException($"'{registered.Name}' inherits from {registered.BaseType}, which is not a registered type."); + } + + foreach (var mixin in registered.Includes) + { + if (!Types.TryGetValue(mixin, out var included) || !included.IsMixin) + { + throw new InvalidOperationException($"'{registered.Name}' includes {mixin}, which is not a registered mixin."); + } + } + + if (registered.IsMixin && (registered.BaseType != null || registered.Includes.Count > 0 || registered.Interface.IsConstructible)) + { + throw new InvalidOperationException($"The mixin '{registered.Name}' can neither inherit, include nor be constructed."); + } + + if (!registered.HasInterfaceObject && (registered.Names.Count > 1 || registered.Interface.IsConstructible || registered.Interface.HasStatics)) + { + throw new InvalidOperationException($"'{registered.Name}' has no interface object to carry an alias, a constructor or static members."); + } + + registered.Complete(); + } + + foreach (var name in _constantOrder) + { + ConstantObjects.Add(new EnumLiteralDefinition(name, _constants[name].ToArray())); + } + } + } + + private sealed class ConstantsRegistration : IJsConstantsRegistration + { + private readonly List _members; + + public ConstantsRegistration(List members) + { + _members = members; + } + + public IJsConstantsRegistration Constant(String name, Double value) + { + Registry.CheckName(name); + _members.Add(new EnumLiteralMember(name, value)); + return this; + } + } + + private sealed class LiteralsRegistration : IJsLiteralsRegistration where TEnum : struct, Enum + { + private readonly Registry _registry; + private readonly Dictionary _values; + + public LiteralsRegistration(Registry registry, Dictionary values) + { + _registry = registry; + _values = values; + } + + public IJsLiteralsRegistration Literal(TEnum value, String literal) + { + literal = literal ?? throw new ArgumentNullException(nameof(literal)); + Object boxed = value; + _registry.LiteralNames[boxed] = literal; + _values[literal] = boxed; + return this; + } + } + + private sealed class TypeRegistration : IJsTypeRegistration where T : class + { + private readonly RegisteredType _type; + + public TypeRegistration(RegisteredType type) + { + _type = type; + } + + public IJsTypeRegistration Inherits() where TBase : class + { + if (typeof(TBase) == typeof(T) || !typeof(TBase).IsAssignableFrom(typeof(T))) + { + throw new InvalidOperationException($"'{_type.Name}' cannot inherit from {typeof(TBase)}."); + } + + _type.BaseType = typeof(TBase); + return this; + } + + public IJsTypeRegistration Includes() where TMixin : class + { + if (typeof(TMixin) == typeof(T) || !typeof(TMixin).IsAssignableFrom(typeof(T))) + { + throw new InvalidOperationException($"'{_type.Name}' cannot include {typeof(TMixin)}."); + } + + if (!_type.Includes.Contains(typeof(TMixin))) + { + _type.Includes.Add(typeof(TMixin)); + } + + return this; + } + + public IJsTypeRegistration WithoutInterfaceObject() + { + _type.HasInterfaceObject = false; + return this; + } + + public IJsTypeRegistration Alias(String name) + { + Registry.CheckName(name); + + if (!_type.Names.Contains(name)) + { + _type.Names.Add(name); + } + + return this; + } + + public IJsTypeRegistration Constructor(Func create, Int32 length = 0) + { + _type.Interface.AddConstructor(create ?? throw new ArgumentNullException(nameof(create)), null, length); + return this; + } + + public IJsTypeRegistration Constructor(Func create, JsDomSignature signature) + { + _type.Interface.AddConstructor( + create ?? throw new ArgumentNullException(nameof(create)), + signature ?? throw new ArgumentNullException(nameof(signature)), + 0); + return this; + } + + public IJsTypeRegistration Property(String name, Func getter, Action setter = null, JsDomPropertyFlags flags = JsDomPropertyFlags.None) + { + _type.Define(name, new RegisteredProperty(getter ?? throw new ArgumentNullException(nameof(getter)), setter, flags, null)); + return this; + } + + public IJsTypeRegistration ForwardingProperty(String name, Func getter, String forwardTo) + { + Registry.CheckName(forwardTo); + _type.Define(name, new RegisteredProperty(getter ?? throw new ArgumentNullException(nameof(getter)), null, JsDomPropertyFlags.None, forwardTo)); + return this; + } + + public IJsTypeRegistration Method(String name, Func invoke, Int32 length = 0) + { + _type.Define(name, new RegisteredMethod(invoke ?? throw new ArgumentNullException(nameof(invoke)), length)); + return this; + } + + public IJsTypeRegistration Method(String name, Action invoke, Int32 length = 0) => + Method(name, ToFunc(invoke), length); + + public IJsTypeRegistration Method(String name, Func invoke, JsDomSignature signature) + { + invoke = invoke ?? throw new ArgumentNullException(nameof(invoke)); + signature = signature ?? throw new ArgumentNullException(nameof(signature)); + + if (_type.Members.TryGetValue(name ?? String.Empty, out var existing) && existing is RegisteredMethod method && method.IsOverloadSet) + { + method.Add(invoke, signature); + } + else + { + _type.Define(name, new RegisteredMethod(invoke, signature)); + } + + return this; + } + + public IJsTypeRegistration Method(String name, Action invoke, JsDomSignature signature) => + Method(name, ToFunc(invoke), signature); + + public IJsTypeRegistration EventHandler(String name, Action add, Action remove) + { + add = add ?? throw new ArgumentNullException(nameof(add)); + remove = remove ?? throw new ArgumentNullException(nameof(remove)); + var definition = new DomEventDefinition((target, handler) => add.Invoke((T)target, handler), (target, handler) => remove.Invoke((T)target, handler)); + _type.Define(name, new RegisteredEvent(definition)); + return this; + } + + public IJsTypeRegistration Constant(String name, Double value) + { + Registry.CheckName(name); + _type.Interface.AddConstant(name, value); + return this; + } + + public IJsTypeRegistration Static(String name, Func invoke, Int32 length = 0) + { + Registry.CheckName(name); + _type.Interface.DefineStatic(name, new RegisteredStatic(invoke ?? throw new ArgumentNullException(nameof(invoke)), length)); + return this; + } + + public IJsTypeRegistration Static(String name, Func invoke, JsDomSignature signature) + { + Registry.CheckName(name); + invoke = invoke ?? throw new ArgumentNullException(nameof(invoke)); + signature = signature ?? throw new ArgumentNullException(nameof(signature)); + + if (_type.Interface.TryGetStatic(name, out var existing) && existing.IsOverloadSet) + { + existing.Add(invoke, signature); + } + else + { + _type.Interface.DefineStatic(name, new RegisteredStatic(invoke, signature)); + } + + return this; + } + + public IJsTypeRegistration StaticProperty(String name, Func getter, Action setter = null) + { + Registry.CheckName(name); + _type.Interface.DefineStatic(name, RegisteredStatic.ForProperty(getter ?? throw new ArgumentNullException(nameof(getter)), setter)); + return this; + } + + public IJsTypeRegistration Indexer(Func getter) + { + getter = getter ?? throw new ArgumentNullException(nameof(getter)); + _type.NumericIndexer = new Indexer((target, arguments, engine) => Guard(() => getter.Invoke((T)target, (Int32)arguments[0]))); + return this; + } + + public IJsTypeRegistration Collection(Func length, Func item) + { + length = length ?? throw new ArgumentNullException(nameof(length)); + item = item ?? throw new ArgumentNullException(nameof(item)); + _type.Collection = IndexedCollection.Create(target => length.Invoke((T)target), (target, index) => item.Invoke((T)target, index)); + + // what the reflection path has for a collection too: its numeric half is the + // engine's, but an ordinary node proxy of it is still indexed + if (_type.NumericIndexer == null) + { + Indexer(item); + } + + return this; + } + + public IJsTypeRegistration NamedIndexer(Func getter, Action setter = null) + { + getter = getter ?? throw new ArgumentNullException(nameof(getter)); + _type.NamedGetter = new Indexer((target, arguments, engine) => Guard(() => getter.Invoke((T)target, (String)arguments[0]))); + _type.NamedSetter = setter == null ? null : new Indexer((target, arguments, engine) => Guard(() => + { + var value = arguments[1] is JsValue js ? js.As(typeof(TValue), engine) : arguments[1]; + setter.Invoke((T)target, (String)arguments[0], value is TValue typed ? typed : default); + return null; + })); + return this; + } + + private static Func ToFunc(Action invoke) + { + invoke = invoke ?? throw new ArgumentNullException(nameof(invoke)); + return (target, arguments) => + { + invoke.Invoke(target, arguments); + return null; + }; + } + + // An indexer fails like a reflected one, which is how an index out of range is told. + private static Object Guard(Func run) + { + try + { + return run.Invoke(); + } + catch (Exception error) when (RegisteredCall.IsHostError(error)) + { + throw new TargetInvocationException(error); + } + } + } + } + + /// + /// What a registration declared of an interface object: its constructors, static members + /// and constants. It is read by in place of reflecting + /// over the type. + /// + sealed class RegisteredInterface + { + private readonly List> _constructors = new List>(); + private readonly List _constructorSignatures = new List(); + private readonly List _staticOrder = new List(); + private readonly Dictionary _statics = new Dictionary(StringComparer.Ordinal); + private readonly List> _constants = new List>(); + private Func[] _creates; + private JsDomSignature[] _signatures; + private Int32 _length; + + public Boolean IsConstructible => _constructors.Count > 0; + + public Boolean HasStatics => _statics.Count > 0; + + public IReadOnlyList> Constants => _constants; + + public void AddConstructor(Func create, JsDomSignature signature, Int32 length) + { + // as for methods: one without a signature replaces, ones with a signature accumulate + if (signature == null || _constructorSignatures.Count == 0 || _constructorSignatures[0] == null) + { + _constructors.Clear(); + _constructorSignatures.Clear(); + } + + _constructors.Add(create); + _constructorSignatures.Add(signature); + _length = signature == null ? length : Math.Min(_constructors.Count == 1 ? Int32.MaxValue : _length, signature.Required); + } + + public void AddConstant(String name, Double value) => _constants.Add(new KeyValuePair(name, value)); + + public Boolean TryGetStatic(String name, out RegisteredStatic member) => _statics.TryGetValue(name, out member); + + public void DefineStatic(String name, RegisteredStatic member) + { + if (!_statics.ContainsKey(name)) + { + _staticOrder.Add(name); + } + + _statics[name] = member; + } + + public void Complete() + { + _creates = _constructors.ToArray(); + _signatures = _constructorSignatures.Count > 0 && _constructorSignatures[0] != null ? _constructorSignatures.ToArray() : null; + } + + public Object Construct(EngineInstance instance, JsValue[] arguments) + { + var create = _creates[RegisteredCall.Select(_signatures, arguments)]; + + using (var scope = RegisteredScope.Enter(instance, null, arguments)) + { + try + { + var result = create.Invoke(new JsDomArguments(instance, arguments)); + scope.Complete(); + return result; + } + catch (Exception error) when (RegisteredCall.IsHostError(error)) + { + throw RegisteredCall.ToScriptError(instance, error); + } + } + } + + public void AddStaticMembers(EngineInstance instance, ObjectInstance constructor) + { + var engine = instance.Jint; + + if (IsConstructible) + { + constructor.DefineOwnProperty("length", new PropertyDescriptor(_length, false, false, true)); + } + + foreach (var constant in _constants) + { + constructor.FastSetProperty(constant.Key, new PropertyDescriptor(constant.Value, false, true, false)); + } + + foreach (var name in _staticOrder) + { + var member = _statics[name]; + + if (member.IsAccessor) + { + var get = new ClrFunction(engine, "get " + name, (_, arguments) => member.Read(instance)); + var set = member.Write == null ? null : new ClrFunction(engine, "set " + name, (_, arguments) => + { + member.Write(instance, arguments.Length > 0 ? arguments[0] : JsValue.Undefined); + return JsValue.Undefined; + }); + constructor.FastSetProperty(name, new GetSetPropertyDescriptor(get, set, true, true)); + } + else + { + var function = new ClrFunction(engine, name, (_, arguments) => member.Invoke(instance, arguments), member.Length); + constructor.FastSetProperty(name, new PropertyDescriptor(function, true, true, true)); + } + } + } + } +} diff --git a/src/AngleSharp.Js/Registration/RegisteredMembers.cs b/src/AngleSharp.Js/Registration/RegisteredMembers.cs new file mode 100644 index 00000000..c064d6b9 --- /dev/null +++ b/src/AngleSharp.Js/Registration/RegisteredMembers.cs @@ -0,0 +1,413 @@ +namespace AngleSharp.Js.Cache +{ + using AngleSharp.Dom; + using AngleSharp.Html.Dom; + using Jint; + using Jint.Native; + using Jint.Native.Object; + using Jint.Runtime; + using Jint.Runtime.Interop; + using System; + using System.Collections.Generic; + + /// + /// What a call of a DOM member is wrapped in, the same for a registered member as in + /// : the engine is the current one, the reactions of custom + /// elements wait for the call to be complete, and a script the call inserted runs before it + /// returns, as in browsers. + /// + /// + /// A struct disposed by a using block, so a call costs no allocation for it - and nothing at + /// all beyond two checks when no custom element is defined and no script is inserted. + /// + readonly struct RegisteredScope : IDisposable + { + private readonly EngineInstance _instance; + private readonly List _inserted; + private readonly Boolean _holdsReactions; + + private RegisteredScope(EngineInstance instance, List inserted, Boolean holdsReactions) + { + _instance = instance; + _inserted = inserted; + _holdsReactions = holdsReactions; + } + + public static RegisteredScope Enter(EngineInstance instance, Object target, JsValue[] arguments) + { + EngineInstance.Current = instance; + var inserted = InsertedScripts.FindUnstarted(target, arguments ?? Array.Empty()); + var holdsReactions = CustomElementRegistry.IsInUse; + + if (holdsReactions) + { + CustomElementRegistry.PushReactions(); + } + + return new RegisteredScope(instance, inserted, holdsReactions); + } + + /// + /// Marks the call as having succeeded, which is when the scripts it inserted run - still + /// within the scope, as for a reflected member. + /// + public void Complete() + { + if (_inserted != null) + { + InsertedScripts.RunPrepared(_instance, _instance.Document, _inserted); + } + } + + public void Dispose() + { + if (_holdsReactions) + { + CustomElementRegistry.PopReactions(); + } + } + } + + /// + /// What every registered member shares: finding its engine and receiver, and turning what the + /// CLR throws into what script sees - the parts the reflection path does in + /// . + /// + static class RegisteredCall + { + public static EngineInstance GetEngine(JsValue thisObject) => + thisObject.GetEngineInstance() ?? throw new JavaScriptException("Illegal invocation."); + + public static T GetTarget(EngineInstance instance, JsValue thisObject) where T : class => + (thisObject is IDomProxy proxy ? proxy.Value : instance.Window.Value) as T + ?? throw new JavaScriptException("Illegal invocation."); + + // Jint's own exceptions (a script error, an exceeded constraint) pass as they are. + public static Boolean IsHostError(Exception error) => !(error is JintException); + + public static JavaScriptException ToScriptError(EngineInstance instance, Exception error) => + new JavaScriptException(instance.ToScriptValue(error)); + + /// + /// Picks the overload for a call: the only one, or the best match of the signatures. + /// + public static Int32 Select(JsDomSignature[] signatures, JsValue[] arguments) => + signatures == null || signatures.Length < 2 ? 0 : signatures.SelectSignature(arguments); + + /// + /// Adds an overload to a set, which is a single declaration without a signature until one + /// with a signature comes along - that one starts the set anew, as declaring replaces. + /// + public static void Add(ref TDelegate[] invokes, ref JsDomSignature[] signatures, TDelegate invoke, JsDomSignature signature) + { + if (signature == null || signatures == null) + { + invokes = new[] { invoke }; + signatures = signature != null ? new[] { signature } : null; + } + else + { + Array.Resize(ref invokes, invokes.Length + 1); + Array.Resize(ref signatures, signatures.Length + 1); + invokes[invokes.Length - 1] = invoke; + signatures[signatures.Length - 1] = signature; + } + } + + // What Function.length reports for a set of overloads: the fewest arguments any takes. + public static Int32 GetLength(JsDomSignature[] signatures, Int32 length) + { + if (signatures == null) + { + return length; + } + + var min = Int32.MaxValue; + + for (var i = 0; i < signatures.Length; i++) + { + min = Math.Min(min, signatures[i].Required); + } + + return min; + } + } + + sealed class RegisteredMethod : DomShapeBuilder.Member where T : class + { + private Func[] _invokes; + private JsDomSignature[] _signatures; + private Int32 _length; + + public RegisteredMethod(Func invoke, Int32 length) + { + _invokes = new[] { invoke }; + _length = length; + } + + public RegisteredMethod(Func invoke, JsDomSignature signature) + { + Add(invoke, signature); + } + + public Boolean IsOverloadSet => _signatures != null; + + public void Add(Func invoke, JsDomSignature signature) + { + RegisteredCall.Add(ref _invokes, ref _signatures, invoke, signature); + _length = RegisteredCall.GetLength(_signatures, 0); + } + + public override Boolean IsSameAs(DomShapeBuilder.Member other) => ReferenceEquals(this, other); + + public override void Declare(JsObjectShape.Builder builder, String name, Boolean perRealm) + { + if (perRealm) + { + var length = _length; + builder.PerRealmSlot( + name, + prototype => + { + var instance = DomPrototypeState.Of(prototype).Instance; + return new ClrFunction(instance.Jint, name, (thisObject, arguments) => Invoke(instance, thisObject, arguments), length); + }, + enumerable: true, + writable: true, + configurable: true); + } + else + { + builder.Method( + name, + (thisObject, arguments) => Invoke(RegisteredCall.GetEngine(thisObject), thisObject, arguments), + _length, + enumerable: true, + writable: true, + configurable: true); + } + } + + // Still asks the prototype above for the method, as it may have been patched there. + public override void DeclareInherited(JsObjectShape.Builder builder, String name) => + builder.PerRealmSlot( + name, + prototype => + { + var instance = DomPrototypeState.Of(prototype).Instance; + return new ClrFunction(instance.Jint, name, (thisObject, arguments) => + instance.Jint.Call(prototype.Prototype.Get(name), thisObject.IsObject() ? thisObject : instance.Window, arguments)); + }, + enumerable: true, + writable: true, + configurable: true); + + private JsValue Invoke(EngineInstance instance, JsValue thisObject, JsValue[] arguments) + { + var target = RegisteredCall.GetTarget(instance, thisObject); + var invoke = _invokes[RegisteredCall.Select(_signatures, arguments)]; + + using (var scope = RegisteredScope.Enter(instance, target, arguments)) + { + try + { + var result = invoke.Invoke(target, new JsDomArguments(instance, arguments)).ToJsValue(instance); + scope.Complete(); + return result; + } + catch (Exception error) when (RegisteredCall.IsHostError(error)) + { + throw RegisteredCall.ToScriptError(instance, error); + } + } + } + } + + sealed class RegisteredProperty : DomShapeBuilder.Member where T : class + { + private readonly Func _getter; + private readonly Action _setter; + private readonly Boolean _sameObject; + private readonly JsString _forwardTo; + + public RegisteredProperty(Func getter, Action setter, JsDomPropertyFlags flags, String forwardTo) + { + _getter = getter; + _setter = setter; + _sameObject = (flags & JsDomPropertyFlags.SameObject) != 0; + _forwardTo = forwardTo != null ? new JsString(forwardTo) : null; + } + + public override Boolean IsSameAs(DomShapeBuilder.Member other) => ReferenceEquals(this, other); + + // An accessor always has a receiver to find its engine by - the global object itself + // when a window member is named bare - so it needs no per-realm variant. + public override void Declare(JsObjectShape.Builder builder, String name, Boolean perRealm) => + builder.Accessor(name, Read, _forwardTo is null ? Write : Forward, enumerable: true, configurable: true); + + private JsValue Read(JsValue thisObject, JsValue[] arguments) + { + var instance = RegisteredCall.GetEngine(thisObject); + var target = RegisteredCall.GetTarget(instance, thisObject); + + using (var scope = RegisteredScope.Enter(instance, target, arguments)) + { + try + { + Object value = _getter.Invoke(target); + + // untyped, so that the node keeps its identity and its own prototype + var result = _sameObject && value != null + ? instance.GetSameObject(target, this, value, value.GetType()) + : value.ToJsValue(instance); + scope.Complete(); + return result; + } + catch (Exception error) when (RegisteredCall.IsHostError(error)) + { + throw RegisteredCall.ToScriptError(instance, error); + } + } + } + + // without a setter a write is ignored, as one to a readonly attribute is in sloppy mode + private JsValue Write(JsValue thisObject, JsValue[] arguments) + { + if (_setter == null) + { + return JsValue.Undefined; + } + + var instance = RegisteredCall.GetEngine(thisObject); + var target = RegisteredCall.GetTarget(instance, thisObject); + + using (var scope = RegisteredScope.Enter(instance, target, arguments)) + { + try + { + _setter.Invoke(target, new JsDomArguments(instance, arguments).Get(0)); + scope.Complete(); + return JsValue.Undefined; + } + catch (Exception error) when (RegisteredCall.IsHostError(error)) + { + throw RegisteredCall.ToScriptError(instance, error); + } + } + } + + // [PutForwards] is an assignment to the attribute of the value, done as script would + private JsValue Forward(JsValue thisObject, JsValue[] arguments) + { + if (Read(thisObject, arguments) is ObjectInstance value) + { + value.Set(_forwardTo, arguments.Length > 0 ? arguments[0] : JsValue.Undefined, value); + } + + return JsValue.Undefined; + } + } + + sealed class RegisteredEvent : DomShapeBuilder.Member + { + private readonly DomEventDefinition _definition; + + public RegisteredEvent(DomEventDefinition definition) + { + _definition = definition; + } + + public override Boolean IsSameAs(DomShapeBuilder.Member other) => ReferenceEquals(this, other); + + public override void Declare(JsObjectShape.Builder builder, String name, Boolean perRealm) => + builder.Accessor(name, _definition.GetHandler, _definition.SetHandler, enumerable: true, configurable: true); + } + + /// + /// A static member of a registered interface, found on its interface object. + /// + sealed class RegisteredStatic + { + private Func[] _invokes; + private JsDomSignature[] _signatures; + private Int32 _length; + + public RegisteredStatic(Func invoke, Int32 length) + { + _invokes = new[] { invoke }; + _length = length; + } + + public RegisteredStatic(Func invoke, JsDomSignature signature) + { + Add(invoke, signature); + } + + public RegisteredStatic(Func read, Action write) + { + Read = read; + Write = write; + } + + public Boolean IsOverloadSet => _signatures != null; + + public Boolean IsAccessor => Read != null; + + public Func Read { get; } + + public Action Write { get; } + + public Int32 Length => _length; + + public void Add(Func invoke, JsDomSignature signature) + { + RegisteredCall.Add(ref _invokes, ref _signatures, invoke, signature); + _length = RegisteredCall.GetLength(_signatures, 0); + } + + public JsValue Invoke(EngineInstance instance, JsValue[] arguments) + { + var invoke = _invokes[RegisteredCall.Select(_signatures, arguments)]; + + using (var scope = RegisteredScope.Enter(instance, null, arguments)) + { + try + { + var result = invoke.Invoke(new JsDomArguments(instance, arguments)).ToJsValue(instance); + scope.Complete(); + return result; + } + catch (Exception error) when (RegisteredCall.IsHostError(error)) + { + throw RegisteredCall.ToScriptError(instance, error); + } + } + } + + public static RegisteredStatic ForProperty(Func getter, Action setter) => new RegisteredStatic( + instance => Guard(instance, () => ((Object)getter.Invoke()).ToJsValue(instance)), + setter == null ? null : (instance, value) => Guard(instance, () => + { + setter.Invoke(new JsDomArguments(instance, new[] { value }).Get(0)); + return JsValue.Undefined; + })); + + // a static accessor is rare enough for the closure this costs + private static JsValue Guard(EngineInstance instance, Func run) + { + using (var scope = RegisteredScope.Enter(instance, null, null)) + { + try + { + var result = run.Invoke(); + scope.Complete(); + return result; + } + catch (Exception error) when (RegisteredCall.IsHostError(error)) + { + throw RegisteredCall.ToScriptError(instance, error); + } + } + } + } +} From db2224aae5c8b66a1cb3adb0fce6c8720f9e54a1 Mon Sep 17 00:00:00 2001 From: Florian Rappl Date: Sun, 22 Nov 2026 20:28:39 +0100 Subject: [PATCH 02/19] Added shared workers --- CHANGELOG.md | 6 + src/AngleSharp.Js.Docs/package.json | 2 +- src/AngleSharp.Js.Tests/WorkerTests.cs | 33 ++++ src/AngleSharp.Js/Dom/SharedWorker.cs | 231 +++++++++++++++++++++++++ src/AngleSharp.Js/Dom/Worker.cs | 60 ++++--- src/AngleSharp.Js/JsModuleLoader.cs | 39 ++++- src/Directory.Build.props | 2 +- 7 files changed, 345 insertions(+), 28 deletions(-) create mode 100644 src/AngleSharp.Js/Dom/SharedWorker.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 6f0a2821..fdb43ac9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,9 @@ +# 1.3.0 + +Released on tbd. + +- Added `SharedWorker`, which the scripts of an origin creating it for the same address + # 1.2.3 Released on Sunday, November 22 2026. diff --git a/src/AngleSharp.Js.Docs/package.json b/src/AngleSharp.Js.Docs/package.json index 23c6a678..24eabe64 100644 --- a/src/AngleSharp.Js.Docs/package.json +++ b/src/AngleSharp.Js.Docs/package.json @@ -1,6 +1,6 @@ { "name": "@anglesharp/js", - "version": "1.2.3", + "version": "1.3.0", "preview": true, "description": "The doclet for the AngleSharp.Js documentation.", "keywords": [ diff --git a/src/AngleSharp.Js.Tests/WorkerTests.cs b/src/AngleSharp.Js.Tests/WorkerTests.cs index 858dda29..5000e90d 100644 --- a/src/AngleSharp.Js.Tests/WorkerTests.cs +++ b/src/AngleSharp.Js.Tests/WorkerTests.cs @@ -112,6 +112,39 @@ public async Task ScriptGetsAnErrorEventOfAWorkerAndCanPostToIt() Assert.IsTrue(await WaitFor(() => document.Title == "error:error"), document.Title); } + [Test] + public async Task SharedWorkerIsSharedByTheScriptsCreatingIt() + { + var document = await OpenWithSourcesAsync(("https://example.com/shared.js", + "var count = 0; onconnect = function (e) { var port = e.ports[0]; count++; port.onmessage = function (m) { port.postMessage(m.data + ':' + count); }; };")); + document.ExecuteScript(@" + window.log = []; + var a = new SharedWorker('shared.js'); + a.port.onmessage = function (e) { log.push('a=' + e.data); }; + a.port.postMessage('ping'); + var b = new SharedWorker('shared.js'); + b.port.onmessage = function (e) { log.push('b=' + e.data); }; + b.port.postMessage('pong');"); + + Assert.IsTrue(await WaitFor(() => document.ExecuteScript("log.length")?.ToString() == "2")); + var log = document.ExecuteScript("log.sort().join(',')")?.ToString(); + Assert.AreEqual("a=ping:2,b=pong:2", log); + } + + [Test] + public async Task SharedWorkerOfAnotherNameIsAnother() + { + var document = await OpenWithSourcesAsync(("https://example.com/shared.js", + "var count = 0; onconnect = function (e) { count++; e.ports[0].postMessage(count); };")); + document.ExecuteScript(@" + window.log = []; + new SharedWorker('shared.js', 'one').port.onmessage = function (e) { log.push(e.data); }; + new SharedWorker('shared.js', { name: 'two' }).port.onmessage = function (e) { log.push(e.data); };"); + + Assert.IsTrue(await WaitFor(() => document.ExecuteScript("log.length")?.ToString() == "2")); + Assert.AreEqual("1,1", document.ExecuteScript("log.join(',')")?.ToString()); + } + [Test] public async Task UnknownWorkerTypeIsRefused() { diff --git a/src/AngleSharp.Js/Dom/SharedWorker.cs b/src/AngleSharp.Js/Dom/SharedWorker.cs new file mode 100644 index 00000000..77348d85 --- /dev/null +++ b/src/AngleSharp.Js/Dom/SharedWorker.cs @@ -0,0 +1,231 @@ +namespace AngleSharp.Js.Dom +{ + using AngleSharp.Attributes; + using AngleSharp.Browser; + using AngleSharp.Dom; + using AngleSharp.Dom.Events; + using AngleSharp.Io; + using AngleSharp.Js; + using AngleSharp.Scripting; + using System; + using System.Collections.Generic; + + /// + /// Represents a shared worker as seen from a window: the windows creating one for the same + /// script (and name) of an origin share it, each talking to it through a port of its own, + /// which the worker gets by a connect event. + /// + [DomName("SharedWorker")] + [DomExposed("Window")] + public sealed class SharedWorker : EventTarget + { + #region Fields + + private static readonly Dictionary<(JsScriptingService, String, String, String), Scope> Scopes = new Dictionary<(JsScriptingService, String, String, String), Scope>(); + + private readonly MessagePort _port; + + #endregion + + #region ctor + + /// + /// Creates a new shared worker, which connects to the running one for the script, or + /// starts it in a separate context. + /// + /// The window creating the worker. + /// The address of the script. + public SharedWorker(IWindow window, String source) + : this(window, source, null) + { + } + + /// + /// Creates a new shared worker, which connects to the running one for the script, or + /// starts it in a separate context. + /// + /// The window creating the worker. + /// The address of the script. + /// The name of the worker, or its options. + [DomConstructor] + public SharedWorker(IWindow window, String source, Object options) + { + if (window?.Document == null) + { + throw new ArgumentNullException(nameof(window)); + } + + if (String.IsNullOrEmpty(source)) + { + throw new DomException(DomError.Syntax); + } + + var document = window.Document; + var scripting = document.Context.GetService() ?? throw new DomException(DomError.NotSupported); + var url = Worker.ResolveUrl(document, source); + var name = options is WorkerOptions workerOptions ? workerOptions.Name ?? String.Empty : options?.ToString() ?? String.Empty; + var key = (scripting, document.Origin ?? String.Empty, url.Href, name); + + // the port of the window, and the one of the worker, which gets its document once started + var gate = new Object(); + _port = new MessagePort(document, gate); + var inside = new MessagePort(null, gate); + _port.Entangle(inside); + + Scope scope; + + lock (Scopes) + { + if (!Scopes.TryGetValue(key, out scope) || scope.IsClosed) + { + scope = new Scope(key, document, scripting, url); + Scopes[key] = scope; + } + + scope.Attach(window, this); + } + + scope.Connect(inside); + } + + #endregion + + #region Properties + + /// + /// Gets the port to talk to the worker. + /// + [DomName("port")] + public MessagePort Port => _port; + + #endregion + + #region Events + + /// + /// Raised when the script of the worker could not be started. + /// + [DomName("onerror")] + public event DomEventHandler Failed + { + add { AddEventListener(EventNames.Error, value); } + remove { RemoveEventListener(EventNames.Error, value); } + } + + #endregion + + #region Helpers + + /// + /// The running script of a shared worker, with the windows connected to it. + /// + private sealed class Scope + { + private const String WorkerIncomingPortsName = "__anglesharpIncomingPorts"; + + private const String ConnectScript = @"(function () { +var ev = { type: 'connect', data: '', origin: '', lastEventId: '', source: __anglesharpIncomingPorts[0], ports: __anglesharpIncomingPorts }; +if (self && typeof self.onconnect === 'function') { + self.onconnect(ev); +} +})();"; + + private readonly (JsScriptingService, String, String, String) _key; + private readonly JsScriptingService _scripting; + private readonly IEventLoop _loop; + private readonly IBrowsingContext _context; + private readonly List _windows = new List(); + private IDocument _document; + private Exception _startupError; + + public Scope((JsScriptingService, String, String, String) key, IDocument creator, JsScriptingService scripting, Url url) + { + _key = key; + _scripting = scripting; + _loop = new JsEventLoop(); + _context = Worker.CreateContext(creator.Context, scripting, _loop); + + Worker.Enqueue(_loop, TaskPriority.Critical, () => + { + try + { + _document = _context.OpenAsync(request => request.Address(url).Content("")).GetAwaiter().GetResult(); + var source = Worker.FetchScript(creator, url); + _scripting.EvaluateScript(_document, Worker.WorkerBootstrap, MimeTypeNames.DefaultJavaScript, url.Href); + _scripting.EvaluateScript(_document, source, MimeTypeNames.DefaultJavaScript, url.Href); + } + catch (Exception ex) + { + _startupError = ex; + } + }); + } + + public Boolean IsClosed { get; private set; } + + public void Attach(IWindow window, SharedWorker worker) + { + if (!_windows.Contains(window)) + { + _windows.Add(window); + window.Unloaded += OnUnloaded; + } + + // the worker failing to start is told to every window connecting + Worker.Enqueue(_loop, TaskPriority.Normal, () => + { + if (_startupError is { } error) + { + var loop = window.Document?.Context.GetService(); + Worker.Enqueue(loop, TaskPriority.Normal, () => + { + var ev = new ErrorEvent(); + ev.Init(_key.Item3, 0, 0, error); + worker.Dispatch(ev); + }); + } + }); + } + + public void Connect(MessagePort port) + { + Worker.Enqueue(_loop, TaskPriority.Normal, () => + { + if (_document == null || IsClosed) + { + return; + } + + port.SetDocument(_document); + var instance = _scripting.GetOrCreateInstance(_document); + var ports = new[] { port }; + instance.Jint.SetValue(WorkerIncomingPortsName, ports.ToJsValue(instance)); + _document.DefaultView?.Dispatch(new MessageEvent("connect", false, false, String.Empty, String.Empty, String.Empty, null, ports)); + _scripting.EvaluateScript(_document, ConnectScript, MimeTypeNames.DefaultJavaScript, _document.Url); + }); + } + + private void OnUnloaded(Object sender, Event ev) + { + lock (Scopes) + { + if (sender is IWindow window) + { + window.Unloaded -= OnUnloaded; + _windows.Remove(window); + } + + // the worker ends with the last window it was created for + if (_windows.Count == 0 && !IsClosed) + { + IsClosed = true; + Scopes.Remove(_key); + ((IDisposable)_loop).Dispose(); + } + } + } + } + + #endregion + } +} diff --git a/src/AngleSharp.Js/Dom/Worker.cs b/src/AngleSharp.Js/Dom/Worker.cs index ef31dcdc..8000dfa8 100644 --- a/src/AngleSharp.Js/Dom/Worker.cs +++ b/src/AngleSharp.Js/Dom/Worker.cs @@ -89,21 +89,7 @@ public Worker(IWindow window, String source, WorkerOptions options) _workerLoop = new JsEventLoop(); try { - var workerConfig = Configuration.Default - .With(_scripting) - .WithOnly(_workerLoop) - .With(_ => parentContext.GetService()) - .With(_ => parentContext.GetService()); - - foreach (var service in parentContext.OriginalServices) - { - if (service is EngineCreator || service is Func) - { - workerConfig = workerConfig.With(service); - } - } - - _workerContext = BrowsingContext.New(workerConfig); + _workerContext = CreateContext(parentContext, _scripting, _workerLoop); Enqueue(_workerLoop, TaskPriority.Critical, () => { @@ -311,9 +297,37 @@ private void DeliverToWorker(SerializedMessage message) _scripting.EvaluateScript(_workerDocument, WorkerDispatchScript, MimeTypeNames.DefaultJavaScript, _workerDocument.Url); } - private String FetchWorkerScript(Url source) + private String FetchWorkerScript(Url source) => FetchScript(_window.Document, source); + + /// + /// Creates the context of a worker, running scripts on its own loop and loading + /// with the loaders of the context creating it. + /// + internal static IBrowsingContext CreateContext(IBrowsingContext parentContext, JsScriptingService scripting, IEventLoop loop) { - var loader = _window.Document.Context.GetService(); + var workerConfig = Configuration.Default + .With(scripting) + .WithOnly(loop) + .With(_ => parentContext.GetService()) + .With(_ => parentContext.GetService()); + + foreach (var service in parentContext.OriginalServices) + { + if (service is EngineCreator || service is Func) + { + workerConfig = workerConfig.With(service); + } + } + + return BrowsingContext.New(workerConfig); + } + + /// + /// Fetches the script of a worker for the given document. + /// + internal static String FetchScript(IDocument owner, Url source) + { + var loader = owner.Context.GetService(); if (loader == null) { @@ -322,7 +336,7 @@ private String FetchWorkerScript(Url source) var request = new DocumentRequest(source) { - Referer = _window.Document.DocumentUri, + Referer = owner.DocumentUri, }; using (var response = loader.FetchAsync(request).Task.GetAwaiter().GetResult()) @@ -349,7 +363,9 @@ private void EnsureLoaderAvailable() } } - private Url ResolveUrl(String source) + private Url ResolveUrl(String source) => ResolveUrl(_window.Document, source); + + internal static Url ResolveUrl(IDocument document, String source) { if (source.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || source.StartsWith("https://", StringComparison.OrdinalIgnoreCase) || @@ -358,7 +374,7 @@ private Url ResolveUrl(String source) return Url.Create(source); } - var documentUrl = _window.Document.Url; + var documentUrl = document.Url; if (String.IsNullOrEmpty(documentUrl) || documentUrl.Is("about:blank")) { @@ -368,7 +384,7 @@ private Url ResolveUrl(String source) return new Url(new Url(documentUrl), source); } - private static void Enqueue(IEventLoop loop, TaskPriority priority, Action action) + internal static void Enqueue(IEventLoop loop, TaskPriority priority, Action action) { if (loop != null) { @@ -380,7 +396,7 @@ private static void Enqueue(IEventLoop loop, TaskPriority priority, Action actio } } - private const String WorkerBootstrap = @"(function () { + internal const String WorkerBootstrap = @"(function () { if (typeof self === 'undefined') { this.self = this; } diff --git a/src/AngleSharp.Js/JsModuleLoader.cs b/src/AngleSharp.Js/JsModuleLoader.cs index f727ebb5..ab72f3b8 100644 --- a/src/AngleSharp.Js/JsModuleLoader.cs +++ b/src/AngleSharp.Js/JsModuleLoader.cs @@ -5,6 +5,7 @@ namespace AngleSharp.Js using AngleSharp.Text; using Jint; using Jint.Runtime.Modules; + using System.Collections.Generic; using System.IO; using System; using System.Linq; @@ -39,17 +40,17 @@ public override ResolvedSpecifier Resolve(string referencingModuleLocation, Modu { var scopeImports = _instance.ImportMap.Scopes[scopePath]; - if (scopeImports.TryGetValue(specifier, out var scopeModuleUrl)) + if (TryMap(scopeImports, specifier, out var scopeModuleUrl)) { - return Resolved(moduleRequest, new Url(GetDocumentBaseUrl(), scopeModuleUrl.OriginalString)); + return Resolved(moduleRequest, scopeModuleUrl); } } } } - if (_instance.ImportMap.Imports.TryGetValue(specifier, out var moduleUrl)) + if (TryMap(_instance.ImportMap.Imports, specifier, out var moduleUrl)) { - return Resolved(moduleRequest, new Url(GetDocumentBaseUrl(), moduleUrl.OriginalString)); + return Resolved(moduleRequest, moduleUrl); } if (specifier.StartsWith("/") || specifier.StartsWith("./") || specifier.StartsWith("../")) @@ -81,6 +82,36 @@ protected override Byte[] LoadModuleContentsAsBytes(Engine engine, ResolvedSpeci return FetchModuleBytes(GetModuleUrl(resolved)); } + // A key of the map is either the whole specifier, or, ending with a slash, a prefix of it, + // whose address the rest of the specifier is appended to (the longest prefix wins). + private Boolean TryMap(Dictionary imports, String specifier, out Url url) + { + if (imports.TryGetValue(specifier, out var address)) + { + url = new Url(GetDocumentBaseUrl(), address.OriginalString); + return true; + } + + var prefix = imports.Keys + .Where(key => key.EndsWith("/") && specifier.StartsWith(key, StringComparison.Ordinal)) + .OrderByDescending(key => key.Length) + .FirstOrDefault(); + + if (prefix != null) + { + var target = imports[prefix].OriginalString; + + if (target.EndsWith("/")) + { + url = new Url(new Url(GetDocumentBaseUrl(), target), specifier.Substring(prefix.Length)); + return true; + } + } + + url = null; + return false; + } + private static ResolvedSpecifier Resolved(ModuleRequest moduleRequest, Url url) { return new ResolvedSpecifier(moduleRequest, url.Href, null, SpecifierType.RelativeOrAbsolute); diff --git a/src/Directory.Build.props b/src/Directory.Build.props index 09b349d9..bd4ed1a9 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -10,7 +10,7 @@ entry of CHANGELOG.md, which build/Build.cs passes in as -p:Version, so this value only affects a plain `dotnet build` and no longer needs bumping for a release. --> - 1.2.3 + 1.3.0 From 5b9e80097700267f08e0cb301b6ec8480f56dfee Mon Sep 17 00:00:00 2001 From: FlorianRappl <1766191+FlorianRappl@users.noreply.github.com> Date: Sun, 22 Nov 2026 22:00:57 +0000 Subject: [PATCH 03/19] Initial plan From 8112a52dedb23b9f783057ad0d54c55934d8b6d8 Mon Sep 17 00:00:00 2001 From: FlorianRappl <1766191+FlorianRappl@users.noreply.github.com> Date: Sun, 22 Nov 2026 22:03:26 +0000 Subject: [PATCH 04/19] Fix shared worker key compatibility with net462 Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- src/AngleSharp.Js.Tests/WorkerTests.cs | 17 +++++++++++++++++ src/AngleSharp.Js/Dom/SharedWorker.cs | 8 ++++---- 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/src/AngleSharp.Js.Tests/WorkerTests.cs b/src/AngleSharp.Js.Tests/WorkerTests.cs index 5000e90d..2c9033f3 100644 --- a/src/AngleSharp.Js.Tests/WorkerTests.cs +++ b/src/AngleSharp.Js.Tests/WorkerTests.cs @@ -145,6 +145,23 @@ public async Task SharedWorkerOfAnotherNameIsAnother() Assert.AreEqual("1,1", document.ExecuteScript("log.join(',')")?.ToString()); } + [Test] + public async Task SharedWorkerKeyIncludesResolvedScriptUrl() + { + var source = "var count = 0; onconnect = function (e) { count++; e.ports[0].postMessage(count); };"; + var document = await OpenWithSourcesAsync( + ("https://example.com/shared.js", source), + ("https://example.com/other.js", source)).ConfigureAwait(false); + document.ExecuteScript(@" + window.log = []; + new SharedWorker('shared.js', 'same').port.onmessage = function (e) { log.push('a=' + e.data); }; + new SharedWorker('/shared.js', 'same').port.onmessage = function (e) { log.push('b=' + e.data); }; + new SharedWorker('other.js', 'same').port.onmessage = function (e) { log.push('c=' + e.data); };"); + + Assert.IsTrue(await WaitFor(() => document.ExecuteScript("log.length")?.ToString() == "3").ConfigureAwait(false)); + Assert.AreEqual("a=1,b=2,c=1", document.ExecuteScript("log.sort().join(',')")?.ToString()); + } + [Test] public async Task UnknownWorkerTypeIsRefused() { diff --git a/src/AngleSharp.Js/Dom/SharedWorker.cs b/src/AngleSharp.Js/Dom/SharedWorker.cs index 77348d85..2a545071 100644 --- a/src/AngleSharp.Js/Dom/SharedWorker.cs +++ b/src/AngleSharp.Js/Dom/SharedWorker.cs @@ -21,7 +21,7 @@ public sealed class SharedWorker : EventTarget { #region Fields - private static readonly Dictionary<(JsScriptingService, String, String, String), Scope> Scopes = new Dictionary<(JsScriptingService, String, String, String), Scope>(); + private static readonly Dictionary, Scope> Scopes = new Dictionary, Scope>(); private readonly MessagePort _port; @@ -64,7 +64,7 @@ public SharedWorker(IWindow window, String source, Object options) var scripting = document.Context.GetService() ?? throw new DomException(DomError.NotSupported); var url = Worker.ResolveUrl(document, source); var name = options is WorkerOptions workerOptions ? workerOptions.Name ?? String.Empty : options?.ToString() ?? String.Empty; - var key = (scripting, document.Origin ?? String.Empty, url.Href, name); + var key = Tuple.Create(scripting, document.Origin ?? String.Empty, url.Href, name); // the port of the window, and the one of the worker, which gets its document once started var gate = new Object(); @@ -130,7 +130,7 @@ private sealed class Scope } })();"; - private readonly (JsScriptingService, String, String, String) _key; + private readonly Tuple _key; private readonly JsScriptingService _scripting; private readonly IEventLoop _loop; private readonly IBrowsingContext _context; @@ -138,7 +138,7 @@ private sealed class Scope private IDocument _document; private Exception _startupError; - public Scope((JsScriptingService, String, String, String) key, IDocument creator, JsScriptingService scripting, Url url) + public Scope(Tuple key, IDocument creator, JsScriptingService scripting, Url url) { _key = key; _scripting = scripting; From 1cf7713ba9ae9078eefeca365b365ae701625ca2 Mon Sep 17 00:00:00 2001 From: Florian Rappl Date: Mon, 23 Nov 2026 00:54:25 +0100 Subject: [PATCH 05/19] Improved web crypto --- src/AngleSharp.Js.Tests/WebCryptoTests.cs | 331 ++++ src/AngleSharp.Js/Dom/Crypto.cs | 8 +- src/AngleSharp.Js/Dom/CryptoKey.cs | 67 + src/AngleSharp.Js/Dom/SubtleCrypto.cs | 176 +++ src/AngleSharp.Js/Dom/WebCrypto.cs | 1708 +++++++++++++++++++++ 5 files changed, 2289 insertions(+), 1 deletion(-) create mode 100644 src/AngleSharp.Js.Tests/WebCryptoTests.cs create mode 100644 src/AngleSharp.Js/Dom/CryptoKey.cs create mode 100644 src/AngleSharp.Js/Dom/SubtleCrypto.cs create mode 100644 src/AngleSharp.Js/Dom/WebCrypto.cs diff --git a/src/AngleSharp.Js.Tests/WebCryptoTests.cs b/src/AngleSharp.Js.Tests/WebCryptoTests.cs new file mode 100644 index 00000000..2da359a7 --- /dev/null +++ b/src/AngleSharp.Js.Tests/WebCryptoTests.cs @@ -0,0 +1,331 @@ +namespace AngleSharp.Js.Tests +{ + using NUnit.Framework; + using System; + using System.Threading.Tasks; + + /// + /// The operations of crypto.subtle (Web Cryptography API), checked with the test vectors of + /// the standards defining the algorithms where there are some. + /// + [TestFixture] + public class WebCryptoTests + { + private const String Prelude = @" + var subtle = crypto.subtle; + function hex(buffer) { return Array.from(new Uint8Array(buffer)).map(function (b) { return (b < 16 ? '0' : '') + b.toString(16); }).join(''); } + function bytes(text) { var r = new Uint8Array(text.length / 2); for (var i = 0; i < r.length; i++) { r[i] = parseInt(text.substr(2 * i, 2), 16); } return r; } + function utf8(text) { return new TextEncoder().encode(text); } + "; + + // Runs the body of an async function; the result (or the name of the error) ends up as the title. + private static async Task Run(String body) + { + var cfg = Configuration.Default.WithJs().WithEventLoop(); + var script = $"{Prelude} (async function () {{ {body} }})().then(function (r) {{ document.title = 'ok:' + r; }}, function (e) {{ document.title = 'error:' + (e && e.name) + ':' + (e && e.message); }});"; + var document = await BrowsingContext.New(cfg).OpenAsync(m => m.Content($"")); + + for (var i = 0; i < 500 && String.IsNullOrEmpty(document.Title); i++) + { + await Task.Delay(20); + } + + return document.Title; + } + + [Test] + public async Task SubtleIsAvailable() + { + var result = await Run("return [typeof crypto.subtle, crypto.subtle === crypto.subtle, crypto.subtle instanceof SubtleCrypto, typeof CryptoKey].join();"); + Assert.AreEqual("ok:object,true,true,function", result); + } + + [TestCase("SHA-1", "a9993e364706816aba3e25717850c26c9cd0d89d")] + [TestCase("SHA-256", "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad")] + [TestCase("sha-384", "cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed8086072ba1e7cc2358baeca134c825a7")] + [TestCase("SHA-512", "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f")] + public async Task DigestHashes(String name, String expected) + { + var result = await Run($"var d = await subtle.digest({{ name: '{name}' }}, utf8('abc')); return (d instanceof ArrayBuffer) + ',' + hex(d);"); + Assert.AreEqual("ok:true," + expected, result); + } + + [Test] + public async Task DigestTakesTheNameAlone() + { + var result = await Run("return hex(await subtle.digest('SHA-256', new Uint8Array(0).buffer));"); + Assert.AreEqual("ok:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", result); + } + + [Test] + public async Task UnknownAlgorithmRejectsWithNotSupportedError() + { + var result = await Run("return await subtle.digest('MD5', utf8('abc'));"); + Assert.That(result, Does.StartWith("error:NotSupportedError")); + } + + [Test] + public async Task HmacSignsAndVerifies() + { + // RFC 4231, test case 2 + var result = await Run(@" + var key = await subtle.importKey('raw', utf8('Jefe'), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign', 'verify']); + var data = utf8('what do ya want for nothing?'); + var signature = await subtle.sign('HMAC', key, data); + var valid = await subtle.verify('HMAC', key, signature, data); + var invalid = await subtle.verify('HMAC', key, signature, utf8('something else')); + return [hex(signature), valid, invalid, key instanceof CryptoKey, key.type, key.algorithm.name, key.algorithm.hash.name, key.algorithm.length, key.usages.join('+'), key.extractable].join();"); + + Assert.AreEqual("ok:5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843,true,false,true,secret,HMAC,SHA-256,32,sign+verify,false", result); + } + + [Test] + public async Task GeneratedHmacKeyHasTheBlockSize() + { + var result = await Run(@" + var key = await subtle.generateKey({ name: 'HMAC', hash: { name: 'SHA-512' } }, true, ['verify', 'sign']); + var raw = await subtle.exportKey('raw', key); + return [key.algorithm.length, raw.byteLength, key.usages.join('+')].join();"); + + Assert.AreEqual("ok:1024,128,sign+verify", result); + } + + [Test] + public async Task Pbkdf2DerivesBits() + { + // RFC 6070 (SHA-1) and the PBKDF2-HMAC-SHA256 vector of RFC 7914 + var result = await Run(@" + var key = await subtle.importKey('raw', utf8('password'), 'PBKDF2', false, ['deriveBits']); + var sha1 = await subtle.deriveBits({ name: 'PBKDF2', salt: utf8('salt'), iterations: 2, hash: 'SHA-1' }, key, 160); + var other = await subtle.importKey('raw', utf8('passwd'), 'PBKDF2', false, ['deriveBits']); + var sha256 = await subtle.deriveBits({ name: 'PBKDF2', salt: utf8('salt'), iterations: 1, hash: 'SHA-256' }, other, 256); + return hex(sha1) + ',' + hex(sha256);"); + + Assert.AreEqual("ok:ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957,55ac046e56e3089fec1691c22544b605f94185216dde0465e68b9d57c20dacbc", result); + } + + [Test] + public async Task HkdfDerivesBits() + { + // RFC 5869, test case 1 + var result = await Run(@" + var key = await subtle.importKey('raw', bytes('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b'), 'HKDF', false, ['deriveBits']); + var bits = await subtle.deriveBits({ name: 'HKDF', hash: 'SHA-256', salt: bytes('000102030405060708090a0b0c'), info: bytes('f0f1f2f3f4f5f6f7f8f9') }, key, 336); + return hex(bits);"); + + Assert.AreEqual("ok:3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865", result); + } + + [Test] + public async Task DeriveKeyGivesAUsableKey() + { + var result = await Run(@" + var base = await subtle.importKey('raw', utf8('secret'), 'PBKDF2', false, ['deriveKey']); + var key = await subtle.deriveKey({ name: 'PBKDF2', salt: utf8('salt'), iterations: 1000, hash: 'SHA-256' }, base, { name: 'AES-GCM', length: 256 }, true, ['encrypt', 'decrypt']); + var iv = new Uint8Array(12); + var encrypted = await subtle.encrypt({ name: 'AES-GCM', iv: iv }, key, utf8('hello')); + var decrypted = await subtle.decrypt({ name: 'AES-GCM', iv: iv }, key, encrypted); + return [key.algorithm.name, key.algorithm.length, new TextDecoder().decode(decrypted)].join();"); + + Assert.AreEqual("ok:AES-GCM,256,hello", result); + } + + [Test] + public async Task AesCbcEncrypts() + { + // NIST SP 800-38A, F.2.1 (the first block; PKCS#7 padding adds a second) + var result = await Run(@" + var key = await subtle.importKey('raw', bytes('2b7e151628aed2a6abf7158809cf4f3c'), 'AES-CBC', false, ['encrypt', 'decrypt']); + var iv = bytes('000102030405060708090a0b0c0d0e0f'); + var encrypted = await subtle.encrypt({ name: 'AES-CBC', iv: iv }, key, bytes('6bc1bee22e409f96e93d7e117393172a')); + var decrypted = await subtle.decrypt({ name: 'AES-CBC', iv: iv }, key, encrypted); + return [hex(encrypted).substr(0, 32), encrypted.byteLength, hex(decrypted)].join();"); + + Assert.AreEqual("ok:7649abac8119b246cee98e9b12e9197d,32,6bc1bee22e409f96e93d7e117393172a", result); + } + + [Test] + public async Task AesCtrEncrypts() + { + // NIST SP 800-38A, F.5.1 + var result = await Run(@" + var key = await subtle.importKey('raw', bytes('2b7e151628aed2a6abf7158809cf4f3c'), 'AES-CTR', false, ['encrypt', 'decrypt']); + var params = { name: 'AES-CTR', counter: bytes('f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff'), length: 64 }; + var encrypted = await subtle.encrypt(params, key, bytes('6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51')); + var decrypted = await subtle.decrypt(params, key, encrypted); + return [hex(encrypted), hex(decrypted)].join();"); + + Assert.AreEqual("ok:874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff,6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51", result); + } + + [Test] + public async Task AesGcmRejectsTamperedData() + { + var result = await Run(@" + var key = await subtle.generateKey({ name: 'AES-GCM', length: 128 }, false, ['encrypt', 'decrypt']); + var iv = crypto.getRandomValues(new Uint8Array(12)); + var encrypted = new Uint8Array(await subtle.encrypt({ name: 'AES-GCM', iv: iv, additionalData: utf8('header') }, key, utf8('hello'))); + var length = encrypted.length; + encrypted[0] ^= 1; + try { + await subtle.decrypt({ name: 'AES-GCM', iv: iv, additionalData: utf8('header') }, key, encrypted); + return 'decrypted'; + } catch (e) { + return length + ',' + e.name + ',' + (e instanceof DOMException); + }"); + + Assert.AreEqual("ok:21,OperationError,true", result); + } + + [Test] + public async Task AesKwWrapsKeys() + { + // RFC 3394, 4.1 + var result = await Run(@" + var kek = await subtle.importKey('raw', bytes('000102030405060708090a0b0c0d0e0f'), 'AES-KW', false, ['wrapKey', 'unwrapKey']); + var key = await subtle.importKey('raw', bytes('00112233445566778899aabbccddeeff'), 'AES-CBC', true, ['encrypt']); + var wrapped = await subtle.wrapKey('raw', key, kek, 'AES-KW'); + var unwrapped = await subtle.unwrapKey('raw', wrapped, kek, 'AES-KW', 'AES-CBC', true, ['encrypt']); + return [hex(wrapped), hex(await subtle.exportKey('raw', unwrapped))].join();"); + + Assert.AreEqual("ok:1fa68b0a8112b447aef34bd8fb5a7b829d3e862371d2cfe5,00112233445566778899aabbccddeeff", result); + } + + [Test] + public async Task JwkKeysCanBeWrapped() + { + var result = await Run(@" + var wrapping = await subtle.generateKey({ name: 'AES-GCM', length: 256 }, false, ['wrapKey', 'unwrapKey']); + var key = await subtle.generateKey({ name: 'HMAC', hash: 'SHA-256' }, true, ['sign']); + var iv = new Uint8Array(12); + var wrapped = await subtle.wrapKey('jwk', key, wrapping, { name: 'AES-GCM', iv: iv }); + var unwrapped = await subtle.unwrapKey('jwk', wrapped, wrapping, { name: 'AES-GCM', iv: iv }, { name: 'HMAC', hash: 'SHA-256' }, true, ['sign']); + var a = await subtle.exportKey('jwk', key); + var b = await subtle.exportKey('jwk', unwrapped); + return [a.k === b.k, b.kty, b.alg, b.ext, b.key_ops.join('+')].join();"); + + Assert.AreEqual("ok:true,oct,HS256,true,sign", result); + } + + [TestCase("P-256", 64)] + [TestCase("P-384", 96)] + [TestCase("P-521", 132)] + public async Task EcdsaSignsAndVerifies(String curve, Int32 signatureLength) + { + var result = await Run($@" + var pair = await subtle.generateKey({{ name: 'ECDSA', namedCurve: '{curve}' }}, true, ['sign', 'verify']); + var params = {{ name: 'ECDSA', hash: 'SHA-256' }}; + var signature = await subtle.sign(params, pair.privateKey, utf8('message')); + var valid = await subtle.verify(params, pair.publicKey, signature, utf8('message')); + var invalid = await subtle.verify(params, pair.publicKey, signature, utf8('other')); + return [signature.byteLength, valid, invalid, pair.publicKey.type, pair.privateKey.type, pair.publicKey.usages.join('+'), pair.privateKey.usages.join('+'), pair.publicKey.algorithm.namedCurve].join();"); + + Assert.AreEqual($"ok:{signatureLength},true,false,public,private,verify,sign,{curve}", result); + } + + [Test] + public async Task EcKeysAreExportedAndImported() + { + var result = await Run(@" + var pair = await subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, true, ['sign', 'verify']); + var jwk = await subtle.exportKey('jwk', pair.privateKey); + var raw = await subtle.exportKey('raw', pair.publicKey); + var spki = await subtle.exportKey('spki', pair.publicKey); + var pkcs8 = await subtle.exportKey('pkcs8', pair.privateKey); + var privateKey = await subtle.importKey('jwk', jwk, { name: 'ECDSA', namedCurve: 'P-256' }, false, ['sign']); + var fromPkcs8 = await subtle.importKey('pkcs8', pkcs8, { name: 'ECDSA', namedCurve: 'P-256' }, false, ['sign']); + var fromRaw = await subtle.importKey('raw', raw, { name: 'ECDSA', namedCurve: 'P-256' }, true, ['verify']); + var fromSpki = await subtle.importKey('spki', spki, { name: 'ECDSA', namedCurve: 'P-256' }, true, ['verify']); + var params = { name: 'ECDSA', hash: 'SHA-384' }; + var signature = await subtle.sign(params, privateKey, utf8('m')); + var other = await subtle.sign(params, fromPkcs8, utf8('m')); + return [jwk.kty, jwk.crv, jwk.d.length, raw.byteLength, new Uint8Array(raw)[0], + await subtle.verify(params, fromRaw, signature, utf8('m')), + await subtle.verify(params, fromSpki, other, utf8('m')), + hex(await subtle.exportKey('raw', fromSpki)) === hex(raw)].join();"); + + Assert.AreEqual("ok:EC,P-256,43,65,4,true,true,true", result); + } + + [Test] + public async Task EcdhAgreesOnTheSameSecret() + { + var result = await Run(@" + var alice = await subtle.generateKey({ name: 'ECDH', namedCurve: 'P-384' }, false, ['deriveBits', 'deriveKey']); + var bob = await subtle.generateKey({ name: 'ECDH', namedCurve: 'P-384' }, false, ['deriveBits']); + var a = await subtle.deriveBits({ name: 'ECDH', public: bob.publicKey }, alice.privateKey, 384); + var b = await subtle.deriveBits({ name: 'ECDH', public: alice.publicKey }, bob.privateKey, 384); + var key = await subtle.deriveKey({ name: 'ECDH', public: bob.publicKey }, alice.privateKey, { name: 'AES-GCM', length: 256 }, true, ['encrypt']); + var raw = await subtle.exportKey('raw', key); + return [a.byteLength, hex(a) === hex(b), hex(raw) === hex(a).substr(0, 64), alice.publicKey.usages.length].join();"); + + Assert.AreEqual("ok:48,true,true,0", result); + } + + [TestCase("RSASSA-PKCS1-v1_5", "{ name: 'RSASSA-PKCS1-v1_5' }", "RS256")] + [TestCase("RSA-PSS", "{ name: 'RSA-PSS', saltLength: 32 }", "PS256")] + public async Task RsaSignsAndVerifies(String name, String parameters, String alg) + { + var result = await Run($@" + var pair = await subtle.generateKey({{ name: '{name}', modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: 'SHA-256' }}, true, ['sign', 'verify']); + var signature = await subtle.sign({parameters}, pair.privateKey, utf8('message')); + var jwk = await subtle.exportKey('jwk', pair.publicKey); + var spki = await subtle.exportKey('spki', pair.publicKey); + var fromJwk = await subtle.importKey('jwk', jwk, {{ name: '{name}', hash: 'SHA-256' }}, false, ['verify']); + var fromSpki = await subtle.importKey('spki', spki, {{ name: '{name}', hash: 'SHA-256' }}, false, ['verify']); + return [signature.byteLength, + await subtle.verify({parameters}, fromJwk, signature, utf8('message')), + await subtle.verify({parameters}, fromSpki, signature, utf8('other')), + jwk.alg, jwk.e, pair.publicKey.algorithm.modulusLength, Array.from(pair.publicKey.algorithm.publicExponent).join('.')].join();"); + + Assert.AreEqual($"ok:256,true,false,{alg},AQAB,2048,1.0.1", result); + } + + [Test] + public async Task RsaOaepEncrypts() + { + var result = await Run(@" + var pair = await subtle.generateKey({ name: 'RSA-OAEP', modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: 'SHA-256' }, true, ['encrypt', 'decrypt']); + var encrypted = await subtle.encrypt({ name: 'RSA-OAEP' }, pair.publicKey, utf8('secret')); + var pkcs8 = await subtle.exportKey('pkcs8', pair.privateKey); + var privateKey = await subtle.importKey('pkcs8', pkcs8, { name: 'RSA-OAEP', hash: 'SHA-256' }, false, ['decrypt']); + var decrypted = await subtle.decrypt({ name: 'RSA-OAEP' }, privateKey, encrypted); + var jwk = await subtle.exportKey('jwk', pair.privateKey); + return [encrypted.byteLength, new TextDecoder().decode(decrypted), jwk.alg, typeof jwk.qi].join();"); + + Assert.AreEqual("ok:256,secret,RSA-OAEP-256,string", result); + } + + [TestCase("await subtle.exportKey('raw', await subtle.generateKey({ name: 'AES-CBC', length: 128 }, false, ['encrypt']))", "InvalidAccessError")] + [TestCase("var k = await subtle.generateKey({ name: 'AES-CBC', length: 128 }, false, ['encrypt']); await subtle.decrypt({ name: 'AES-CBC', iv: new Uint8Array(16) }, k, new Uint8Array(16))", "InvalidAccessError")] + [TestCase("var k = await subtle.generateKey({ name: 'AES-CBC', length: 128 }, false, ['encrypt']); await subtle.encrypt({ name: 'AES-CTR', counter: new Uint8Array(16), length: 64 }, k, new Uint8Array(16))", "InvalidAccessError")] + [TestCase("await subtle.generateKey({ name: 'AES-GCM', length: 128 }, false, [])", "SyntaxError")] + [TestCase("await subtle.generateKey({ name: 'AES-GCM', length: 128 }, false, ['sign'])", "SyntaxError")] + [TestCase("await subtle.generateKey({ name: 'AES-GCM', length: 100 }, false, ['encrypt'])", "OperationError")] + [TestCase("await subtle.importKey('raw', new Uint8Array(15), 'AES-GCM', false, ['encrypt'])", "DataError")] + [TestCase("await subtle.importKey('raw', utf8('x'), 'PBKDF2', true, ['deriveBits'])", "SyntaxError")] + [TestCase("await subtle.importKey('jwk', { kty: 'oct', k: 'AAAAAAAAAAAAAAAAAAAAAA', alg: 'A256GCM' }, 'AES-GCM', false, ['encrypt'])", "DataError")] + [TestCase("await subtle.importKey('jwk', { kty: 'oct', k: 'AAAAAAAAAAAAAAAAAAAAAA', ext: false }, 'AES-GCM', true, ['encrypt'])", "DataError")] + [TestCase("await subtle.importKey('pem', new Uint8Array(16), 'AES-GCM', false, ['encrypt'])", "TypeError")] + [TestCase("await subtle.generateKey({ name: 'AES-GCM', length: 128 }, false, ['launch'])", "TypeError")] + [TestCase("await subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-192' }, false, ['sign'])", "NotSupportedError")] + [TestCase("await subtle.generateKey({ name: 'HMAC' }, false, ['sign'])", "TypeError")] + [TestCase("await subtle.sign('SHA-256', null, new Uint8Array(1))", "NotSupportedError")] + public async Task FailuresRejectWithTheErrorOfTheStandard(String body, String expected) + { + var result = await Run(body + "; return 'done';"); + Assert.That(result, Does.StartWith("error:" + expected + ":")); + } + + [Test] + public async Task FailuresRejectRatherThanThrow() + { + var result = await Run(@" + var p = subtle.digest('MD5', new Uint8Array(1)); + var isPromise = p instanceof Promise; + try { await p; } catch (e) { return isPromise + ',' + e.name; }"); + + Assert.AreEqual("ok:true,NotSupportedError", result); + } + } +} diff --git a/src/AngleSharp.Js/Dom/Crypto.cs b/src/AngleSharp.Js/Dom/Crypto.cs index e71bdffc..c273cc04 100644 --- a/src/AngleSharp.Js/Dom/Crypto.cs +++ b/src/AngleSharp.Js/Dom/Crypto.cs @@ -9,7 +9,7 @@ namespace AngleSharp.Js.Dom using System.Security.Cryptography; /// - /// Represents the Crypto interface: random numbers, without the operations of crypto.subtle. + /// Represents the Crypto interface: random numbers and the operations of crypto.subtle. /// [DomName("Crypto")] public sealed class Crypto @@ -20,6 +20,12 @@ internal Crypto() { } + /// + /// Gets the operations of the Web Cryptography API. + /// + [DomName("subtle")] + public SubtleCrypto Subtle { get; } = new SubtleCrypto(); + /// /// Fills the given array of integers with random numbers. /// diff --git a/src/AngleSharp.Js/Dom/CryptoKey.cs b/src/AngleSharp.Js/Dom/CryptoKey.cs new file mode 100644 index 00000000..2ee25742 --- /dev/null +++ b/src/AngleSharp.Js/Dom/CryptoKey.cs @@ -0,0 +1,67 @@ +namespace AngleSharp.Js.Dom +{ + using AngleSharp.Attributes; + using System; + using System.Collections.Generic; + using System.Security.Cryptography; + + /// + /// Represents a key of the Web Cryptography API, which scripts get from crypto.subtle + /// without being able to see its material unless they export an extractable one. + /// + [DomName("CryptoKey")] + [DomExposed("Window")] + [DomExposed("Worker")] + public sealed class CryptoKey + { + private readonly IDictionary _algorithm; + private readonly String[] _usages; + + internal CryptoKey(String type, Boolean extractable, IDictionary algorithm, String[] usages) + { + Type = type; + Extractable = extractable; + _algorithm = algorithm; + _usages = usages; + } + + /// + /// Gets the type of the key: "secret", "public" or "private". + /// + [DomName("type")] + public String Type { get; } + + /// + /// Gets if the key may be exported. + /// + [DomName("extractable")] + public Boolean Extractable { get; } + + /// + /// Gets the algorithm the key is for and its parameters (e.g. the name, the length and + /// the hash), which is a plain object for scripts. + /// + [DomName("algorithm")] + public IDictionary Algorithm => new Dictionary(_algorithm); + + /// + /// Gets what the key may be used for, e.g. "encrypt" or "sign". + /// + [DomName("usages")] + public String[] Usages => (String[])_usages.Clone(); + + internal String AlgorithmName => (String)_algorithm["name"]; + + internal String Hash { get; set; } + + internal String Curve { get; set; } + + internal Byte[] Secret { get; set; } + + internal RSAParameters? Rsa { get; set; } + + internal ECParameters? Ec { get; set; } + + internal Boolean Allows(String usage) => Array.IndexOf(_usages, usage) >= 0; + } +} diff --git a/src/AngleSharp.Js/Dom/SubtleCrypto.cs b/src/AngleSharp.Js/Dom/SubtleCrypto.cs new file mode 100644 index 00000000..7f4f7d56 --- /dev/null +++ b/src/AngleSharp.Js/Dom/SubtleCrypto.cs @@ -0,0 +1,176 @@ +namespace AngleSharp.Js.Dom +{ + using AngleSharp.Attributes; + using System; + using System.Threading.Tasks; + + /// + /// Represents the SubtleCrypto interface of the Web Cryptography API (crypto.subtle): hashes + /// (SHA-1, SHA-256, SHA-384, SHA-512), HMAC, AES (CBC, CTR, GCM, KW), PBKDF2, HKDF, ECDSA, + /// ECDH (P-256, P-384, P-521), RSASSA-PKCS1-v1_5, RSA-PSS and RSA-OAEP. Every operation + /// gives a promise, which is rejected (rather than throwing) if the operation fails. + /// + [DomName("SubtleCrypto")] + [DomExposed("Window")] + [DomExposed("Worker")] + public sealed class SubtleCrypto + { + internal SubtleCrypto() + { + } + + /// + /// Encrypts the data. + /// + /// The name of the algorithm or an object with its parameters. + /// The key to encrypt with. + /// The data to encrypt. + /// The encrypted data, an ArrayBuffer for scripts. + [DomName("encrypt")] + public Task Encrypt(Object algorithm, CryptoKey key, Byte[] data) => + Run(() => WebCrypto.Encrypt(algorithm, key, data)); + + /// + /// Decrypts the data. + /// + /// The name of the algorithm or an object with its parameters. + /// The key to decrypt with. + /// The data to decrypt. + /// The decrypted data, an ArrayBuffer for scripts. + [DomName("decrypt")] + public Task Decrypt(Object algorithm, CryptoKey key, Byte[] data) => + Run(() => WebCrypto.Decrypt(algorithm, key, data)); + + /// + /// Signs the data. + /// + /// The name of the algorithm or an object with its parameters. + /// The key to sign with. + /// The data to sign. + /// The signature, an ArrayBuffer for scripts. + [DomName("sign")] + public Task Sign(Object algorithm, CryptoKey key, Byte[] data) => + Run(() => WebCrypto.Sign(algorithm, key, data)); + + /// + /// Verifies the signature of the data. + /// + /// The name of the algorithm or an object with its parameters. + /// The key to verify with. + /// The signature. + /// The data that was signed. + /// True if the signature is valid. + [DomName("verify")] + public Task Verify(Object algorithm, CryptoKey key, Byte[] signature, Byte[] data) => + Run(() => WebCrypto.Verify(algorithm, key, signature, data)); + + /// + /// Computes the digest (hash) of the data. + /// + /// The name of the hash, e.g. "SHA-256". + /// The data to hash. + /// The digest, an ArrayBuffer for scripts. + [DomName("digest")] + public Task Digest(Object algorithm, Byte[] data) => + Run(() => WebCrypto.Digest(algorithm, data)); + + /// + /// Generates a key, or a key pair ({ publicKey, privateKey }) for the asymmetric algorithms. + /// + /// The algorithm and its parameters. + /// If the (private) key may be exported. + /// What the key may be used for. + /// The key or the key pair. + [DomName("generateKey")] + public Task GenerateKey(Object algorithm, Boolean extractable, String[] keyUsages) => + Run(() => WebCrypto.GenerateKey(algorithm, extractable, keyUsages)); + + /// + /// Derives a key from a base key. + /// + /// The algorithm of the derivation and its parameters. + /// The key to derive from. + /// The algorithm of the derived key and its parameters. + /// If the derived key may be exported. + /// What the derived key may be used for. + /// The derived key. + [DomName("deriveKey")] + public Task DeriveKey(Object algorithm, CryptoKey baseKey, Object derivedKeyType, Boolean extractable, String[] keyUsages) => + Run(() => WebCrypto.DeriveKey(algorithm, baseKey, derivedKeyType, extractable, keyUsages)); + + /// + /// Derives bits from a base key. + /// + /// The algorithm of the derivation and its parameters. + /// The key to derive from. + /// The number of bits to derive, null for all (ECDH only). + /// The derived bits, an ArrayBuffer for scripts. + [DomName("deriveBits")] + public Task DeriveBits(Object algorithm, CryptoKey baseKey, Int32? length = null) => + Run(() => WebCrypto.DeriveBits(algorithm, baseKey, length)); + + /// + /// Imports a key. + /// + /// The format of the data: "raw", "spki", "pkcs8" or "jwk". + /// The key, bytes or a JSON Web Key object. + /// The algorithm the key is for and its parameters. + /// If the key may be exported. + /// What the key may be used for. + /// The imported key. + [DomName("importKey")] + public Task ImportKey(String format, Object keyData, Object algorithm, Boolean extractable, String[] keyUsages) => + Run(() => WebCrypto.ImportKey(format, keyData, algorithm, extractable, keyUsages)); + + /// + /// Exports an extractable key. + /// + /// The format: "raw", "spki", "pkcs8" or "jwk". + /// The key to export. + /// An ArrayBuffer, or a JSON Web Key object for "jwk". + [DomName("exportKey")] + public Task ExportKey(String format, CryptoKey key) => + Run(() => WebCrypto.ExportKey(format, key)); + + /// + /// Exports a key and encrypts it with another one. + /// + /// The format to export the key in. + /// The key to wrap. + /// The key to encrypt with. + /// The algorithm to encrypt with and its parameters. + /// The wrapped key, an ArrayBuffer for scripts. + [DomName("wrapKey")] + public Task WrapKey(String format, CryptoKey key, CryptoKey wrappingKey, Object wrapAlgorithm) => + Run(() => WebCrypto.WrapKey(format, key, wrappingKey, wrapAlgorithm)); + + /// + /// Decrypts a wrapped key and imports it. + /// + /// The format the key was exported in. + /// The wrapped key. + /// The key to decrypt with. + /// The algorithm to decrypt with and its parameters. + /// The algorithm the unwrapped key is for. + /// If the unwrapped key may be exported. + /// What the unwrapped key may be used for. + /// The unwrapped key. + [DomName("unwrapKey")] + public Task UnwrapKey(String format, Byte[] wrappedKey, CryptoKey unwrappingKey, Object unwrapAlgorithm, Object unwrappedKeyAlgorithm, Boolean extractable, String[] keyUsages) => + Run(() => WebCrypto.UnwrapKey(format, wrappedKey, unwrappingKey, unwrapAlgorithm, unwrappedKeyAlgorithm, extractable, keyUsages)); + + // The work is done right away (it is quick enough), but a failure has to reject the + // promise rather than being thrown, as the standard asks for. + private static Task Run(Func operation) + { + try + { + return Task.FromResult(operation()); + } + catch (Exception ex) + { + return Task.FromException(ex); + } + } + } +} diff --git a/src/AngleSharp.Js/Dom/WebCrypto.cs b/src/AngleSharp.Js/Dom/WebCrypto.cs new file mode 100644 index 00000000..40cbf0e4 --- /dev/null +++ b/src/AngleSharp.Js/Dom/WebCrypto.cs @@ -0,0 +1,1708 @@ +namespace AngleSharp.Js.Dom +{ + using AngleSharp.Dom; + using Jint; + using Jint.Native; + using Jint.Native.Json; + using Jint.Native.Object; + using Jint.Runtime; + using System; + using System.Collections.Generic; + using System.Linq; + using System.Security.Cryptography; + using System.Text; + + /// + /// The operations of crypto.subtle (Web Cryptography API, W3C), done with the cryptography + /// of .NET. AES-GCM, the formats spki and pkcs8, and ECDH need .NET 8 or later. + /// + static class WebCrypto + { + private const String Encrypt_ = "encrypt"; + private const String Decrypt_ = "decrypt"; + private const String Sign_ = "sign"; + private const String Verify_ = "verify"; + private const String DeriveKey_ = "deriveKey"; + private const String DeriveBits_ = "deriveBits"; + private const String WrapKey_ = "wrapKey"; + private const String UnwrapKey_ = "unwrapKey"; + private const String Digest_ = "digest"; + private const String GenerateKey_ = "generateKey"; + private const String ImportKey_ = "importKey"; + private const String GetKeyLength_ = "get key length"; + + // The order of the KeyUsage enumeration, which is the order of a key's usages. + private static readonly String[] AllUsages = { Encrypt_, Decrypt_, Sign_, Verify_, DeriveKey_, DeriveBits_, WrapKey_, UnwrapKey_ }; + + private static readonly Dictionary Operations = new Dictionary + { + ["SHA-1"] = new[] { Digest_ }, + ["SHA-256"] = new[] { Digest_ }, + ["SHA-384"] = new[] { Digest_ }, + ["SHA-512"] = new[] { Digest_ }, + ["HMAC"] = new[] { Sign_, Verify_, GenerateKey_, ImportKey_, GetKeyLength_ }, + ["AES-CBC"] = new[] { Encrypt_, Decrypt_, GenerateKey_, ImportKey_, GetKeyLength_ }, + ["AES-CTR"] = new[] { Encrypt_, Decrypt_, GenerateKey_, ImportKey_, GetKeyLength_ }, + ["AES-GCM"] = new[] { Encrypt_, Decrypt_, GenerateKey_, ImportKey_, GetKeyLength_ }, + ["AES-KW"] = new[] { WrapKey_, UnwrapKey_, GenerateKey_, ImportKey_, GetKeyLength_ }, + ["PBKDF2"] = new[] { DeriveBits_, ImportKey_, GetKeyLength_ }, + ["HKDF"] = new[] { DeriveBits_, ImportKey_, GetKeyLength_ }, + ["ECDSA"] = new[] { Sign_, Verify_, GenerateKey_, ImportKey_ }, + ["ECDH"] = new[] { DeriveBits_, GenerateKey_, ImportKey_ }, + ["RSASSA-PKCS1-v1_5"] = new[] { Sign_, Verify_, GenerateKey_, ImportKey_ }, + ["RSA-PSS"] = new[] { Sign_, Verify_, GenerateKey_, ImportKey_ }, + ["RSA-OAEP"] = new[] { Encrypt_, Decrypt_, GenerateKey_, ImportKey_ }, + }; + + #region Operations + + public static Byte[] Digest(Object algorithm, Byte[] data) + { + var normalized = Normalize(algorithm, Digest_); + return Hash(normalized.Name, Required(data)); + } + + public static Byte[] Encrypt(Object algorithm, CryptoKey key, Byte[] data) + { + var normalized = Normalize(algorithm, Encrypt_); + CheckKey(key, normalized, Encrypt_); + return EncryptCore(normalized, key, Required(data)); + } + + public static Byte[] Decrypt(Object algorithm, CryptoKey key, Byte[] data) + { + var normalized = Normalize(algorithm, Decrypt_); + CheckKey(key, normalized, Decrypt_); + return DecryptCore(normalized, key, Required(data)); + } + + public static Byte[] Sign(Object algorithm, CryptoKey key, Byte[] data) + { + var normalized = Normalize(algorithm, Sign_); + CheckKey(key, normalized, Sign_); + data = Required(data); + + switch (normalized.Name) + { + case "HMAC": + return Hmac(key.Hash, key.Secret, data); + case "ECDSA": + using (var ecdsa = ECDsa.Create(key.Ec.Value)) + { + return ecdsa.SignData(data, HashName(normalized.GetHash())); + } + default: + using (var rsa = CreateRsa(key)) + { + return rsa.SignData(data, HashName(key.Hash), GetRsaPadding(normalized, key)); + } + } + } + + public static Boolean Verify(Object algorithm, CryptoKey key, Byte[] signature, Byte[] data) + { + var normalized = Normalize(algorithm, Verify_); + CheckKey(key, normalized, Verify_); + signature = Required(signature); + data = Required(data); + + switch (normalized.Name) + { + case "HMAC": + return AreEqual(Hmac(key.Hash, key.Secret, data), signature); + case "ECDSA": + using (var ecdsa = ECDsa.Create(key.Ec.Value)) + { + // the signature is r and s, each as long as a coordinate (IEEE P1363) + return signature.Length == 2 * CoordinateLength(key.Curve) && + ecdsa.VerifyData(data, signature, HashName(normalized.GetHash())); + } + default: + using (var rsa = CreateRsa(key)) + { + try + { + return rsa.VerifyData(data, signature, HashName(key.Hash), GetRsaPadding(normalized, key)); + } + catch (CryptographicException) + { + return false; + } + } + } + } + + public static Object GenerateKey(Object algorithm, Boolean extractable, String[] usages) + { + var normalized = Normalize(algorithm, GenerateKey_); + usages = CheckUsageValues(usages); + + switch (normalized.Name) + { + case "HMAC": + { + CheckUsages(usages, Sign_, Verify_); + var hash = normalized.GetHash(); + var length = normalized.GetInteger("length") ?? BlockBits(hash); + + if (length == 0) + { + throw OperationError(); + } + + return RequireUsages(CreateHmacKey(hash, RandomBytes((length + 7) / 8), length, extractable, usages)); + } + case "AES-CBC": + case "AES-CTR": + case "AES-GCM": + case "AES-KW": + { + CheckUsages(usages, GetAesUsages(normalized.Name)); + var length = normalized.GetInteger("length") ?? throw TypeError("The length of the key is missing."); + + if (length != 128 && length != 192 && length != 256) + { + throw OperationError(); + } + + return RequireUsages(CreateAesKey(normalized.Name, RandomBytes(length / 8), extractable, usages)); + } + case "ECDSA": + case "ECDH": + { + var isEcdsa = normalized.Name == "ECDSA"; + CheckUsages(usages, isEcdsa ? new[] { Sign_, Verify_ } : new[] { DeriveKey_, DeriveBits_ }); + var curve = GetCurve(normalized); + ECParameters parameters; + + using (var ecdsa = ECDsa.Create(GetNamedCurve(curve))) + { + parameters = ecdsa.ExportParameters(true); + } + + var publicKey = CreateEcKey(normalized.Name, curve, PublicPart(parameters), true, Intersect(usages, isEcdsa ? new[] { Verify_ } : new String[0])); + var privateKey = CreateEcKey(normalized.Name, curve, parameters, extractable, Intersect(usages, isEcdsa ? new[] { Sign_ } : new[] { DeriveKey_, DeriveBits_ })); + return CreateKeyPair(publicKey, RequireUsages(privateKey)); + } + default: + { + var (publicUsages, privateUsages) = GetRsaUsages(normalized.Name); + CheckUsages(usages, publicUsages.Concat(privateUsages).ToArray()); + var bits = normalized.GetInteger("modulusLength") ?? throw TypeError("The modulusLength is missing."); + var exponent = normalized.GetBytes("publicExponent"); + var hash = normalized.GetHash(); + + // the platform only generates keys with the usual exponent 65537 + if (!AreEqual(TrimZeros(exponent), new Byte[] { 1, 0, 1 })) + { + throw OperationError(); + } + + RSAParameters parameters; + + try + { + using (var rsa = RSA.Create()) + { + rsa.KeySize = bits; + parameters = rsa.ExportParameters(true); + } + } + catch (CryptographicException) + { + throw OperationError(); + } + + var publicKey = CreateRsaKey(normalized.Name, hash, PublicPart(parameters), true, Intersect(usages, publicUsages)); + var privateKey = CreateRsaKey(normalized.Name, hash, parameters, extractable, Intersect(usages, privateUsages)); + return CreateKeyPair(publicKey, RequireUsages(privateKey)); + } + } + } + + public static CryptoKey ImportKey(String format, Object keyData, Object algorithm, Boolean extractable, String[] usages) + { + CheckFormat(format); + var normalized = Normalize(algorithm, ImportKey_); + usages = CheckUsageValues(usages); + Byte[] data = null; + Jwk jwk = null; + + if (format == "jwk") + { + jwk = keyData is ObjectInstance obj && !obj.IsBufferSource() + ? new Jwk(obj) + : throw TypeError("A JSON Web Key has to be an object."); + jwk.Check(extractable, usages); + } + else + { + data = keyData as Byte[] ?? throw TypeError("The key data has to be an ArrayBuffer or a view on one."); + } + + switch (normalized.Name) + { + case "HMAC": + return RequireUsages(ImportHmacKey(format, data, jwk, normalized, extractable, usages)); + case "AES-CBC": + case "AES-CTR": + case "AES-GCM": + case "AES-KW": + return RequireUsages(ImportAesKey(format, data, jwk, normalized.Name, extractable, usages)); + case "PBKDF2": + case "HKDF": + CheckUsages(usages, DeriveKey_, DeriveBits_); + + if (format != "raw") + { + throw NotSupportedError(); + } + else if (extractable) + { + throw SyntaxError(); + } + + return RequireUsages(new CryptoKey("secret", false, CreateAlgorithm(normalized.Name), usages) { Secret = data }); + case "ECDSA": + case "ECDH": + return RequireUsages(ImportEcKey(format, data, jwk, normalized, extractable, usages)); + default: + return RequireUsages(ImportRsaKey(format, data, jwk, normalized, extractable, usages)); + } + } + + public static Object ExportKey(String format, CryptoKey key) + { + CheckFormat(format); + + if (key is null) + { + throw TypeError("The key is missing."); + } + else if (!key.Extractable) + { + throw InvalidAccessError(); + } + + switch (format) + { + case "raw": + if (key.Secret != null) + { + return (Byte[])key.Secret.Clone(); + } + else if (key.Ec is ECParameters ec && key.Type == "public") + { + return EncodePoint(ec, key.Curve); + } + + throw InvalidAccessError(); + case "jwk": + return ExportJwk(key); + default: + return ExportDer(format, key); + } + } + + public static Byte[] DeriveBits(Object algorithm, CryptoKey baseKey, Int32? length) + { + var normalized = Normalize(algorithm, DeriveBits_); + CheckKey(baseKey, normalized, DeriveBits_); + return DeriveBitsCore(normalized, baseKey, length); + } + + public static CryptoKey DeriveKey(Object algorithm, CryptoKey baseKey, Object derivedKeyType, Boolean extractable, String[] usages) + { + var normalized = Normalize(algorithm, DeriveBits_); + Normalize(derivedKeyType, ImportKey_); + var length = GetKeyLength(Normalize(derivedKeyType, GetKeyLength_)); + CheckKey(baseKey, normalized, DeriveKey_); + var bits = DeriveBitsCore(normalized, baseKey, length); + return ImportKey("raw", bits, derivedKeyType, extractable, usages); + } + + public static Byte[] WrapKey(String format, CryptoKey key, CryptoKey wrappingKey, Object wrapAlgorithm) + { + CheckFormat(format); + var normalized = NormalizeWrap(wrapAlgorithm, WrapKey_, Encrypt_); + CheckKey(wrappingKey, normalized, WrapKey_); + var exported = ExportKey(format, key); + var bytes = exported as Byte[] ?? Encoding.UTF8.GetBytes(ToJson(exported)); + return normalized.Name == "AES-KW" ? AesKeyWrap(wrappingKey.Secret, bytes) : EncryptCore(normalized, wrappingKey, bytes); + } + + public static CryptoKey UnwrapKey(String format, Byte[] wrappedKey, CryptoKey unwrappingKey, Object unwrapAlgorithm, Object unwrappedKeyAlgorithm, Boolean extractable, String[] usages) + { + CheckFormat(format); + var normalized = NormalizeWrap(unwrapAlgorithm, UnwrapKey_, Decrypt_); + Normalize(unwrappedKeyAlgorithm, ImportKey_); + CheckKey(unwrappingKey, normalized, UnwrapKey_); + wrappedKey = Required(wrappedKey); + var bytes = normalized.Name == "AES-KW" ? AesKeyUnwrap(unwrappingKey.Secret, wrappedKey) : DecryptCore(normalized, unwrappingKey, wrappedKey); + Object keyData = bytes; + + if (format == "jwk") + { + try + { + var engine = EngineInstance.Current.Jint; + keyData = new JsonParser(engine).Parse(Encoding.UTF8.GetString(bytes)) as ObjectInstance; + } + catch (JavaScriptException) + { + keyData = null; + } + + if (keyData is null) + { + throw DataError(); + } + } + + return ImportKey(format, keyData, unwrappedKeyAlgorithm, extractable, usages); + } + + #endregion + + #region Encryption + + private static Byte[] EncryptCore(Algorithm algorithm, CryptoKey key, Byte[] data) + { + switch (algorithm.Name) + { + case "AES-CBC": + using (var aes = CreateAes(key.Secret, CipherMode.CBC, PaddingMode.PKCS7)) + using (var encryptor = aes.CreateEncryptor(key.Secret, GetAesCbcIv(algorithm))) + { + return encryptor.TransformFinalBlock(data, 0, data.Length); + } + case "AES-CTR": + return AesCtr(algorithm, key.Secret, data); + case "AES-GCM": + return AesGcmEncrypt(algorithm, key.Secret, data); + default: + using (var rsa = CreateRsa(key)) + { + try + { + return rsa.Encrypt(data, GetOaepPadding(algorithm, key)); + } + catch (CryptographicException) + { + throw OperationError(); + } + } + } + } + + private static Byte[] DecryptCore(Algorithm algorithm, CryptoKey key, Byte[] data) + { + try + { + switch (algorithm.Name) + { + case "AES-CBC": + using (var aes = CreateAes(key.Secret, CipherMode.CBC, PaddingMode.PKCS7)) + using (var decryptor = aes.CreateDecryptor(key.Secret, GetAesCbcIv(algorithm))) + { + return decryptor.TransformFinalBlock(data, 0, data.Length); + } + case "AES-CTR": + return AesCtr(algorithm, key.Secret, data); + case "AES-GCM": + return AesGcmDecrypt(algorithm, key.Secret, data); + default: + using (var rsa = CreateRsa(key)) + { + return rsa.Decrypt(data, GetOaepPadding(algorithm, key)); + } + } + } + catch (CryptographicException) + { + throw OperationError(); + } + } + + private static Aes CreateAes(Byte[] key, CipherMode mode, PaddingMode padding) + { + var aes = Aes.Create(); + aes.Key = key; + aes.Mode = mode; + aes.Padding = padding; + return aes; + } + + private static Byte[] GetAesCbcIv(Algorithm algorithm) + { + var iv = algorithm.GetBytes("iv"); + return iv.Length == 16 ? iv : throw OperationError(); + } + + private static Byte[] AesCtr(Algorithm algorithm, Byte[] key, Byte[] data) + { + var counter = algorithm.GetBytes("counter"); + var length = algorithm.GetInteger("length") ?? throw TypeError("The length of the counter is missing."); + + if (counter.Length != 16 || length == 0 || length > 128) + { + throw OperationError(); + } + + var blocks = (data.Length + 15) / 16; + + // the counter must not wrap around, as it would encrypt with the same stream again + if (length < 63 && blocks > (1L << length)) + { + throw OperationError(); + } + + var block = (Byte[])counter.Clone(); + var stream = new Byte[16]; + var result = new Byte[data.Length]; + + using (var aes = CreateAes(key, CipherMode.ECB, PaddingMode.None)) + using (var encryptor = aes.CreateEncryptor()) + { + for (var offset = 0; offset < data.Length; offset += 16) + { + encryptor.TransformBlock(block, 0, 16, stream, 0); + + for (var i = 0; i < 16 && offset + i < data.Length; i++) + { + result[offset + i] = (Byte)(data[offset + i] ^ stream[i]); + } + + IncrementCounter(block, length); + } + } + + return result; + } + + // Only the rightmost bits (the given number) of the block are the counter. + private static void IncrementCounter(Byte[] block, Int32 bits) + { + for (var i = block.Length - 1; i >= 0 && bits > 0; i--, bits -= 8) + { + var mask = bits >= 8 ? 0xFF : (1 << bits) - 1; + var value = ((block[i] & mask) + 1) & mask; + block[i] = (Byte)((block[i] & ~mask) | value); + + if (value != 0) + { + break; + } + } + } + + private static Byte[] AesGcmEncrypt(Algorithm algorithm, Byte[] key, Byte[] data) + { +#if NET8_0_OR_GREATER + var (iv, additionalData, tagLength) = GetAesGcmParameters(algorithm); + var result = new Byte[data.Length + tagLength]; + + using (var gcm = new AesGcm(key, tagLength)) + { + gcm.Encrypt(iv, data, result.AsSpan(0, data.Length), result.AsSpan(data.Length), additionalData); + } + + return result; +#else + throw NotSupportedError(); +#endif + } + + private static Byte[] AesGcmDecrypt(Algorithm algorithm, Byte[] key, Byte[] data) + { +#if NET8_0_OR_GREATER + var (iv, additionalData, tagLength) = GetAesGcmParameters(algorithm); + + if (data.Length < tagLength) + { + throw OperationError(); + } + + var result = new Byte[data.Length - tagLength]; + + using (var gcm = new AesGcm(key, tagLength)) + { + gcm.Decrypt(iv, data.AsSpan(0, result.Length), data.AsSpan(result.Length), result, additionalData); + } + + return result; +#else + throw NotSupportedError(); +#endif + } + + private static (Byte[] Iv, Byte[] AdditionalData, Int32 TagLength) GetAesGcmParameters(Algorithm algorithm) + { + var iv = algorithm.GetBytes("iv"); + var additionalData = algorithm.GetBytes("additionalData", false); + var tagLength = algorithm.GetInteger("tagLength") ?? 128; + + if (Array.IndexOf(new[] { 32, 64, 96, 104, 112, 120, 128 }, tagLength) < 0) + { + throw OperationError(); + } + + // the platform takes 96 bit nonces and tags of at least 96 bits only + if (iv.Length != 12 || tagLength < 96) + { + throw NotSupportedError(); + } + + return (iv, additionalData, tagLength / 8); + } + + private static readonly Byte[] KeyWrapIv = { 0xA6, 0xA6, 0xA6, 0xA6, 0xA6, 0xA6, 0xA6, 0xA6 }; + + // RFC 3394 + private static Byte[] AesKeyWrap(Byte[] key, Byte[] data) + { + if (data.Length < 16 || data.Length % 8 != 0) + { + throw OperationError(); + } + + var n = data.Length / 8; + var a = (Byte[])KeyWrapIv.Clone(); + var r = (Byte[])data.Clone(); + var block = new Byte[16]; + + using (var aes = CreateAes(key, CipherMode.ECB, PaddingMode.None)) + using (var encryptor = aes.CreateEncryptor()) + { + for (var j = 0; j < 6; j++) + { + for (var i = 0; i < n; i++) + { + Buffer.BlockCopy(a, 0, block, 0, 8); + Buffer.BlockCopy(r, 8 * i, block, 8, 8); + encryptor.TransformBlock(block, 0, 16, block, 0); + Buffer.BlockCopy(block, 0, a, 0, 8); + XorCounter(a, (UInt64)(n * j + i + 1)); + Buffer.BlockCopy(block, 8, r, 8 * i, 8); + } + } + } + + var result = new Byte[data.Length + 8]; + Buffer.BlockCopy(a, 0, result, 0, 8); + Buffer.BlockCopy(r, 0, result, 8, data.Length); + return result; + } + + private static Byte[] AesKeyUnwrap(Byte[] key, Byte[] data) + { + if (data.Length < 24 || data.Length % 8 != 0) + { + throw OperationError(); + } + + var n = data.Length / 8 - 1; + var a = new Byte[8]; + var r = new Byte[data.Length - 8]; + var block = new Byte[16]; + Buffer.BlockCopy(data, 0, a, 0, 8); + Buffer.BlockCopy(data, 8, r, 0, r.Length); + + using (var aes = CreateAes(key, CipherMode.ECB, PaddingMode.None)) + using (var decryptor = aes.CreateDecryptor()) + { + for (var j = 5; j >= 0; j--) + { + for (var i = n - 1; i >= 0; i--) + { + XorCounter(a, (UInt64)(n * j + i + 1)); + Buffer.BlockCopy(a, 0, block, 0, 8); + Buffer.BlockCopy(r, 8 * i, block, 8, 8); + decryptor.TransformBlock(block, 0, 16, block, 0); + Buffer.BlockCopy(block, 0, a, 0, 8); + Buffer.BlockCopy(block, 8, r, 8 * i, 8); + } + } + } + + return AreEqual(a, KeyWrapIv) ? r : throw OperationError(); + } + + private static void XorCounter(Byte[] a, UInt64 t) + { + for (var k = 7; k >= 0; k--, t >>= 8) + { + a[k] ^= (Byte)t; + } + } + + #endregion + + #region Derivation + + private static Byte[] DeriveBitsCore(Algorithm algorithm, CryptoKey key, Int32? length) + { + switch (algorithm.Name) + { + case "PBKDF2": + { + var salt = algorithm.GetBytes("salt"); + var iterations = algorithm.GetInteger("iterations") ?? throw TypeError("The iterations are missing."); + var hash = algorithm.GetHash(); + + if (length is null || length.Value % 8 != 0 || iterations == 0) + { + throw OperationError(); + } + + return Pbkdf2(hash, key.Secret, salt, iterations, length.Value / 8); + } + case "HKDF": + { + var hash = algorithm.GetHash(); + var salt = algorithm.GetBytes("salt"); + var info = algorithm.GetBytes("info"); + + if (length is null || length.Value % 8 != 0 || length.Value / 8 > 255 * HashLength(hash)) + { + throw OperationError(); + } + + return Hkdf(hash, key.Secret, salt, info, length.Value / 8); + } + default: + { + var publicKey = algorithm.Get("public").FromJsValue() as CryptoKey ?? throw TypeError("The public key is missing."); + + if (publicKey.Type != "public" || publicKey.AlgorithmName != "ECDH" || publicKey.Curve != key.Curve) + { + throw InvalidAccessError(); + } + + var secret = EcdhSecret(key, publicKey); + + if (length is null) + { + return secret; + } + else if (length.Value > secret.Length * 8) + { + throw OperationError(); + } + + var result = new Byte[(length.Value + 7) / 8]; + Buffer.BlockCopy(secret, 0, result, 0, result.Length); + + if (length.Value % 8 != 0) + { + result[result.Length - 1] &= (Byte)(0xFF << (8 - length.Value % 8)); + } + + return result; + } + } + } + + private static Byte[] EcdhSecret(CryptoKey privateKey, CryptoKey publicKey) + { +#if NET8_0_OR_GREATER + using (var mine = ECDiffieHellman.Create(privateKey.Ec.Value)) + using (var theirs = ECDiffieHellman.Create(publicKey.Ec.Value)) + { + return mine.DeriveRawSecretAgreement(theirs.PublicKey); + } +#else + throw NotSupportedError(); +#endif + } + + private static Int32? GetKeyLength(Algorithm algorithm) + { + switch (algorithm.Name) + { + case "HMAC": + { + var length = algorithm.GetInteger("length") ?? BlockBits(algorithm.GetHash()); + return length != 0 ? length : throw TypeError("The length of the key can't be zero."); + } + case "PBKDF2": + case "HKDF": + return null; + default: + { + var length = algorithm.GetInteger("length") ?? throw TypeError("The length of the key is missing."); + return length == 128 || length == 192 || length == 256 ? length : throw OperationError(); + } + } + } + + private static Byte[] Pbkdf2(String hash, Byte[] password, Byte[] salt, Int32 iterations, Int32 length) + { +#if NET8_0_OR_GREATER + return Rfc2898DeriveBytes.Pbkdf2(password, salt, iterations, HashName(hash), length); +#else + var result = new Byte[length]; + var hashLength = HashLength(hash); + + using (var hmac = IncrementalHash.CreateHMAC(HashName(hash), password)) + { + for (var block = 1; (block - 1) * hashLength < length; block++) + { + hmac.AppendData(salt); + hmac.AppendData(new[] { (Byte)(block >> 24), (Byte)(block >> 16), (Byte)(block >> 8), (Byte)block }); + var u = hmac.GetHashAndReset(); + var t = (Byte[])u.Clone(); + + for (var i = 1; i < iterations; i++) + { + hmac.AppendData(u); + u = hmac.GetHashAndReset(); + + for (var k = 0; k < t.Length; k++) + { + t[k] ^= u[k]; + } + } + + var offset = (block - 1) * hashLength; + Buffer.BlockCopy(t, 0, result, offset, Math.Min(hashLength, length - offset)); + } + } + + return result; +#endif + } + + // RFC 5869 + private static Byte[] Hkdf(String hash, Byte[] secret, Byte[] salt, Byte[] info, Int32 length) + { + var hashLength = HashLength(hash); + var prk = Hmac(hash, salt.Length > 0 ? salt : new Byte[hashLength], secret); + var result = new Byte[length]; + var previous = new Byte[0]; + + for (var (i, offset) = (1, 0); offset < length; i++, offset += hashLength) + { + var input = new Byte[previous.Length + info.Length + 1]; + Buffer.BlockCopy(previous, 0, input, 0, previous.Length); + Buffer.BlockCopy(info, 0, input, previous.Length, info.Length); + input[input.Length - 1] = (Byte)i; + previous = Hmac(hash, prk, input); + Buffer.BlockCopy(previous, 0, result, offset, Math.Min(hashLength, length - offset)); + } + + return result; + } + + #endregion + + #region Import + + private static CryptoKey ImportHmacKey(String format, Byte[] data, Jwk jwk, Algorithm algorithm, Boolean extractable, String[] usages) + { + CheckUsages(usages, Sign_, Verify_); + var hash = algorithm.GetHash(); + + if (jwk != null) + { + jwk.CheckType("oct"); + jwk.CheckUse("sig"); + jwk.CheckAlgorithm(hash == "SHA-1" ? "HS1" : "HS" + hash.Substring(4)); + data = jwk.GetBytes("k"); + } + else if (format != "raw") + { + throw NotSupportedError(); + } + + var bits = data.Length * 8; + var length = algorithm.GetInteger("length") ?? bits; + + if (bits == 0 || length > bits || length <= bits - 8) + { + throw DataError(); + } + + return CreateHmacKey(hash, data, length, extractable, usages); + } + + private static CryptoKey ImportAesKey(String format, Byte[] data, Jwk jwk, String name, Boolean extractable, String[] usages) + { + CheckUsages(usages, GetAesUsages(name)); + + if (jwk != null) + { + jwk.CheckType("oct"); + jwk.CheckUse("enc"); + data = jwk.GetBytes("k"); + jwk.CheckAlgorithm("A" + data.Length * 8 + name.Substring(4)); + } + else if (format != "raw") + { + throw NotSupportedError(); + } + + if (data.Length != 16 && data.Length != 24 && data.Length != 32) + { + throw DataError(); + } + + return CreateAesKey(name, data, extractable, usages); + } + + private static CryptoKey ImportEcKey(String format, Byte[] data, Jwk jwk, Algorithm algorithm, Boolean extractable, String[] usages) + { + var isEcdsa = algorithm.Name == "ECDSA"; + var curve = GetCurve(algorithm); + var size = CoordinateLength(curve); + ECParameters parameters; + + switch (format) + { + case "raw": + if (data.Length != 1 + 2 * size || data[0] != 4) + { + throw DataError(); + } + + parameters = new ECParameters + { + Curve = GetNamedCurve(curve), + Q = new ECPoint { X = Slice(data, 1, size), Y = Slice(data, 1 + size, size) }, + }; + break; + case "jwk": + jwk.CheckType("EC"); + + if (jwk.Get("crv") != curve) + { + throw DataError(); + } + + if (isEcdsa) + { + jwk.CheckUse("sig"); + jwk.CheckAlgorithm(curve == "P-521" ? "ES512" : "ES" + curve.Substring(2)); + } + + parameters = new ECParameters + { + Curve = GetNamedCurve(curve), + Q = new ECPoint { X = jwk.GetBytes("x", size), Y = jwk.GetBytes("y", size) }, + D = jwk.Get("d") != null ? jwk.GetBytes("d", size) : null, + }; + break; + default: + parameters = ImportEcDer(format, data, curve); + break; + } + + try + { + using (var ecdsa = ECDsa.Create(parameters)) + { + // validated by the platform, e.g. that the point is on the curve + } + } + catch (CryptographicException) + { + throw DataError(); + } + + var isPrivate = parameters.D != null; + + if (isPrivate) + { + CheckUsages(usages, isEcdsa ? new[] { Sign_ } : new[] { DeriveKey_, DeriveBits_ }); + } + else + { + CheckUsages(usages, isEcdsa ? new[] { Verify_ } : new String[0]); + } + + return CreateEcKey(algorithm.Name, curve, parameters, extractable, usages); + } + + private static ECParameters ImportEcDer(String format, Byte[] data, String curve) + { +#if NET8_0_OR_GREATER + try + { + using (var ecdsa = ECDsa.Create()) + { + if (format == "spki") + { + ecdsa.ImportSubjectPublicKeyInfo(data, out _); + } + else + { + ecdsa.ImportPkcs8PrivateKey(data, out _); + } + + var parameters = ecdsa.ExportParameters(format == "pkcs8"); + return GetCurveName(parameters.Curve) == curve ? parameters : throw DataError(); + } + } + catch (CryptographicException) + { + throw DataError(); + } +#else + throw NotSupportedError(); +#endif + } + + private static CryptoKey ImportRsaKey(String format, Byte[] data, Jwk jwk, Algorithm algorithm, Boolean extractable, String[] usages) + { + var hash = algorithm.GetHash(); + var (publicUsages, privateUsages) = GetRsaUsages(algorithm.Name); + RSAParameters parameters; + + switch (format) + { + case "raw": + throw NotSupportedError(); + case "jwk": + jwk.CheckType("RSA"); + jwk.CheckUse(algorithm.Name == "RSA-OAEP" ? "enc" : "sig"); + jwk.CheckAlgorithm(GetRsaJwkAlgorithm(algorithm.Name, hash)); + var modulus = TrimZeros(jwk.GetBytes("n")); + var half = (modulus.Length + 1) / 2; + parameters = new RSAParameters + { + Modulus = modulus, + Exponent = TrimZeros(jwk.GetBytes("e")), + }; + + if (jwk.Get("d") != null) + { + // the platform needs the primes (and the values computed from them) too + if (jwk.Get("p") == null) + { + throw NotSupportedError(); + } + + parameters.D = jwk.GetBytes("d", modulus.Length); + parameters.P = jwk.GetBytes("p", half); + parameters.Q = jwk.GetBytes("q", half); + parameters.DP = jwk.GetBytes("dp", half); + parameters.DQ = jwk.GetBytes("dq", half); + parameters.InverseQ = jwk.GetBytes("qi", half); + } + + break; + default: + parameters = ImportRsaDer(format, data); + break; + } + + try + { + using (var rsa = RSA.Create()) + { + rsa.ImportParameters(parameters); + } + } + catch (CryptographicException) + { + throw DataError(); + } + + CheckUsages(usages, parameters.D != null ? privateUsages : publicUsages); + return CreateRsaKey(algorithm.Name, hash, parameters, extractable, usages); + } + + private static RSAParameters ImportRsaDer(String format, Byte[] data) + { +#if NET8_0_OR_GREATER + try + { + using (var rsa = RSA.Create()) + { + if (format == "spki") + { + rsa.ImportSubjectPublicKeyInfo(data, out _); + } + else + { + rsa.ImportPkcs8PrivateKey(data, out _); + } + + return rsa.ExportParameters(format == "pkcs8"); + } + } + catch (CryptographicException) + { + throw DataError(); + } +#else + throw NotSupportedError(); +#endif + } + + #endregion + + #region Export + + private static IDictionary ExportJwk(CryptoKey key) + { + var jwk = new Dictionary(); + + switch (key.AlgorithmName) + { + case "HMAC": + jwk["kty"] = "oct"; + jwk["k"] = ToBase64Url(key.Secret); + jwk["alg"] = key.Hash == "SHA-1" ? "HS1" : "HS" + key.Hash.Substring(4); + break; + case "AES-CBC": + case "AES-CTR": + case "AES-GCM": + case "AES-KW": + jwk["kty"] = "oct"; + jwk["k"] = ToBase64Url(key.Secret); + jwk["alg"] = "A" + key.Secret.Length * 8 + key.AlgorithmName.Substring(4); + break; + case "ECDSA": + case "ECDH": + { + var ec = key.Ec.Value; + var size = CoordinateLength(key.Curve); + jwk["kty"] = "EC"; + jwk["crv"] = key.Curve; + jwk["x"] = ToBase64Url(Pad(ec.Q.X, size)); + jwk["y"] = ToBase64Url(Pad(ec.Q.Y, size)); + + if (key.Type == "private") + { + jwk["d"] = ToBase64Url(Pad(ec.D, size)); + } + + break; + } + case "RSASSA-PKCS1-v1_5": + case "RSA-PSS": + case "RSA-OAEP": + { + var rsa = key.Rsa.Value; + jwk["kty"] = "RSA"; + jwk["alg"] = GetRsaJwkAlgorithm(key.AlgorithmName, key.Hash); + jwk["n"] = ToBase64Url(TrimZeros(rsa.Modulus)); + jwk["e"] = ToBase64Url(TrimZeros(rsa.Exponent)); + + if (key.Type == "private") + { + jwk["d"] = ToBase64Url(TrimZeros(rsa.D)); + jwk["p"] = ToBase64Url(TrimZeros(rsa.P)); + jwk["q"] = ToBase64Url(TrimZeros(rsa.Q)); + jwk["dp"] = ToBase64Url(TrimZeros(rsa.DP)); + jwk["dq"] = ToBase64Url(TrimZeros(rsa.DQ)); + jwk["qi"] = ToBase64Url(TrimZeros(rsa.InverseQ)); + } + + break; + } + default: + throw NotSupportedError(); + } + + jwk["key_ops"] = key.Usages; + jwk["ext"] = key.Extractable; + return jwk; + } + + private static Byte[] ExportDer(String format, CryptoKey key) + { + var isPublic = format == "spki"; + + if (key.Secret != null || (isPublic ? key.Type != "public" : key.Type != "private")) + { + throw InvalidAccessError(); + } + +#if NET8_0_OR_GREATER + if (key.Ec is ECParameters ec) + { + using (var ecdsa = ECDsa.Create(ec)) + { + return isPublic ? ecdsa.ExportSubjectPublicKeyInfo() : ecdsa.ExportPkcs8PrivateKey(); + } + } + + using (var rsa = CreateRsa(key)) + { + return isPublic ? rsa.ExportSubjectPublicKeyInfo() : rsa.ExportPkcs8PrivateKey(); + } +#else + throw NotSupportedError(); +#endif + } + + private static String ToJson(Object value) + { + var engine = EngineInstance.Current; + return new JsonSerializer(engine.Jint).Serialize(value.ToJsValue(engine)).ToString(); + } + + #endregion + + #region Keys + + private static CryptoKey CreateHmacKey(String hash, Byte[] data, Int32 length, Boolean extractable, String[] usages) + { + var algorithm = CreateAlgorithm("HMAC"); + algorithm["hash"] = CreateAlgorithm(hash); + algorithm["length"] = length; + return new CryptoKey("secret", extractable, algorithm, usages) { Secret = data, Hash = hash }; + } + + private static CryptoKey CreateAesKey(String name, Byte[] data, Boolean extractable, String[] usages) + { + var algorithm = CreateAlgorithm(name); + algorithm["length"] = data.Length * 8; + return new CryptoKey("secret", extractable, algorithm, usages) { Secret = data }; + } + + private static CryptoKey CreateEcKey(String name, String curve, ECParameters parameters, Boolean extractable, String[] usages) + { + var algorithm = CreateAlgorithm(name); + algorithm["namedCurve"] = curve; + var type = parameters.D != null ? "private" : "public"; + return new CryptoKey(type, extractable, algorithm, usages) { Ec = parameters, Curve = curve }; + } + + private static CryptoKey CreateRsaKey(String name, String hash, RSAParameters parameters, Boolean extractable, String[] usages) + { + var algorithm = CreateAlgorithm(name); + algorithm["modulusLength"] = TrimZeros(parameters.Modulus).Length * 8; + algorithm["publicExponent"] = new ArraySegment(TrimZeros(parameters.Exponent)); + algorithm["hash"] = CreateAlgorithm(hash); + var type = parameters.D != null ? "private" : "public"; + return new CryptoKey(type, extractable, algorithm, usages) { Rsa = parameters, Hash = hash }; + } + + private static IDictionary CreateKeyPair(CryptoKey publicKey, CryptoKey privateKey) => + new Dictionary + { + ["publicKey"] = publicKey, + ["privateKey"] = privateKey, + }; + + private static Dictionary CreateAlgorithm(String name) => + new Dictionary { ["name"] = name }; + + private static ECParameters PublicPart(ECParameters parameters) => + new ECParameters { Curve = parameters.Curve, Q = parameters.Q }; + + private static RSAParameters PublicPart(RSAParameters parameters) => + new RSAParameters { Modulus = parameters.Modulus, Exponent = parameters.Exponent }; + + private static RSA CreateRsa(CryptoKey key) + { + var rsa = RSA.Create(); + rsa.ImportParameters(key.Rsa.Value); + return rsa; + } + + private static RSASignaturePadding GetRsaPadding(Algorithm algorithm, CryptoKey key) + { + if (algorithm.Name == "RSA-PSS") + { + var saltLength = algorithm.GetInteger("saltLength") ?? throw TypeError("The saltLength is missing."); + + // the platform uses a salt as long as the hash, which is what is used most + return saltLength == HashLength(key.Hash) ? RSASignaturePadding.Pss : throw NotSupportedError(); + } + + return RSASignaturePadding.Pkcs1; + } + + private static RSAEncryptionPadding GetOaepPadding(Algorithm algorithm, CryptoKey key) + { + var label = algorithm.GetBytes("label", false); + + if (label != null && label.Length > 0) + { + throw NotSupportedError(); + } + + switch (key.Hash) + { + case "SHA-1": + return RSAEncryptionPadding.OaepSHA1; + case "SHA-256": + return RSAEncryptionPadding.OaepSHA256; + case "SHA-384": + return RSAEncryptionPadding.OaepSHA384; + default: + return RSAEncryptionPadding.OaepSHA512; + } + } + + private static String GetRsaJwkAlgorithm(String name, String hash) + { + var bits = hash == "SHA-1" ? "1" : hash.Substring(4); + + switch (name) + { + case "RSASSA-PKCS1-v1_5": + return "RS" + bits; + case "RSA-PSS": + return "PS" + bits; + default: + return hash == "SHA-1" ? "RSA-OAEP" : "RSA-OAEP-" + bits; + } + } + + private static (String[] Public, String[] Private) GetRsaUsages(String name) => + name == "RSA-OAEP" + ? (new[] { Encrypt_, WrapKey_ }, new[] { Decrypt_, UnwrapKey_ }) + : (new[] { Verify_ }, new[] { Sign_ }); + + private static String[] GetAesUsages(String name) => + name == "AES-KW" ? new[] { WrapKey_, UnwrapKey_ } : new[] { Encrypt_, Decrypt_, WrapKey_, UnwrapKey_ }; + + private static String GetCurve(Algorithm algorithm) + { + var value = algorithm.Get("namedCurve"); + + if (value.IsUndefined()) + { + throw TypeError("The namedCurve is missing."); + } + + var curve = TypeConverter.ToString(value); + return curve == "P-256" || curve == "P-384" || curve == "P-521" ? curve : throw NotSupportedError(); + } + + private static ECCurve GetNamedCurve(String curve) + { + switch (curve) + { + case "P-256": + return ECCurve.NamedCurves.nistP256; + case "P-384": + return ECCurve.NamedCurves.nistP384; + default: + return ECCurve.NamedCurves.nistP521; + } + } + + private static String GetCurveName(ECCurve curve) + { + switch (curve.Oid?.Value) + { + case "1.2.840.10045.3.1.7": + return "P-256"; + case "1.3.132.0.34": + return "P-384"; + case "1.3.132.0.35": + return "P-521"; + } + + switch (curve.Oid?.FriendlyName) + { + case "nistP256": + case "ECDSA_P256": + return "P-256"; + case "nistP384": + case "ECDSA_P384": + return "P-384"; + case "nistP521": + case "ECDSA_P521": + return "P-521"; + } + + return null; + } + + private static Int32 CoordinateLength(String curve) => + curve == "P-256" ? 32 : curve == "P-384" ? 48 : 66; + + private static Byte[] EncodePoint(ECParameters parameters, String curve) + { + var size = CoordinateLength(curve); + var result = new Byte[1 + 2 * size]; + result[0] = 4; + Buffer.BlockCopy(Pad(parameters.Q.X, size), 0, result, 1, size); + Buffer.BlockCopy(Pad(parameters.Q.Y, size), 0, result, 1 + size, size); + return result; + } + + #endregion + + #region Checks + + private static Algorithm Normalize(Object algorithm, String operation) + { + String name; + var source = algorithm as ObjectInstance; + + if (algorithm is String text) + { + name = text; + } + else if (source != null && !source.IsBufferSource()) + { + var value = source.Get("name"); + + if (value.IsUndefined()) + { + throw TypeError("The algorithm has no name."); + } + + name = TypeConverter.ToString(value); + } + else + { + throw TypeError("The algorithm has to be a name or an object."); + } + + var canonical = Operations.Keys.FirstOrDefault(key => key.Equals(name, StringComparison.OrdinalIgnoreCase)); + + if (canonical is null || Array.IndexOf(Operations[canonical], operation) < 0) + { + throw NotSupportedError(); + } + + return new Algorithm(canonical, source); + } + + private static Algorithm NormalizeWrap(Object algorithm, String operation, String fallback) + { + try + { + return Normalize(algorithm, operation); + } + catch (DomException) + { + return Normalize(algorithm, fallback); + } + } + + private static void CheckKey(CryptoKey key, Algorithm algorithm, String usage) + { + if (key is null) + { + throw TypeError("The key is missing."); + } + else if (key.AlgorithmName != algorithm.Name || !key.Allows(usage)) + { + throw InvalidAccessError(); + } + } + + private static void CheckFormat(String format) + { + if (format != "raw" && format != "spki" && format != "pkcs8" && format != "jwk") + { + throw TypeError($"The format '{format}' is not one of raw, spki, pkcs8 or jwk."); + } + } + + private static String[] CheckUsageValues(String[] usages) + { + usages = usages ?? throw TypeError("The key usages are missing."); + + foreach (var usage in usages) + { + if (Array.IndexOf(AllUsages, usage) < 0) + { + throw TypeError($"The key usage '{usage}' is not valid."); + } + } + + return AllUsages.Where(usage => usages.Contains(usage)).ToArray(); + } + + private static void CheckUsages(String[] usages, params String[] allowed) + { + if (usages.Any(usage => Array.IndexOf(allowed, usage) < 0)) + { + throw SyntaxError(); + } + } + + private static String[] Intersect(String[] usages, String[] allowed) => + AllUsages.Where(usage => usages.Contains(usage) && allowed.Contains(usage)).ToArray(); + + // A secret or private key that can't be used for anything is an error. + private static CryptoKey RequireUsages(CryptoKey key) => + key.Type != "public" && key.Usages.Length == 0 ? throw SyntaxError() : key; + + private static Byte[] Required(Byte[] data) => + data ?? throw TypeError("The data has to be an ArrayBuffer or a view on one."); + + #endregion + + #region Helpers + + private static HashAlgorithmName HashName(String hash) + { + switch (hash) + { + case "SHA-1": + return HashAlgorithmName.SHA1; + case "SHA-256": + return HashAlgorithmName.SHA256; + case "SHA-384": + return HashAlgorithmName.SHA384; + default: + return HashAlgorithmName.SHA512; + } + } + + private static Int32 HashLength(String hash) => + hash == "SHA-1" ? 20 : hash == "SHA-256" ? 32 : hash == "SHA-384" ? 48 : 64; + + private static Int32 BlockBits(String hash) => + hash == "SHA-384" || hash == "SHA-512" ? 1024 : 512; + + private static Byte[] Hash(String hash, Byte[] data) + { + using (var algorithm = IncrementalHash.CreateHash(HashName(hash))) + { + algorithm.AppendData(data); + return algorithm.GetHashAndReset(); + } + } + + private static Byte[] Hmac(String hash, Byte[] key, Byte[] data) + { + using (var algorithm = IncrementalHash.CreateHMAC(HashName(hash), key)) + { + algorithm.AppendData(data); + return algorithm.GetHashAndReset(); + } + } + + private static Byte[] RandomBytes(Int32 count) + { + var bytes = new Byte[count]; + + using (var random = RandomNumberGenerator.Create()) + { + random.GetBytes(bytes); + } + + return bytes; + } + + // In constant time, so a signature can't be guessed byte by byte. + private static Boolean AreEqual(Byte[] a, Byte[] b) + { + if (a.Length != b.Length) + { + return false; + } + + var difference = 0; + + for (var i = 0; i < a.Length; i++) + { + difference |= a[i] ^ b[i]; + } + + return difference == 0; + } + + private static Byte[] TrimZeros(Byte[] value) + { + var start = 0; + + while (start < value.Length - 1 && value[start] == 0) + { + start++; + } + + return Slice(value, start, value.Length - start); + } + + private static Byte[] Pad(Byte[] value, Int32 length) + { + value = TrimZeros(value); + + if (value.Length > length) + { + throw DataError(); + } + + var result = new Byte[length]; + Buffer.BlockCopy(value, 0, result, length - value.Length, value.Length); + return result; + } + + private static Byte[] Slice(Byte[] value, Int32 offset, Int32 length) + { + var result = new Byte[length]; + Buffer.BlockCopy(value, offset, result, 0, length); + return result; + } + + private static String ToBase64Url(Byte[] value) => + Convert.ToBase64String(value).TrimEnd('=').Replace('+', '-').Replace('/', '_'); + + private static Byte[] FromBase64Url(String value) + { + var text = value.Replace('-', '+').Replace('_', '/'); + + try + { + return Convert.FromBase64String(text.PadRight(text.Length + (4 - text.Length % 4) % 4, '=')); + } + catch (FormatException) + { + throw DataError(); + } + } + + private static Exception TypeError(String message) => + new JavaScriptException(EngineInstance.Current.Jint.Intrinsics.TypeError, message); + + private static Exception NotSupportedError() => new DomException(DomError.NotSupported); + + private static Exception SyntaxError() => new DomException(DomError.Syntax); + + private static Exception InvalidAccessError() => new DomException(DomError.InvalidAccess); + + private static Exception OperationError() => new DomException("OperationError"); + + private static Exception DataError() => new DomException("DataError"); + + #endregion + + #region Nested types + + /// + /// A normalized algorithm: its name, and the object of a script with its parameters. + /// + private sealed class Algorithm + { + private readonly ObjectInstance _source; + + public Algorithm(String name, ObjectInstance source) + { + Name = name; + _source = source; + } + + public String Name { get; } + + public JsValue Get(String member) => _source?.Get(member) ?? JsValue.Undefined; + + public Byte[] GetBytes(String member, Boolean isRequired = true) + { + var value = Get(member); + + if (value.IsUndefined() && !isRequired) + { + return null; + } + else if (value is ObjectInstance obj && value.IsBufferSource()) + { + return obj.GetBytes(); + } + + throw TypeError($"The {member} has to be an ArrayBuffer or a view on one."); + } + + public Int32? GetInteger(String member) + { + var value = Get(member); + return value.IsUndefined() ? (Int32?)null : (Int32)TypeConverter.ToUint32(value); + } + + public String GetHash() + { + var value = Get("hash"); + + if (value.IsUndefined()) + { + throw TypeError("The hash is missing."); + } + + return Normalize(value.FromJsValue(), Digest_).Name; + } + } + + /// + /// A JSON Web Key (RFC 7517) given by a script. + /// + private sealed class Jwk + { + private readonly ObjectInstance _source; + + public Jwk(ObjectInstance source) + { + _source = source; + } + + public String Get(String member) + { + var value = _source.Get(member); + return value.IsUndefined() || value.IsNull() ? null : TypeConverter.ToString(value); + } + + public Byte[] GetBytes(String member) => FromBase64Url(Get(member) ?? throw DataError()); + + public Byte[] GetBytes(String member, Int32 length) => Pad(GetBytes(member), length); + + public void Check(Boolean extractable, String[] usages) + { + if (Get("kty") is null) + { + throw DataError(); + } + + var ext = _source.Get("ext"); + + if (extractable && !ext.IsUndefined() && !TypeConverter.ToBoolean(ext)) + { + throw DataError(); + } + + if (_source.Get("key_ops") is JsArray ops) + { + var allowed = Enumerable.Range(0, (Int32)TypeConverter.ToNumber(ops.Get("length"))) + .Select(i => TypeConverter.ToString(ops.Get(i.ToString()))) + .ToArray(); + + if (usages.Any(usage => !allowed.Contains(usage))) + { + throw DataError(); + } + } + } + + public void CheckType(String kty) + { + if (Get("kty") != kty) + { + throw DataError(); + } + } + + public void CheckUse(String use) + { + var value = Get("use"); + + if (value != null && value != use) + { + throw DataError(); + } + } + + public void CheckAlgorithm(String alg) + { + var value = Get("alg"); + + if (value != null && value != alg) + { + throw DataError(); + } + } + } + + #endregion + } +} From 7be766feca5d91d3271b8243315ccb497828d090 Mon Sep 17 00:00:00 2001 From: Florian Rappl Date: Mon, 23 Nov 2026 08:11:43 +0100 Subject: [PATCH 06/19] Conformance fixes and enhancements --- CHANGELOG.md | 12 + src/AngleSharp.Js.Tests/Html5TestTests.cs | 3 + src/AngleSharp.Js.Tests/InteropTests.cs | 223 ++++++++++++++++ src/AngleSharp.Js.Tests/ModuleTests.cs | 75 +++++- src/AngleSharp.Js.Tests/WorkerTests.cs | 13 + src/AngleSharp.Js/EngineInstance.cs | 245 +++++++++++++++++- src/AngleSharp.Js/Extensions/DomDelegates.cs | 10 + .../Extensions/EngineExtensions.cs | 59 ++++- .../Extensions/JsValueExtensions.cs | 18 ++ .../Extensions/OverloadResolution.cs | 5 + .../Extensions/ReflectionExtensions.cs | 35 ++- src/AngleSharp.Js/JsHost.cs | 26 +- src/AngleSharp.Js/JsModuleLoader.cs | 72 ++++- src/AngleSharp.Js/JsScriptingService.cs | 28 +- .../Proxies/DomConstructorInstance.cs | 19 +- src/AngleSharp.Js/Proxies/ScriptCallback.cs | 105 ++++++++ 16 files changed, 916 insertions(+), 32 deletions(-) create mode 100644 src/AngleSharp.Js.Tests/InteropTests.cs create mode 100644 src/AngleSharp.Js/Proxies/ScriptCallback.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index fdb43ac9..3f6a6537 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,19 @@ Released on tbd. +- Fixed a module with a top-level `await` blocking the page for many seconds +- Fixed import map entries of a prefix not being used +- Fixed an `import()` of a module that could not be fetched not rejecting with a `TypeError` +- Fixed the DOM of libraries registered by a creator only being missing +- Updated a WebIDL namespace to be a plain object, whose members are no longer members of the window too - Added `SharedWorker`, which the scripts of an origin creating it for the same address +- Added CSS module scripts (`import sheet from './a.css' with { type: 'css' }`), whose default export is a constructed style sheet +- Added `import.meta.resolve()` +- Added interfaces of a namespace (`[DomExposed("WebAssembly")]` puts `WebAssembly.Module` there instead of on the window) +- Added delegates of the DOM as functions of scripts +- Added `BigInteger` as BigInt, `Memory` as an ArrayBuffer +- Added exceptions of the DOM (e.g. `WebAssembly.RuntimeError`) being errors of their class +- Added the Web Cryptography API (`crypto.subtle`, also in workers) # 1.2.3 diff --git a/src/AngleSharp.Js.Tests/Html5TestTests.cs b/src/AngleSharp.Js.Tests/Html5TestTests.cs index d22146d3..d3616658 100644 --- a/src/AngleSharp.Js.Tests/Html5TestTests.cs +++ b/src/AngleSharp.Js.Tests/Html5TestTests.cs @@ -27,6 +27,9 @@ public async Task Html5TestShouldProduceScoreWithoutScriptErrors() Assert.IsNotNull(score, failureMessage); TestContext.WriteLine("HTML5test score: {0}", score.TextContent); Assert.Greater(Double.Parse(score.TextContent, CultureInfo.InvariantCulture), 0.0, failureMessage); + // AngleSharp.Io before 1.4.0 (the one of these tests) rejects the fetch('') of the page, + // instead of fetching the address of the document. + errors.RemoveAll(error => error.Message.Contains("Value cannot be null. (Parameter 'url')")); Assert.IsEmpty(errors, failureMessage); } diff --git a/src/AngleSharp.Js.Tests/InteropTests.cs b/src/AngleSharp.Js.Tests/InteropTests.cs new file mode 100644 index 00000000..08db1adc --- /dev/null +++ b/src/AngleSharp.Js.Tests/InteropTests.cs @@ -0,0 +1,223 @@ +namespace AngleSharp.Js.Tests +{ + using AngleSharp.Attributes; + using AngleSharp.Dom; + using NUnit.Framework; + using System; + using System.Collections.Generic; + using System.Numerics; + using System.Threading.Tasks; + + /// + /// What a library can give to scripts besides objects of the DOM: namespaces with interfaces + /// of their own, functions, BigInts, shared buffers, promises and errors of its own. + /// + [TestFixture] + public class InteropTests + { + private static async Task Run(String body) + { + // a service of this assembly makes it one of the libraries of the scripts + var cfg = Configuration.Default.WithJs().WithEventLoop().WithOnly(_ => new InteropService()); + var script = $"(async function () {{ {body} }})().then(function (r) {{ document.title = 'ok:' + r; }}, function (e) {{ document.title = 'error:' + e; }});"; + var document = await BrowsingContext.New(cfg).OpenAsync(m => m.Content($"")); + + for (var i = 0; i < 200 && String.IsNullOrEmpty(document.Title); i++) + { + await Task.Delay(20); + } + + return document.Title; + } + + [Test] + public async Task LibraryOfAServiceGivenByACreatorIsFound() + { + Assert.AreEqual("ok:object", await Run("return typeof Interop;")); + } + + [Test] + public async Task NamespaceIsAnObjectWithItsMembersAndInterfaces() + { + var result = await Run(@" + return [typeof Interop, Object.prototype.toString.call(Interop), Interop.twice(21), typeof Interop.Thing, + new Interop.Thing(5).size, new Interop.Thing(5) instanceof Interop.Thing, typeof Thing, 'twice' in window, + Object.keys(window).indexOf('Interop')].join();"); + + Assert.AreEqual("ok:object,[object Interop],42,function,5,true,undefined,false,-1", result); + } + + [Test] + public async Task DelegateIsAFunction() + { + var result = await Run(@" + var add = Interop.adder(); + var join = Interop.joiner(); + return [typeof add, add(2, 3), add.length, Interop.adder() === add, join(1, 'a', undefined, true), join.length, Interop.echo(join) === join, Interop.isJoiner(join)].join();"); + + Assert.AreEqual("ok:function,5,2,true,Double:1|String:a|Missing|Boolean:True,0,true,true", result); + } + + [Test] + public async Task FunctionOfAScriptIsAVariadicDelegate() + { + var result = await Run(@" + var f = function () { return Array.prototype.join.call(arguments, '+'); }; + return [Interop.call(f), Interop.echo(f) === f].join();"); + + Assert.AreEqual("ok:1+x+,true", result); + } + + [Test] + public async Task BigIntegerIsABigInt() + { + var result = await Run("var b = Interop.big(); return [typeof b, b === 2n ** 70n, Interop.bigOf(12n)].join();"); + Assert.AreEqual("ok:bigint,true,BigInteger:12", result); + } + + [Test] + public async Task MemoryIsASharedArrayBuffer() + { + var result = await Run(@" + var buffer = Interop.buffer(); + new Uint8Array(buffer)[1] = 7; + return [buffer instanceof ArrayBuffer, buffer.byteLength, buffer === Interop.buffer(), Interop.byteAt(1)].join();"); + + Assert.AreEqual("ok:true,4,true,7", result); + } + + [Test] + public async Task PromiseIsATask() + { + var result = await Run(@" + var a = await Interop.later(Promise.resolve('given')); + var b = await Interop.later('value'); + var c = await Interop.later(Promise.reject(new Error('no'))).catch(function (e) { return 'caught ' + e.message; }); + return [a, b, c].join();"); + + Assert.AreEqual("ok:given!,value!,caught no", result); + } + + [Test] + public async Task ExceptionOfTheDomIsAnErrorOfItsClass() + { + var result = await Run(@" + try { Interop.fail(); } catch (e) { + return [e instanceof Interop.Failure, e instanceof Error, e.message, e.name, new Interop.Failure('made') instanceof Error].join(); + }"); + + Assert.AreEqual("ok:true,true,it broke,Failure,true", result); + } + + [Test] + public async Task ExceptionOfTheDomCanBeAwaited() + { + var result = await Run(@" + var made = new Interop.Failure('made'); + try { await Promise.reject(made); } catch (e) { return [e === made, e.message, typeof e.stack].join(); }"); + + Assert.AreEqual("ok:true,made,string", result); + } + + [Test] + public async Task FunctionOfADelegateIsTheDelegateForAnObject() + { + Assert.AreEqual("ok:Variadic", await Run("return Interop.typeOf(Interop.joiner());")); + } + + [Test] + public async Task CssIsANamespace() + { + var document = await BrowsingContext.New(Helpers.GetCssConfig()).OpenAsync(m => m.Content("")); + Assert.AreEqual("object,a\\ b,false", document.Title); + } + + [Test] + public async Task MixinHasNoInterfaceObject() + { + Assert.AreEqual("undefined,function", await "[typeof WindowBase64, typeof btoa].join()".EvalScriptAsync()); + } + } + + public sealed class InteropService + { + } + + public delegate Object Variadic(Object[] arguments); + + [DomName("Interop")] + [DomExposed("Window")] + public static class InteropNamespace + { + private static readonly Byte[] Bytes = new Byte[4]; + private static readonly Func Add = (a, b) => a + b; + private static readonly Variadic Join = arguments => String.Join("|", Array.ConvertAll(arguments, m => m == System.Reflection.Missing.Value ? "Missing" : m.GetType().Name + ":" + m)); + + [DomName("twice")] + public static Double Twice(this IWindow window, Double value) => 2 * value; + + [DomName("adder")] + public static Func Adder() => Add; + + [DomName("joiner")] + public static Variadic Joiner() => Join; + + [DomName("call")] + public static Object Call(Variadic callback) => callback(new Object[] { 1, "x", null }); + + [DomName("isJoiner")] + public static Boolean IsJoiner(Variadic callback) => ReferenceEquals(callback, Join); + + [DomName("echo")] + public static Variadic Echo(Variadic callback) => callback; + + [DomName("big")] + public static Object Big() => BigInteger.Pow(2, 70); + + [DomName("bigOf")] + public static String BigOf(Object value) => value.GetType().Name + ":" + value; + + [DomName("buffer")] + public static Object Buffer() => new Memory(Bytes); + + [DomName("byteAt")] + public static Int32 ByteAt(Int32 index) => Bytes[index]; + + [DomName("later")] + public static async Task Later(Task value) => await value + "!"; + + [DomName("typeOf")] + public static String TypeOf(Object value) => value.GetType().Name; + + [DomName("fail")] + public static void Fail() => throw new InteropFailure("it broke"); + } + + [DomName("Thing")] + [DomExposed("Interop")] + public sealed class InteropThing + { + [DomConstructor] + public InteropThing(Int32 size) + { + Size = size; + } + + [DomName("size")] + public Int32 Size { get; } + } + + [DomName("Failure")] + [DomExposed("Interop")] + public sealed class InteropFailure : Exception + { + [DomConstructor] + public InteropFailure(String message) + : base(message) + { + } + + [DomName("name")] + public String Name => "Failure"; + } +} diff --git a/src/AngleSharp.Js.Tests/ModuleTests.cs b/src/AngleSharp.Js.Tests/ModuleTests.cs index 1d858758..26770dbe 100644 --- a/src/AngleSharp.Js.Tests/ModuleTests.cs +++ b/src/AngleSharp.Js.Tests/ModuleTests.cs @@ -300,5 +300,78 @@ private static async Task OpenFileAsync(String html, Dictionary WaitForTitleAsync(IDocument document, String initial = "") + { + for (var i = 0; i < 100 && document.Title == initial; i++) + { + await Task.Delay(50); + } + + return document.Title; + } + + [Test] + public async Task ImportMapPrefixFindsTheRestOfTheSpecifier() + { + var document = await OpenAsync(@"", new Dictionary + { + { "/js/lib/a.js", "export const a = 'a';" }, + { "/other/b.js", "export const b = 'b';" }, + }); + + Assert.AreEqual("ab", document.Title); + } + + [Test] + public async Task ModuleWithATopLevelAwaitGoesOnOnceItIsSettled() + { + var watch = System.Diagnostics.Stopwatch.StartNew(); + var document = await OpenAsync("", new Dictionary + { + { "/dir/later.js", "export const value = await new Promise(resolve => setTimeout(() => resolve('settled'), 20));" }, + }); + + Assert.AreEqual("settled", await WaitForTitleAsync(document)); + // the timer runs on the event loop, which the module doesn't wait for + Assert.Less(watch.ElapsedMilliseconds, 5000); + } + + [Test] + public async Task ImportOfAModuleNotFoundRejectsWithATypeError() + { + var document = await OpenAsync(""); + + Assert.AreEqual("TypeError", await WaitForTitleAsync(document)); + } + + [Test] + public async Task CssModuleGivesAStyleSheet() + { + var config = Configuration.Default + .WithCss() + .WithJs() + .WithEventLoop() + .With(new MockHttpClientRequester(new Dictionary { { "/dir/style.css", ".a { color: red } .b { color: blue }" } })) + .WithDefaultLoader(new LoaderOptions { IsResourceLoadingEnabled = true }); + var document = await BrowsingContext.New(config).OpenAsync(r => r.Address(Page).Content("")); + await document.WhenStable(); + + if (await WaitForTitleAsync(document) == "not constructible") + { + Assert.Ignore("The style sheets of the referenced AngleSharp.Css can't be constructed."); + } + + Assert.AreEqual("true 2", await WaitForTitleAsync(document)); + } + + [Test] + public async Task ImportMetaResolveGivesTheAddressOfASpecifier() + { + var document = await OpenAsync(@""); + + Assert.AreEqual("https://example.com/dir/x.js https://example.com/js/dep.js", document.Title); + } +} } diff --git a/src/AngleSharp.Js.Tests/WorkerTests.cs b/src/AngleSharp.Js.Tests/WorkerTests.cs index 2c9033f3..e3d2ad60 100644 --- a/src/AngleSharp.Js.Tests/WorkerTests.cs +++ b/src/AngleSharp.Js.Tests/WorkerTests.cs @@ -75,6 +75,19 @@ public async Task WorkerRunsAModuleWithItsImports() worker.Terminate(); } + [Test] + public async Task WorkerHasWebCrypto() + { + var document = await OpenWithSourcesAsync(("https://example.com/worker.js", "crypto.subtle.digest('SHA-1', new Uint8Array(0)).then(function (d) { self.__d = d.byteLength; });")); + var worker = new AngleSharp.Js.Dom.Worker(document.DefaultView, "https://example.com/worker.js"); + + Assert.IsTrue(await WaitFor(() => worker.IsInitialized || worker.StartupError != null)); + Assert.IsNull(worker.StartupError, worker.StartupError?.ToString()); + Assert.IsTrue(await WaitFor(() => worker.EvaluateInWorker("String(self.__d)")?.ToString() == "20")); + Assert.AreEqual("object,function", worker.EvaluateInWorker("[typeof crypto.subtle, typeof CryptoKey].join()")?.ToString()); + worker.Terminate(); + } + [Test] public async Task WorkerKnowsItsAddress() { diff --git a/src/AngleSharp.Js/EngineInstance.cs b/src/AngleSharp.Js/EngineInstance.cs index b537fe6d..d0d28cf2 100644 --- a/src/AngleSharp.Js/EngineInstance.cs +++ b/src/AngleSharp.Js/EngineInstance.cs @@ -19,6 +19,8 @@ namespace AngleSharp.Js using Jint.Runtime.Descriptors; using Jint.Runtime.Interop; using System; + using AngleSharp.Js.Proxies; + using System.Runtime.InteropServices; using System.Collections; using System.Collections.Generic; using System.Reflection; @@ -48,6 +50,10 @@ sealed class EngineInstance #region Fields private Int32 _scriptDepth; + private ICollection _namespaces; + private readonly ConditionalWeakTable _functions = new ConditionalWeakTable(); + private readonly ConditionalWeakTable _delegates = new ConditionalWeakTable(); + private readonly ConditionalWeakTable _buffers = new ConditionalWeakTable(); private const String ScriptValueKey = "AngleSharp.ScriptValue"; // Jint's StackGuard.Disabled, which is internal. @@ -55,6 +61,7 @@ sealed class EngineInstance private readonly Engine _engine; private readonly TimeSpan _regexTimeout; + private readonly Options.ConstraintOptions _constraints; private readonly Boolean _retainFunctionSourceText; private readonly PrototypeCache _prototypes; private readonly ReferenceCache _references; @@ -80,8 +87,9 @@ public EngineInstance(IWindow window, IDictionary assignments, I { _importMap = new JsImportMap(); var engineOptions = new Options(); - engineOptions.EnableModules(new JsModuleLoader(this, window.Document)); - engineOptions.UseHostFactory(_ => new JsHost(window.Document)); + var moduleLoader = new JsModuleLoader(this, window.Document); + engineOptions.EnableModules(moduleLoader); + engineOptions.UseHostFactory(engine => new JsHost(engine, window.Document, moduleLoader)); // The handler uses the caches initialized below. The creator must return the // engine before DOM objects are wrapped or page scripts are evaluated. engineOptions.SetWrapObjectHandler(WrapObject); @@ -95,6 +103,7 @@ public EngineInstance(IWindow window, IDictionary assignments, I _engine = (creator is null ? new Engine(engineOptions) : creator.Invoke(window, engineOptions)) ?? throw new InvalidOperationException("The engine creator must return a Jint engine."); _regexTimeout = engineOptions.Constraints.RegexTimeout; + _constraints = engineOptions.Constraints; _libs = new LibrarySet(libs); _prototypes = new PrototypeCache(_engine, _libs); _references = new ReferenceCache(); @@ -144,6 +153,11 @@ public EngineInstance(IWindow window, IDictionary assignments, I public IEnumerable Libs => _libs.Assemblies; + /// + /// Gets the names of the WebIDL namespaces (e.g. CSS) of the libraries. + /// + public ICollection Namespaces => _namespaces ??= _libs.Assemblies.GetDomNamespaces(); + public DomNodeInstance Window => _window; /// @@ -604,9 +618,169 @@ public JsValue ToScriptValue(Exception error) return error.Data[ScriptValueKey].ToJsValue(this); } - return error is DomException exception - ? GetDomException(exception) - : _engine.Intrinsics.Error.Construct(error?.Message ?? String.Empty); + if (error is DomException exception) + { + return GetDomException(exception); + } + + // An exception of the DOM (e.g. WebAssembly.RuntimeError) is an Error of its class. + if (error != null && error.GetType().IsDomType()) + { + return GetDomNode(error); + } + + return _engine.Intrinsics.Error.Construct(error?.Message ?? String.Empty); + } + + /// + /// Gets the function of a script for a delegate, which is the same one each time; for the + /// delegate of a function of a script, that function. + /// + public JsValue GetFunction(Delegate callback) + { + if (callback.Target is ScriptCallback script && ReferenceEquals(script.Engine, this)) + { + return script.Function; + } + + return _functions.GetValue(callback, target => + { + var invoke = target.GetType().GetTypeInfo().GetDeclaredMethod("Invoke"); + var parameters = invoke.GetParameters(); + var isVariadic = ScriptCallback.IsVariadic(target.GetType()); + var function = new ClrFunction(_engine, String.Empty, (self, arguments) => InvokeDelegate(target, parameters, isVariadic, arguments), isVariadic ? 0 : parameters.Length, PropertyFlag.Configurable); + _delegates.Add(function, target); + return function; + }); + } + + /// + /// Gets the delegate a function was made for by , so a + /// script handing it back gives the library what it gave (e.g. an exported function of a + /// WebAssembly module imported by another one). + /// + public Boolean TryGetDelegate(JsValue function, out Delegate callback) + { + callback = null; + return function is ClrFunction clr && _delegates.TryGetValue(clr, out callback); + } + + private JsValue InvokeDelegate(Delegate callback, ParameterInfo[] parameters, Boolean isVariadic, JsValue[] arguments) + { + try + { + Object result; + + if (isVariadic) + { + var values = new Object[arguments.Length]; + + for (var i = 0; i < values.Length; i++) + { + values[i] = ScriptCallback.ToClr(arguments[i]); + } + + result = ScriptCallback.InvokeVariadic(callback, values); + } + else + { + var values = new Object[parameters.Length]; + + for (var i = 0; i < values.Length; i++) + { + var argument = i < arguments.Length ? arguments[i] : JsValue.Undefined; + values[i] = argument.IsUndefined() && parameters[i].ParameterType.GetTypeInfo().IsValueType + ? Activator.CreateInstance(parameters[i].ParameterType) + : argument.As(parameters[i].ParameterType, this); + } + + result = callback.DynamicInvoke(values); + } + + return result == Missing.Value ? JsValue.Undefined : result.ToJsValue(this); + } + catch (TargetInvocationException ex) + { + throw ToScriptError(ex); + } + catch (Exception ex) when (!(ex is JavaScriptException)) + { + throw new JavaScriptException(ToScriptValue(ex)); + } + } + + /// + /// Gets the ArrayBuffer sharing the bytes of the given memory (e.g. the memory of a + /// WebAssembly module), which is the same one for the same array. Memory that is only a + /// part of its array is copied, as an ArrayBuffer can only be a whole array. + /// + public JsValue GetSharedBuffer(Memory memory) + { + if (MemoryMarshal.TryGetArray(memory, out var segment) && segment.Offset == 0 && segment.Count == segment.Array.Length) + { + return _buffers.GetValue(segment.Array, array => _engine.Intrinsics.ArrayBuffer.Construct(array)); + } + + return _engine.Intrinsics.ArrayBuffer.Construct(memory.ToArray()); + } + + /// + /// Gets a task for what a script gave, which is settled by a promise as it settles. + /// + public Object ToTask(JsValue value, Type resultType) + { + var source = (ITaskSource)Activator.CreateInstance(typeof(TaskSource<>).MakeGenericType(resultType)); + var onFulfilled = new ClrFunction(_engine, String.Empty, (self, arguments) => + { + try + { + source.Resolve(arguments.Length > 0 ? arguments[0] : JsValue.Undefined, this); + } + catch (Exception ex) + { + source.Reject(ex); + } + + return JsValue.Undefined; + }); + var onRejected = new ClrFunction(_engine, String.Empty, (self, arguments) => + { + source.Reject(new JavaScriptException(arguments.Length > 0 ? arguments[0] : JsValue.Undefined)); + return JsValue.Undefined; + }); + + // a thenable settles it, anything else is the result right away + if (value is ObjectInstance thenable && thenable.Get("then") is Jint.Native.Function.Function) + { + _engine.Call(thenable.Get("then"), thenable, new JsValue[] { onFulfilled, onRejected }); + } + else + { + _engine.Call(onFulfilled, JsValue.Undefined, new[] { value }); + } + + return source.Task; + } + + private interface ITaskSource + { + Object Task { get; } + + void Resolve(JsValue value, EngineInstance engine); + + void Reject(Exception error); + } + + private sealed class TaskSource : ITaskSource + { + private readonly TaskCompletionSource _source = new TaskCompletionSource(); + + public Object Task => _source.Task; + + public void Resolve(JsValue value, EngineInstance engine) => + _source.TrySetResult(typeof(T) == typeof(Object) ? (T)ScriptCallback.ToClr(value) : (T)value.As(typeof(T), engine)); + + public void Reject(Exception error) => _source.TrySetException(error); } /// @@ -813,11 +987,33 @@ private JsValue ImportModule(String specifier, String source) } _engine.Modules.Add(specifier, source); - _engine.Modules.Import(specifier); + + // A module with a top-level await (of its own or of an import) is evaluated up to there, + // and goes on once what it awaits is settled, e.g. by a timer, which can only run once + // this is done. Jint waits for that, so it is told not to; it only wants it done now. + var timeout = _constraints.PromiseTimeout; + _constraints.PromiseTimeout = TimeSpan.FromMilliseconds(1); + + try + { + _engine.Modules.Import(specifier); + } + catch (InvalidOperationException ex) when (IsAwaitingModule(ex)) + { + } + finally + { + _constraints.PromiseTimeout = timeout; + } return JsValue.Undefined; } + // Jint has no other way to tell that the promise of evaluating the module is pending + private static Boolean IsAwaitingModule(InvalidOperationException ex) => + ex.Message.EndsWith("Pending", StringComparison.Ordinal) || + (ex.InnerException?.Message.EndsWith("Pending", StringComparison.Ordinal) ?? false); + #endregion #region Helpers @@ -861,7 +1057,34 @@ private ObjectInstance CreateInstance(Object obj) return CreateInstance(new CrossOriginWindow(window, _document), typeof(CrossOriginWindow)); } - return IsOutOfReach(obj) ? new Jint.Native.JsObject(_engine) : CreateInstance(obj, obj.GetType()); + if (IsOutOfReach(obj)) + { + return new Jint.Native.JsObject(_engine); + } + + var instance = CreateInstance(obj, obj.GetType()); + + if (obj is Exception error) + { + SetErrorProperties(instance, error); + } + + return instance; + } + + // An exception of the DOM is an Error (its prototype is one): like a native error it has + // a message and a stack, which Jint takes when it is thrown again (e.g. by an await). + private void SetErrorProperties(ObjectInstance instance, Exception error) + { + var message = error.Message ?? String.Empty; + + if (!instance.HasOwnProperty("message")) + { + instance.FastSetProperty("message", new PropertyDescriptor(message, true, false, true)); + } + + var stack = _engine.Intrinsics.Error.Construct(message).Get("stack"); + instance.FastSetProperty("stack", new PropertyDescriptor(stack.IsString() ? stack : (JsValue)String.Empty, true, false, true)); } private ObjectInstance CreateInstance(Object obj, Type type) @@ -897,9 +1120,11 @@ private ObjectInstance CreatePrototype(Type type) // the cache entry currently being built, so the fold is ruled out before the ask and the // chain stops at Object.prototype, which is where it used to stop as well. private ObjectInstance GetParentPrototype(Type type, Type baseType) => - ReferenceEquals(_prototypes.Canonicalize(baseType), type) - ? _engine.Intrinsics.Object.PrototypeObject - : GetDomPrototype(baseType); + baseType == typeof(Exception) + ? (ObjectInstance)_engine.Intrinsics.Error.Get("prototype") + : ReferenceEquals(_prototypes.Canonicalize(baseType), type) + ? _engine.Intrinsics.Object.PrototypeObject + : GetDomPrototype(baseType); /// /// Converts a value handed over from C#, which reaches Jint through JsValue.FromObject diff --git a/src/AngleSharp.Js/Extensions/DomDelegates.cs b/src/AngleSharp.Js/Extensions/DomDelegates.cs index 66cb573b..75339245 100644 --- a/src/AngleSharp.Js/Extensions/DomDelegates.cs +++ b/src/AngleSharp.Js/Extensions/DomDelegates.cs @@ -104,6 +104,16 @@ public static Function AsCallbackObject(this ObjectInstance target, Type type, E public static Delegate ToDelegate(this Type type, Function function, EngineInstance engine) { + if (engine.TryGetDelegate(function, out var given) && type.GetTypeInfo().IsAssignableFrom(given.GetType().GetTypeInfo())) + { + return given; + } + + if (type != typeof(DomEventHandler) && AngleSharp.Js.Proxies.ScriptCallback.IsVariadic(type)) + { + return AngleSharp.Js.Proxies.ScriptCallback.Create(type, function, engine); + } + if (type != typeof(DomEventHandler)) { var method = _converters.GetOrAdd(type, CreateConverter); diff --git a/src/AngleSharp.Js/Extensions/EngineExtensions.cs b/src/AngleSharp.Js/Extensions/EngineExtensions.cs index 0faacb2d..d56023b1 100644 --- a/src/AngleSharp.Js/Extensions/EngineExtensions.cs +++ b/src/AngleSharp.Js/Extensions/EngineExtensions.cs @@ -8,6 +8,7 @@ namespace AngleSharp.Js using Jint.Native; using Jint.Native.Number; using Jint.Native.Object; + using Jint.Native.Symbol; using Jint.Runtime; using Jint.Runtime.Descriptors; using Jint.Runtime.Interop; @@ -15,6 +16,7 @@ namespace AngleSharp.Js using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; + using System.Linq; using System.Reflection; using System.Threading.Tasks; @@ -105,6 +107,19 @@ public static JsValue ToJsValue(this Object obj, EngineInstance engine) { return engine.CreatePromise(task); } + else if (obj is Delegate callback) + { + // e.g. an exported function of a WebAssembly module, which scripts call + return engine.GetFunction(callback); + } + else if (obj is System.Numerics.BigInteger integer) + { + return new JsBigInt(integer); + } + else if (obj is Memory memory) + { + return engine.GetSharedBuffer(memory); + } else if (obj is IDictionary record) { // A WebIDL record (e.g., the object of a JSON response) arrives as a plain object @@ -283,14 +298,54 @@ public static void AddConstructors(this EngineInstance engine, ObjectInstance ct } } - var definitions = SelectConstructors(assembly.ExportedTypes); + // A mixin has no name of its own for scripts, and what a namespace holds is found there. + var namespaces = engine.Namespaces; + var exposed = assembly.ExportedTypes.Where(m => !m.HasNoInterfaceObject() && m.GetDomNamespace(namespaces) == null); + var definitions = SelectConstructors(exposed); foreach (var definition in definitions) { - ctx.FastSetProperty(definition.Key, CreateConstructorProperty(engine, definition.Value)); + var property = definition.Value.Type.IsDomNamespace() + ? CreateNamespaceProperty(engine, definition.Value) + : CreateConstructorProperty(engine, definition.Value); + ctx.FastSetProperty(definition.Key, property); } } + // A namespace is writable and configurable, but not enumerable, like an interface object. + private static PropertyDescriptor CreateNamespaceProperty(EngineInstance engine, ConstructorDefinition definition) => + PropertyDescriptor.CreateLazy( + new ConstructorRequest(engine, definition), + static request => request.Instance.CreateNamespace(request.Definition), + PropertyFlag.NonEnumerable); + + /// + /// Creates the object of a WebIDL namespace: its static members, its constants and the + /// interfaces exposed to it (e.g. WebAssembly.Module), but no constructor of its own. + /// + internal static ObjectInstance CreateNamespace(this EngineInstance engine, ConstructorDefinition definition) + { + var obj = new JsObject(engine.Jint); + DomConstructorInstance.AddStaticMembers(engine, obj, definition.Type.GetStaticMembers()); + + foreach (var constant in engine.Libs.GetConstants(definition.Name)) + { + obj.FastSetProperty(constant.Key, new PropertyDescriptor(JsNumber.Create(constant.Value), false, true, false)); + } + + var members = engine.Libs + .SelectMany(m => m.ExportedTypes) + .Where(m => !m.IsDomNamespace() && definition.Names.Contains(m.GetDomNamespace(engine.Namespaces))); + + foreach (var member in SelectConstructors(members)) + { + obj.FastSetProperty(member.Key, CreateConstructorProperty(engine, member.Value)); + } + + obj.FastSetProperty(GlobalSymbolRegistry.ToStringTag, new PropertyDescriptor(definition.Name, false, false, true)); + return obj; + } + private static void SetEnumLiteral(EngineInstance engine, ObjectInstance obj, EnumLiteralDefinition enumDefinition) { var target = obj.Get(enumDefinition.Name) as ObjectInstance; diff --git a/src/AngleSharp.Js/Extensions/JsValueExtensions.cs b/src/AngleSharp.Js/Extensions/JsValueExtensions.cs index 34054cfe..c9229d01 100644 --- a/src/AngleSharp.Js/Extensions/JsValueExtensions.cs +++ b/src/AngleSharp.Js/Extensions/JsValueExtensions.cs @@ -16,6 +16,7 @@ namespace AngleSharp.Js using System.Collections.Generic; using System.Globalization; using System.Reflection; + using System.Threading.Tasks; static class JsValueExtensions { @@ -130,6 +131,13 @@ private static Double Wrap(Double integer) => private static Object AsComplex(this JsValue value, Type targetType, EngineInstance engine) { + // A function standing for a delegate of the DOM is that delegate (e.g. an exported + // function of WebAssembly put into a table). + if (targetType == typeof(Object) && engine.TryGetDelegate(value, out var callback)) + { + return callback; + } + var obj = value.FromJsValue(); var sourceType = obj.GetType(); @@ -319,6 +327,12 @@ public static Object FromJsValue(this JsValue val) public static Object As(this JsValue value, Type targetType, EngineInstance engine) { + // A promise (or any value) given for a task, e.g. the fetch() a library awaits. + if (targetType == typeof(Task) || (targetType.GetTypeInfo().IsGenericType && targetType.GetGenericTypeDefinition() == typeof(Task<>))) + { + return engine.ToTask(value, targetType == typeof(Task) ? typeof(Object) : targetType.GetTypeInfo().GenericTypeArguments[0]); + } + if (value != JsValue.Null) { if (targetType == typeof(Int32)) @@ -340,6 +354,10 @@ public static Object As(this JsValue value, Type targetType, EngineInstance engi { return TypeConverter.ToNumber(value); } + else if (targetType == typeof(System.Numerics.BigInteger)) + { + return TypeConverter.ToBigInt(value); + } else if (targetType == typeof(String)) { return value.IsPrimitive() ? TypeConverter.ToString(value) : value.ToString(); diff --git a/src/AngleSharp.Js/Extensions/OverloadResolution.cs b/src/AngleSharp.Js/Extensions/OverloadResolution.cs index f49959e2..a0ad803e 100644 --- a/src/AngleSharp.Js/Extensions/OverloadResolution.cs +++ b/src/AngleSharp.Js/Extensions/OverloadResolution.cs @@ -99,6 +99,11 @@ private static Int32 Match(JsValue value, Type type) return !info.IsValueType || type != target ? 1 : 0; } + if (value.IsBigInt()) + { + return target == typeof(System.Numerics.BigInteger) ? 2 : target == typeof(Object) ? 1 : 0; + } + if (value.IsCallable()) { return info.IsSubclassOf(typeof(Delegate)) ? 2 : target == typeof(Object) ? 1 : 0; diff --git a/src/AngleSharp.Js/Extensions/ReflectionExtensions.cs b/src/AngleSharp.Js/Extensions/ReflectionExtensions.cs index 3793263a..717c5e6f 100644 --- a/src/AngleSharp.Js/Extensions/ReflectionExtensions.cs +++ b/src/AngleSharp.Js/Extensions/ReflectionExtensions.cs @@ -18,11 +18,44 @@ public static String[] GetParameterNames(this MethodInfo method) => public static Object GetDefaultValue(this Type type) => type.GetTypeInfo().IsValueType ? Activator.CreateInstance(type) : null; + // A namespace (e.g. CSS) is exposed to the window as an object of its own, so what it + // takes the window for (CSS.supports) is none of the window's members. public static IEnumerable GetExtensionTypes(this IEnumerable libs, String name) => libs .SelectMany(m => m.ExportedTypes) - .Where(m => m.GetTypeInfo().GetCustomAttributes().Any(n => n.Target.Is(name))) + .Where(m => !m.IsDomNamespace() && m.GetTypeInfo().GetCustomAttributes().Any(n => n.Target.Is(name))) .ToArray(); + /// + /// Gets if the type is a WebIDL namespace (e.g. CSS or WebAssembly): a static class with a + /// DOM name, which scripts see as a plain object holding its members, rather than a mixin + /// (a static class without an interface object, e.g. WindowBase64) adding them elsewhere. + /// + public static Boolean IsDomNamespace(this Type type) + { + var info = type.GetTypeInfo(); + return info.IsAbstract && info.IsSealed && info.IsDefined(typeof(DomNameAttribute), false) && !type.HasNoInterfaceObject(); + } + + public static Boolean HasNoInterfaceObject(this Type type) => + type.GetTypeInfo().IsDefined(typeof(DomNoInterfaceObjectAttribute), false); + + /// + /// Gets the namespace the type is exposed to (WebIDL's [LegacyNamespace], e.g. the Module + /// of WebAssembly), if one of the names it is exposed to is one of the given namespaces. + /// + public static String GetDomNamespace(this Type type, ICollection namespaces) => + namespaces.Count == 0 + ? null + : type.GetTypeInfo().GetCustomAttributes() + .Select(m => m.Target) + .FirstOrDefault(namespaces.Contains); + + public static ICollection GetDomNamespaces(this IEnumerable libs) => new HashSet(libs + .SelectMany(m => m.ExportedTypes) + .Where(IsDomNamespace) + .SelectMany(m => m.GetTypeInfo().GetCustomAttributes()) + .Select(m => m.OfficialName), StringComparer.Ordinal); + public static Type GetGenericInterface(this Type type, Type definition) { foreach (var candidate in type.GetTypeInfo().ImplementedInterfaces) diff --git a/src/AngleSharp.Js/JsHost.cs b/src/AngleSharp.Js/JsHost.cs index 2c27179b..951ea855 100644 --- a/src/AngleSharp.Js/JsHost.cs +++ b/src/AngleSharp.Js/JsHost.cs @@ -1,14 +1,17 @@ namespace AngleSharp.Js { using AngleSharp.Dom; + using Jint; using Jint.Native; + using Jint.Runtime.Interop; using Jint.Runtime; using Jint.Runtime.Modules; using System; using System.Collections.Generic; /// - /// Tells a module what the engine leaves to the host: where it comes from (import.meta.url). + /// Tells a module what the engine leaves to the host: where it comes from (import.meta.url) and + /// what it would import (import.meta.resolve). /// sealed class JsHost : Host { @@ -18,20 +21,39 @@ sealed class JsHost : Host /// public const String InlineModuleMark = "#inline-module-"; + private readonly Engine _engine; private readonly IDocument _document; + private readonly IModuleLoader _loader; - public JsHost(IDocument document) + public JsHost(Engine engine, IDocument document, IModuleLoader loader) { + _engine = engine; _document = document; + _loader = loader; } public override List> GetImportMetaProperties(Module module) { var properties = base.GetImportMetaProperties(module) ?? new List>(); properties.Add(new KeyValuePair("url", GetAddress(module.Location))); + properties.Add(new KeyValuePair("resolve", new ClrFunction(_engine, "resolve", (_, arguments) => + Resolve(module.Location, TypeConverter.ToString(arguments.At(0))), 1))); return properties; } + // the address the module would import, without importing it; a name nothing maps fails + private JsValue Resolve(String location, String specifier) + { + var resolved = _loader.Resolve(location, new ModuleRequest(specifier, Array.Empty())); + + if (resolved.Type != SpecifierType.RelativeOrAbsolute) + { + throw new JavaScriptException(_engine.Intrinsics.TypeError, $"The specifier '{specifier}' could not be resolved."); + } + + return resolved.Key; + } + private String GetAddress(String location) { var mark = location?.IndexOf(InlineModuleMark, StringComparison.Ordinal) ?? -1; diff --git a/src/AngleSharp.Js/JsModuleLoader.cs b/src/AngleSharp.Js/JsModuleLoader.cs index ab72f3b8..c5776097 100644 --- a/src/AngleSharp.Js/JsModuleLoader.cs +++ b/src/AngleSharp.Js/JsModuleLoader.cs @@ -4,18 +4,21 @@ namespace AngleSharp.Js using AngleSharp.Io; using AngleSharp.Text; using Jint; + using Jint.Native; + using Jint.Runtime; using Jint.Runtime.Modules; using System.Collections.Generic; using System.IO; using System; using System.Linq; - internal class JsModuleLoader : ModuleLoader + internal class JsModuleLoader : ModuleLoader, IModuleLoader { private readonly EngineInstance _instance; private readonly IResourceLoader _resourceLoader; private readonly IElement _scriptElement; private readonly IDocument _document; + private JavaScriptException _failure; public JsModuleLoader(EngineInstance instance, IDocument document) { @@ -70,16 +73,57 @@ public override ResolvedSpecifier Resolve(string referencingModuleLocation, Modu return new ResolvedSpecifier(moduleRequest, specifier, null, SpecifierType.Bare); } + // A CSS module script (import ... with { type: 'css' }) has the style sheet it gives as + // its default export, a constructed one, as the page adopts it like such one. Jint's own + // loading can't be overridden, so the interface is implemented anew. + Module IModuleLoader.LoadModule(Engine engine, ResolvedSpecifier resolved) + { + _failure = null; + + try + { + return LoadModule(engine, resolved); + } + catch (JavaScriptException) when (_failure != null) + { + // Jint replaces what went wrong with a string telling the module could not be loaded + throw _failure; + } + } + + private new Module LoadModule(Engine engine, ResolvedSpecifier resolved) + { + if (IsCssModule(resolved.ModuleRequest)) + { + var source = FetchModule(engine, GetModuleUrl(resolved)); + var constructor = engine.GetValue("CSSStyleSheet"); + + if (!constructor.IsConstructor()) + { + throw new JavaScriptException(engine.Intrinsics.TypeError, $"The CSS module '{resolved.Key}' needs style sheets to be constructed."); + } + + var sheet = engine.Construct(constructor); + engine.Invoke(sheet.Get("replaceSync"), sheet, new Object[] { source }); + return ModuleFactory.BuildJsonModule(engine, sheet, resolved.Key); + } + + return base.LoadModule(engine, resolved); + } + + private static Boolean IsCssModule(ModuleRequest request) => + request.Attributes?.Any(attribute => attribute.Key == "type" && attribute.Value == "css") ?? false; + // Every module comes through AngleSharp's resource loader, whatever its scheme, so the // requesters the host registered decide what a page can reach. protected override string LoadModuleContents(Engine engine, ResolvedSpecifier resolved) { - return FetchModule(GetModuleUrl(resolved)); + return FetchModule(engine, GetModuleUrl(resolved)); } protected override Byte[] LoadModuleContentsAsBytes(Engine engine, ResolvedSpecifier resolved) { - return FetchModuleBytes(GetModuleUrl(resolved)); + return FetchModuleBytes(engine, GetModuleUrl(resolved)); } // A key of the map is either the whole specifier, or, ending with a slash, a prefix of it, @@ -149,14 +193,14 @@ private static Url GetModuleUrl(ResolvedSpecifier resolved) return new Url(resolved.Key); } - private string FetchModule(Url moduleUrl) + private string FetchModule(Engine engine, Url moduleUrl) { if (_resourceLoader == null) { return string.Empty; } - var response = Fetch(moduleUrl); + var response = Fetch(engine, moduleUrl); string content; @@ -168,14 +212,14 @@ private string FetchModule(Url moduleUrl) return content; } - private Byte[] FetchModuleBytes(Url moduleUrl) + private Byte[] FetchModuleBytes(Engine engine, Url moduleUrl) { if (_resourceLoader == null) { return Array.Empty(); } - var response = Fetch(moduleUrl); + var response = Fetch(engine, moduleUrl); using (var content = new MemoryStream()) { @@ -184,11 +228,21 @@ private Byte[] FetchModuleBytes(Url moduleUrl) } } - private IResponse Fetch(Url moduleUrl) + // A module that could not be fetched, or was answered with an error (e.g. a page telling it + // was not found), is a TypeError, which is what an import() of it rejects with. + private IResponse Fetch(Engine engine, Url moduleUrl) { var request = new ResourceRequest(_scriptElement, moduleUrl); var response = _resourceLoader.FetchAsync(request).Task.GetAwaiter().GetResult(); - return response ?? throw new InvalidOperationException($"No requester could load the module '{moduleUrl.Href}'."); + + if (response == null || (Int32)response.StatusCode < 200 || (Int32)response.StatusCode > 299) + { + response?.Dispose(); + _failure = new JavaScriptException(engine.Intrinsics.TypeError, $"Failed to fetch the module '{moduleUrl.Href}'."); + throw _failure; + } + + return response; } } } diff --git a/src/AngleSharp.Js/JsScriptingService.cs b/src/AngleSharp.Js/JsScriptingService.cs index 90dac27d..eb83f4d0 100644 --- a/src/AngleSharp.Js/JsScriptingService.cs +++ b/src/AngleSharp.Js/JsScriptingService.cs @@ -237,10 +237,36 @@ internal EngineInstance GetOrCreateInstance(IDocument document) private static IEnumerable GetAssemblies(IBrowsingContext context) => context .GetServices() - .Select(m => m.GetType().GetAssembly()) + .SelectMany(GetAssemblies) .Distinct() .Where(m => m.FullName.StartsWith("AngleSharp")); + // A service registered by a creator (e.g. WithWasm's runtime factory) is only created when + // first asked for, so until then it is the delegate, a type of the framework: the library + // is the one of the type it creates and of its code. + private static IEnumerable GetAssemblies(Object service) + { + yield return service.GetType().GetAssembly(); + + if (service is Delegate creator) + { + var type = creator.GetType(); + + if (type.GetTypeInfo().IsGenericType) + { + foreach (var argument in type.GetTypeInfo().GenericTypeArguments) + { + yield return argument.GetAssembly(); + } + } + + if (creator.GetMethodInfo()?.DeclaringType is Type declaring) + { + yield return declaring.GetAssembly(); + } + } + } + #endregion } } diff --git a/src/AngleSharp.Js/Proxies/DomConstructorInstance.cs b/src/AngleSharp.Js/Proxies/DomConstructorInstance.cs index 3b5201bd..acd6e7c6 100644 --- a/src/AngleSharp.Js/Proxies/DomConstructorInstance.cs +++ b/src/AngleSharp.Js/Proxies/DomConstructorInstance.cs @@ -55,8 +55,15 @@ private void AddConstants(IEnumerable> constants) } } - private void AddStaticMembers(StaticMember[] members) + private void AddStaticMembers(StaticMember[] members) => AddStaticMembers(_instance, this, members); + + /// + /// Adds the static members of a type to its constructor, or to the object of a namespace. + /// + public static void AddStaticMembers(EngineInstance instance, ObjectInstance target, StaticMember[] members) { + var engine = instance.Jint; + foreach (var member in members) { var name = member.Name; @@ -65,15 +72,15 @@ private void AddStaticMembers(StaticMember[] members) { var getter = member.Getter; var setter = member.Setter; - var get = getter == null ? null : new ClrFunction(Engine, "get " + name, (_, arguments) => _instance.CallStatic(getter, arguments)); - var set = setter == null ? null : new ClrFunction(Engine, "set " + name, (_, arguments) => _instance.CallStatic(setter, arguments)); - SetOwnProperty(name, new GetSetPropertyDescriptor(get, set, true, true)); + var get = getter == null ? null : new ClrFunction(engine, "get " + name, (_, arguments) => instance.CallStatic(getter, arguments)); + var set = setter == null ? null : new ClrFunction(engine, "set " + name, (_, arguments) => instance.CallStatic(setter, arguments)); + target.FastSetProperty(name, new GetSetPropertyDescriptor(get, set, true, true)); } else { var overloads = member.Overloads; - var function = new ClrFunction(Engine, name, (_, arguments) => _instance.CallStatic(overloads.SelectOverload(arguments), arguments)); - SetOwnProperty(name, new PropertyDescriptor(function, true, true, true)); + var function = new ClrFunction(engine, name, (_, arguments) => instance.CallStatic(overloads.SelectOverload(arguments), arguments)); + target.FastSetProperty(name, new PropertyDescriptor(function, true, true, true)); } } } diff --git a/src/AngleSharp.Js/Proxies/ScriptCallback.cs b/src/AngleSharp.Js/Proxies/ScriptCallback.cs new file mode 100644 index 00000000..1513ac1d --- /dev/null +++ b/src/AngleSharp.Js/Proxies/ScriptCallback.cs @@ -0,0 +1,105 @@ +namespace AngleSharp.Js.Proxies +{ + using Jint; + using Jint.Native; + using Jint.Native.Function; + using System; + using System.Collections.Generic; + using System.Linq; + using System.Linq.Expressions; + using System.Reflection; + + /// + /// A function of a script behind a variadic delegate, i.e. one taking all of its arguments + /// as a list (e.g. the host functions a WebAssembly module imports), which the library calls + /// with any number of them. An argument is converted as for any member of the DOM; an + /// undefined (the result too) is . + /// + sealed class ScriptCallback + { + private static readonly MethodInfo InvokeMethod = typeof(ScriptCallback).GetTypeInfo().GetDeclaredMethod(nameof(Invoke)); + private static readonly MethodInfo InvokeVoidMethod = typeof(ScriptCallback).GetTypeInfo().GetDeclaredMethod(nameof(InvokeVoid)); + + private ScriptCallback(Function function, EngineInstance engine) + { + Function = function; + Engine = engine; + } + + public Function Function { get; } + + public EngineInstance Engine { get; } + + /// + /// Gets if the delegate type takes its arguments as a list: its one parameter is an + /// Object[] (or a read-only list of objects), and it gives an object or nothing. + /// + public static Boolean IsVariadic(Type type) + { + var invoke = type.GetTypeInfo().GetDeclaredMethod("Invoke"); + var parameters = invoke?.GetParameters(); + + return parameters != null && parameters.Length == 1 && + (parameters[0].ParameterType == typeof(Object[]) || parameters[0].ParameterType == typeof(IReadOnlyList)) && + (invoke.ReturnType == typeof(Object) || invoke.ReturnType == typeof(void)); + } + + public static Delegate Create(Type type, Function function, EngineInstance engine) + { + var invoke = type.GetTypeInfo().GetDeclaredMethod("Invoke"); + var target = new ScriptCallback(function, engine); + return InvokeMethod.ReturnType == invoke.ReturnType + ? InvokeMethod.CreateDelegate(type, target) + : InvokeVoidMethod.CreateDelegate(type, target); + } + + private Object Invoke(IReadOnlyList arguments) + { + var values = new JsValue[arguments?.Count ?? 0]; + + for (var i = 0; i < values.Length; i++) + { + values[i] = arguments[i] == Missing.Value ? JsValue.Undefined : arguments[i].ToJsValue(Engine); + } + + Engine.EnterScript(); + + try + { + return ToClr(Engine.Jint.Call(Function, JsValue.Undefined, values)); + } + finally + { + Engine.LeaveScript(); + } + } + + private void InvokeVoid(IReadOnlyList arguments) => Invoke(arguments); + + /// + /// Converts what a script gave to what a variadic delegate takes or gives. + /// + public static Object ToClr(JsValue value) => value.IsUndefined() ? Missing.Value : value.FromJsValue(); + + /// + /// Calls a variadic delegate with the given arguments; compiled once per delegate type. + /// + public static Object InvokeVariadic(Delegate callback, Object[] arguments) => + Invokers.GetOrAdd(callback.GetType(), CreateInvoker)(callback, arguments); + + private static readonly System.Collections.Concurrent.ConcurrentDictionary> Invokers = + new System.Collections.Concurrent.ConcurrentDictionary>(); + + private static Func CreateInvoker(Type type) + { + var invoke = type.GetTypeInfo().GetDeclaredMethod("Invoke"); + var callback = Expression.Parameter(typeof(Delegate), "callback"); + var arguments = Expression.Parameter(typeof(Object[]), "arguments"); + var call = Expression.Call(Expression.Convert(callback, type), invoke, Expression.Convert(arguments, invoke.GetParameters()[0].ParameterType)); + var body = invoke.ReturnType == typeof(void) + ? (Expression)Expression.Block(call, Expression.Constant(null, typeof(Object))) + : Expression.Convert(call, typeof(Object)); + return Expression.Lambda>(body, callback, arguments).Compile(); + } + } +} From a29a0c939f21f1ba97c90168feda60e7d0756f78 Mon Sep 17 00:00:00 2001 From: Florian Rappl Date: Mon, 23 Nov 2026 08:54:02 +0100 Subject: [PATCH 07/19] Fixes for .NET 4.6.2 --- src/AngleSharp.Js/Dom/CryptoKey.cs | 2 +- src/AngleSharp.Js/Dom/EcKeyParameters.cs | 224 ++++++++++++++++++++ src/AngleSharp.Js/Dom/WebCrypto.cs | 258 ++++++++++++----------- 3 files changed, 355 insertions(+), 129 deletions(-) create mode 100644 src/AngleSharp.Js/Dom/EcKeyParameters.cs diff --git a/src/AngleSharp.Js/Dom/CryptoKey.cs b/src/AngleSharp.Js/Dom/CryptoKey.cs index 2ee25742..a5e3908f 100644 --- a/src/AngleSharp.Js/Dom/CryptoKey.cs +++ b/src/AngleSharp.Js/Dom/CryptoKey.cs @@ -60,7 +60,7 @@ internal CryptoKey(String type, Boolean extractable, IDictionary internal RSAParameters? Rsa { get; set; } - internal ECParameters? Ec { get; set; } + internal EcKeyParameters? Ec { get; set; } internal Boolean Allows(String usage) => Array.IndexOf(_usages, usage) >= 0; } diff --git a/src/AngleSharp.Js/Dom/EcKeyParameters.cs b/src/AngleSharp.Js/Dom/EcKeyParameters.cs new file mode 100644 index 00000000..c026d3b8 --- /dev/null +++ b/src/AngleSharp.Js/Dom/EcKeyParameters.cs @@ -0,0 +1,224 @@ +namespace AngleSharp.Js.Dom +{ + using System; + using System.Security.Cryptography; + + /// + /// The material of an elliptic curve key on one of the named curves of the Web Cryptography + /// API. It stands in for ECParameters, which .NET Framework 4.6.2 does not have: there the + /// key reaches the platform as a CNG key blob instead. + /// + readonly struct EcKeyParameters + { + public EcKeyParameters(String curve, Byte[] x, Byte[] y, Byte[] d) + { + Curve = curve; + X = x; + Y = y; + D = d; + } + + /// + /// Gets the name of the curve, i.e., "P-256", "P-384" or "P-521". + /// + public String Curve { get; } + + public Byte[] X { get; } + + public Byte[] Y { get; } + + /// + /// Gets the private key, which is null for a public key. + /// + public Byte[] D { get; } + + public Boolean IsPrivate => D != null; + + public EcKeyParameters PublicPart => new EcKeyParameters(Curve, X, Y, null); + + public static Int32 CoordinateLength(String curve) => + curve == "P-256" ? 32 : curve == "P-384" ? 48 : 66; + + /// + /// Creates a new key pair on the given curve. + /// + public static EcKeyParameters Generate(String curve) + { +#if NET462 + var creation = new CngKeyCreationParameters { ExportPolicy = CngExportPolicies.AllowPlaintextExport }; + + using (var key = CngKey.Create(GetCngAlgorithm(curve), null, creation)) + { + return FromBlob(curve, key.Export(CngKeyBlobFormat.EccPrivateBlob)); + } +#else + using (var ecdsa = ECDsa.Create(GetNamedCurve(curve))) + { + return From(ecdsa.ExportParameters(true)).Value; + } +#endif + } + + /// + /// Creates the platform's ECDSA for the key, which also checks the key (e.g. that the + /// point is on the curve) by throwing a CryptographicException. + /// + public ECDsa CreateEcdsa() + { +#if NET462 + var format = IsPrivate ? CngKeyBlobFormat.EccPrivateBlob : CngKeyBlobFormat.EccPublicBlob; + return new ECDsaCng(CngKey.Import(ToBlob(), format)); +#else + return ECDsa.Create(ToParameters()); +#endif + } + +#if NET462 + // BCRYPT_ECCKEY_BLOB: the magic and the length of a coordinate (each a little endian + // UInt32), followed by X, Y and - for a private key - D, each of that length. + private const Int32 BlobHeaderLength = 8; + + private Byte[] ToBlob() + { + var size = CoordinateLength(Curve); + var count = IsPrivate ? 3 : 2; + var blob = new Byte[BlobHeaderLength + count * size]; + WriteUInt32(blob, 0, GetMagic(Curve, IsPrivate)); + WriteUInt32(blob, 4, (UInt32)size); + CopyPadded(X, blob, BlobHeaderLength, size); + CopyPadded(Y, blob, BlobHeaderLength + size, size); + + if (IsPrivate) + { + CopyPadded(D, blob, BlobHeaderLength + 2 * size, size); + } + + return blob; + } + + private static EcKeyParameters FromBlob(String curve, Byte[] blob) + { + var size = (Int32)(blob[4] | blob[5] << 8 | blob[6] << 16 | blob[7] << 24); + var hasD = blob.Length >= BlobHeaderLength + 3 * size; + var x = Slice(blob, BlobHeaderLength, size); + var y = Slice(blob, BlobHeaderLength + size, size); + var d = hasD ? Slice(blob, BlobHeaderLength + 2 * size, size) : null; + return new EcKeyParameters(curve, x, y, d); + } + + // The ECDSA magics ("ECS1" to "ECS6"): an ECDH key only ever reaches the platform to be + // checked here, which the ECDSA algorithm of the same curve does just as well. + private static UInt32 GetMagic(String curve, Boolean isPrivate) + { + var index = curve == "P-256" ? 1u : curve == "P-384" ? 3u : 5u; + return 0x30534345u + index + (isPrivate ? 1u : 0u); + } + + private static CngAlgorithm GetCngAlgorithm(String curve) + { + switch (curve) + { + case "P-256": + return CngAlgorithm.ECDsaP256; + case "P-384": + return CngAlgorithm.ECDsaP384; + default: + return CngAlgorithm.ECDsaP521; + } + } + + private static void WriteUInt32(Byte[] target, Int32 offset, UInt32 value) + { + target[offset] = (Byte)value; + target[offset + 1] = (Byte)(value >> 8); + target[offset + 2] = (Byte)(value >> 16); + target[offset + 3] = (Byte)(value >> 24); + } + + // Right-aligned, as the coordinates are big endian numbers. + private static void CopyPadded(Byte[] value, Byte[] target, Int32 offset, Int32 size) + { + var start = 0; + + while (value.Length - start > size && value[start] == 0) + { + start++; + } + + var length = value.Length - start; + + if (length > size) + { + throw new CryptographicException(); + } + + Buffer.BlockCopy(value, start, target, offset + size - length, length); + } + + private static Byte[] Slice(Byte[] value, Int32 offset, Int32 length) + { + var result = new Byte[length]; + Buffer.BlockCopy(value, offset, result, 0, length); + return result; + } +#else + public ECParameters ToParameters() => new ECParameters + { + Curve = GetNamedCurve(Curve), + Q = new ECPoint { X = X, Y = Y }, + D = D, + }; + + /// + /// Gets the key of the given parameters, or null if they are not on one of the named + /// curves of the Web Cryptography API. + /// + public static EcKeyParameters? From(ECParameters parameters) + { + var curve = GetCurveName(parameters.Curve); + return curve != null ? new EcKeyParameters(curve, parameters.Q.X, parameters.Q.Y, parameters.D) : (EcKeyParameters?)null; + } + + private static ECCurve GetNamedCurve(String curve) + { + switch (curve) + { + case "P-256": + return ECCurve.NamedCurves.nistP256; + case "P-384": + return ECCurve.NamedCurves.nistP384; + default: + return ECCurve.NamedCurves.nistP521; + } + } + + private static String GetCurveName(ECCurve curve) + { + switch (curve.Oid?.Value) + { + case "1.2.840.10045.3.1.7": + return "P-256"; + case "1.3.132.0.34": + return "P-384"; + case "1.3.132.0.35": + return "P-521"; + } + + switch (curve.Oid?.FriendlyName) + { + case "nistP256": + case "ECDSA_P256": + return "P-256"; + case "nistP384": + case "ECDSA_P384": + return "P-384"; + case "nistP521": + case "ECDSA_P521": + return "P-521"; + } + + return null; + } +#endif + } +} diff --git a/src/AngleSharp.Js/Dom/WebCrypto.cs b/src/AngleSharp.Js/Dom/WebCrypto.cs index 40cbf0e4..54ca670e 100644 --- a/src/AngleSharp.Js/Dom/WebCrypto.cs +++ b/src/AngleSharp.Js/Dom/WebCrypto.cs @@ -87,7 +87,7 @@ public static Byte[] Sign(Object algorithm, CryptoKey key, Byte[] data) case "HMAC": return Hmac(key.Hash, key.Secret, data); case "ECDSA": - using (var ecdsa = ECDsa.Create(key.Ec.Value)) + using (var ecdsa = key.Ec.Value.CreateEcdsa()) { return ecdsa.SignData(data, HashName(normalized.GetHash())); } @@ -111,10 +111,10 @@ public static Boolean Verify(Object algorithm, CryptoKey key, Byte[] signature, case "HMAC": return AreEqual(Hmac(key.Hash, key.Secret, data), signature); case "ECDSA": - using (var ecdsa = ECDsa.Create(key.Ec.Value)) + using (var ecdsa = key.Ec.Value.CreateEcdsa()) { // the signature is r and s, each as long as a coordinate (IEEE P1363) - return signature.Length == 2 * CoordinateLength(key.Curve) && + return signature.Length == 2 * EcKeyParameters.CoordinateLength(key.Curve) && ecdsa.VerifyData(data, signature, HashName(normalized.GetHash())); } default: @@ -173,21 +173,15 @@ public static Object GenerateKey(Object algorithm, Boolean extractable, String[] var isEcdsa = normalized.Name == "ECDSA"; CheckUsages(usages, isEcdsa ? new[] { Sign_, Verify_ } : new[] { DeriveKey_, DeriveBits_ }); var curve = GetCurve(normalized); - ECParameters parameters; - - using (var ecdsa = ECDsa.Create(GetNamedCurve(curve))) - { - parameters = ecdsa.ExportParameters(true); - } - - var publicKey = CreateEcKey(normalized.Name, curve, PublicPart(parameters), true, Intersect(usages, isEcdsa ? new[] { Verify_ } : new String[0])); - var privateKey = CreateEcKey(normalized.Name, curve, parameters, extractable, Intersect(usages, isEcdsa ? new[] { Sign_ } : new[] { DeriveKey_, DeriveBits_ })); + var parameters = EcKeyParameters.Generate(curve); + var publicKey = CreateEcKey(normalized.Name, parameters.PublicPart, true, Intersect(usages, isEcdsa ? new[] { Verify_ } : new String[0])); + var privateKey = CreateEcKey(normalized.Name, parameters, extractable, Intersect(usages, isEcdsa ? new[] { Sign_ } : new[] { DeriveKey_, DeriveBits_ })); return CreateKeyPair(publicKey, RequireUsages(privateKey)); } default: { - var (publicUsages, privateUsages) = GetRsaUsages(normalized.Name); - CheckUsages(usages, publicUsages.Concat(privateUsages).ToArray()); + var rsaUsages = GetRsaUsages(normalized.Name); + CheckUsages(usages, rsaUsages.Public.Concat(rsaUsages.Private).ToArray()); var bits = normalized.GetInteger("modulusLength") ?? throw TypeError("The modulusLength is missing."); var exponent = normalized.GetBytes("publicExponent"); var hash = normalized.GetHash(); @@ -213,8 +207,8 @@ public static Object GenerateKey(Object algorithm, Boolean extractable, String[] throw OperationError(); } - var publicKey = CreateRsaKey(normalized.Name, hash, PublicPart(parameters), true, Intersect(usages, publicUsages)); - var privateKey = CreateRsaKey(normalized.Name, hash, parameters, extractable, Intersect(usages, privateUsages)); + var publicKey = CreateRsaKey(normalized.Name, hash, PublicPart(parameters), true, Intersect(usages, rsaUsages.Public)); + var privateKey = CreateRsaKey(normalized.Name, hash, parameters, extractable, Intersect(usages, rsaUsages.Private)); return CreateKeyPair(publicKey, RequireUsages(privateKey)); } } @@ -291,9 +285,9 @@ public static Object ExportKey(String format, CryptoKey key) { return (Byte[])key.Secret.Clone(); } - else if (key.Ec is ECParameters ec && key.Type == "public") + else if (key.Ec is EcKeyParameters ec && key.Type == "public") { - return EncodePoint(ec, key.Curve); + return EncodePoint(ec); } throw InvalidAccessError(); @@ -499,12 +493,12 @@ private static void IncrementCounter(Byte[] block, Int32 bits) private static Byte[] AesGcmEncrypt(Algorithm algorithm, Byte[] key, Byte[] data) { #if NET8_0_OR_GREATER - var (iv, additionalData, tagLength) = GetAesGcmParameters(algorithm); - var result = new Byte[data.Length + tagLength]; + var parameters = GetAesGcmParameters(algorithm); + var result = new Byte[data.Length + parameters.TagLength]; - using (var gcm = new AesGcm(key, tagLength)) + using (var gcm = new AesGcm(key, parameters.TagLength)) { - gcm.Encrypt(iv, data, result.AsSpan(0, data.Length), result.AsSpan(data.Length), additionalData); + gcm.Encrypt(parameters.Iv, data, result.AsSpan(0, data.Length), result.AsSpan(data.Length), parameters.AdditionalData); } return result; @@ -516,18 +510,18 @@ private static Byte[] AesGcmEncrypt(Algorithm algorithm, Byte[] key, Byte[] data private static Byte[] AesGcmDecrypt(Algorithm algorithm, Byte[] key, Byte[] data) { #if NET8_0_OR_GREATER - var (iv, additionalData, tagLength) = GetAesGcmParameters(algorithm); + var parameters = GetAesGcmParameters(algorithm); - if (data.Length < tagLength) + if (data.Length < parameters.TagLength) { throw OperationError(); } - var result = new Byte[data.Length - tagLength]; + var result = new Byte[data.Length - parameters.TagLength]; - using (var gcm = new AesGcm(key, tagLength)) + using (var gcm = new AesGcm(key, parameters.TagLength)) { - gcm.Decrypt(iv, data.AsSpan(0, result.Length), data.AsSpan(result.Length), result, additionalData); + gcm.Decrypt(parameters.Iv, data.AsSpan(0, result.Length), data.AsSpan(result.Length), result, parameters.AdditionalData); } return result; @@ -536,7 +530,7 @@ private static Byte[] AesGcmDecrypt(Algorithm algorithm, Byte[] key, Byte[] data #endif } - private static (Byte[] Iv, Byte[] AdditionalData, Int32 TagLength) GetAesGcmParameters(Algorithm algorithm) + private static AesGcmParameters GetAesGcmParameters(Algorithm algorithm) { var iv = algorithm.GetBytes("iv"); var additionalData = algorithm.GetBytes("additionalData", false); @@ -553,7 +547,7 @@ private static (Byte[] Iv, Byte[] AdditionalData, Int32 TagLength) GetAesGcmPara throw NotSupportedError(); } - return (iv, additionalData, tagLength / 8); + return new AesGcmParameters(iv, additionalData, tagLength / 8); } private static readonly Byte[] KeyWrapIv = { 0xA6, 0xA6, 0xA6, 0xA6, 0xA6, 0xA6, 0xA6, 0xA6 }; @@ -706,8 +700,8 @@ private static Byte[] DeriveBitsCore(Algorithm algorithm, CryptoKey key, Int32? private static Byte[] EcdhSecret(CryptoKey privateKey, CryptoKey publicKey) { #if NET8_0_OR_GREATER - using (var mine = ECDiffieHellman.Create(privateKey.Ec.Value)) - using (var theirs = ECDiffieHellman.Create(publicKey.Ec.Value)) + using (var mine = ECDiffieHellman.Create(privateKey.Ec.Value.ToParameters())) + using (var theirs = ECDiffieHellman.Create(publicKey.Ec.Value.ToParameters())) { return mine.DeriveRawSecretAgreement(theirs.PublicKey); } @@ -744,19 +738,18 @@ private static Byte[] Pbkdf2(String hash, Byte[] password, Byte[] salt, Int32 it var result = new Byte[length]; var hashLength = HashLength(hash); - using (var hmac = IncrementalHash.CreateHMAC(HashName(hash), password)) + using (var hmac = CreateHmac(hash, password)) { for (var block = 1; (block - 1) * hashLength < length; block++) { - hmac.AppendData(salt); - hmac.AppendData(new[] { (Byte)(block >> 24), (Byte)(block >> 16), (Byte)(block >> 8), (Byte)block }); - var u = hmac.GetHashAndReset(); + hmac.TransformBlock(salt, 0, salt.Length, null, 0); + hmac.TransformFinalBlock(new[] { (Byte)(block >> 24), (Byte)(block >> 16), (Byte)(block >> 8), (Byte)block }, 0, 4); + var u = hmac.Hash; var t = (Byte[])u.Clone(); for (var i = 1; i < iterations; i++) { - hmac.AppendData(u); - u = hmac.GetHashAndReset(); + u = hmac.ComputeHash(u); for (var k = 0; k < t.Length; k++) { @@ -781,7 +774,7 @@ private static Byte[] Hkdf(String hash, Byte[] secret, Byte[] salt, Byte[] info, var result = new Byte[length]; var previous = new Byte[0]; - for (var (i, offset) = (1, 0); offset < length; i++, offset += hashLength) + for (Int32 i = 1, offset = 0; offset < length; i++, offset += hashLength) { var input = new Byte[previous.Length + info.Length + 1]; Buffer.BlockCopy(previous, 0, input, 0, previous.Length); @@ -854,8 +847,8 @@ private static CryptoKey ImportEcKey(String format, Byte[] data, Jwk jwk, Algori { var isEcdsa = algorithm.Name == "ECDSA"; var curve = GetCurve(algorithm); - var size = CoordinateLength(curve); - ECParameters parameters; + var size = EcKeyParameters.CoordinateLength(curve); + EcKeyParameters parameters; switch (format) { @@ -865,11 +858,7 @@ private static CryptoKey ImportEcKey(String format, Byte[] data, Jwk jwk, Algori throw DataError(); } - parameters = new ECParameters - { - Curve = GetNamedCurve(curve), - Q = new ECPoint { X = Slice(data, 1, size), Y = Slice(data, 1 + size, size) }, - }; + parameters = new EcKeyParameters(curve, Slice(data, 1, size), Slice(data, 1 + size, size), null); break; case "jwk": jwk.CheckType("EC"); @@ -885,12 +874,8 @@ private static CryptoKey ImportEcKey(String format, Byte[] data, Jwk jwk, Algori jwk.CheckAlgorithm(curve == "P-521" ? "ES512" : "ES" + curve.Substring(2)); } - parameters = new ECParameters - { - Curve = GetNamedCurve(curve), - Q = new ECPoint { X = jwk.GetBytes("x", size), Y = jwk.GetBytes("y", size) }, - D = jwk.Get("d") != null ? jwk.GetBytes("d", size) : null, - }; + var d = jwk.Get("d") != null ? jwk.GetBytes("d", size) : null; + parameters = new EcKeyParameters(curve, jwk.GetBytes("x", size), jwk.GetBytes("y", size), d); break; default: parameters = ImportEcDer(format, data, curve); @@ -899,7 +884,7 @@ private static CryptoKey ImportEcKey(String format, Byte[] data, Jwk jwk, Algori try { - using (var ecdsa = ECDsa.Create(parameters)) + using (var ecdsa = parameters.CreateEcdsa()) { // validated by the platform, e.g. that the point is on the curve } @@ -909,7 +894,7 @@ private static CryptoKey ImportEcKey(String format, Byte[] data, Jwk jwk, Algori throw DataError(); } - var isPrivate = parameters.D != null; + var isPrivate = parameters.IsPrivate; if (isPrivate) { @@ -920,10 +905,10 @@ private static CryptoKey ImportEcKey(String format, Byte[] data, Jwk jwk, Algori CheckUsages(usages, isEcdsa ? new[] { Verify_ } : new String[0]); } - return CreateEcKey(algorithm.Name, curve, parameters, extractable, usages); + return CreateEcKey(algorithm.Name, parameters, extractable, usages); } - private static ECParameters ImportEcDer(String format, Byte[] data, String curve) + private static EcKeyParameters ImportEcDer(String format, Byte[] data, String curve) { #if NET8_0_OR_GREATER try @@ -939,8 +924,8 @@ private static ECParameters ImportEcDer(String format, Byte[] data, String curve ecdsa.ImportPkcs8PrivateKey(data, out _); } - var parameters = ecdsa.ExportParameters(format == "pkcs8"); - return GetCurveName(parameters.Curve) == curve ? parameters : throw DataError(); + var parameters = EcKeyParameters.From(ecdsa.ExportParameters(format == "pkcs8")); + return parameters?.Curve == curve ? parameters.Value : throw DataError(); } } catch (CryptographicException) @@ -955,7 +940,7 @@ private static ECParameters ImportEcDer(String format, Byte[] data, String curve private static CryptoKey ImportRsaKey(String format, Byte[] data, Jwk jwk, Algorithm algorithm, Boolean extractable, String[] usages) { var hash = algorithm.GetHash(); - var (publicUsages, privateUsages) = GetRsaUsages(algorithm.Name); + var rsaUsages = GetRsaUsages(algorithm.Name); RSAParameters parameters; switch (format) @@ -1008,7 +993,7 @@ private static CryptoKey ImportRsaKey(String format, Byte[] data, Jwk jwk, Algor throw DataError(); } - CheckUsages(usages, parameters.D != null ? privateUsages : publicUsages); + CheckUsages(usages, parameters.D != null ? rsaUsages.Private : rsaUsages.Public); return CreateRsaKey(algorithm.Name, hash, parameters, extractable, usages); } @@ -1067,11 +1052,11 @@ private static IDictionary ExportJwk(CryptoKey key) case "ECDH": { var ec = key.Ec.Value; - var size = CoordinateLength(key.Curve); + var size = EcKeyParameters.CoordinateLength(key.Curve); jwk["kty"] = "EC"; jwk["crv"] = key.Curve; - jwk["x"] = ToBase64Url(Pad(ec.Q.X, size)); - jwk["y"] = ToBase64Url(Pad(ec.Q.Y, size)); + jwk["x"] = ToBase64Url(Pad(ec.X, size)); + jwk["y"] = ToBase64Url(Pad(ec.Y, size)); if (key.Type == "private") { @@ -1121,9 +1106,9 @@ private static Byte[] ExportDer(String format, CryptoKey key) } #if NET8_0_OR_GREATER - if (key.Ec is ECParameters ec) + if (key.Ec is EcKeyParameters ec) { - using (var ecdsa = ECDsa.Create(ec)) + using (var ecdsa = ec.CreateEcdsa()) { return isPublic ? ecdsa.ExportSubjectPublicKeyInfo() : ecdsa.ExportPkcs8PrivateKey(); } @@ -1163,12 +1148,12 @@ private static CryptoKey CreateAesKey(String name, Byte[] data, Boolean extracta return new CryptoKey("secret", extractable, algorithm, usages) { Secret = data }; } - private static CryptoKey CreateEcKey(String name, String curve, ECParameters parameters, Boolean extractable, String[] usages) + private static CryptoKey CreateEcKey(String name, EcKeyParameters parameters, Boolean extractable, String[] usages) { var algorithm = CreateAlgorithm(name); - algorithm["namedCurve"] = curve; - var type = parameters.D != null ? "private" : "public"; - return new CryptoKey(type, extractable, algorithm, usages) { Ec = parameters, Curve = curve }; + algorithm["namedCurve"] = parameters.Curve; + var type = parameters.IsPrivate ? "private" : "public"; + return new CryptoKey(type, extractable, algorithm, usages) { Ec = parameters, Curve = parameters.Curve }; } private static CryptoKey CreateRsaKey(String name, String hash, RSAParameters parameters, Boolean extractable, String[] usages) @@ -1191,9 +1176,6 @@ private static IDictionary CreateKeyPair(CryptoKey publicKey, Cr private static Dictionary CreateAlgorithm(String name) => new Dictionary { ["name"] = name }; - private static ECParameters PublicPart(ECParameters parameters) => - new ECParameters { Curve = parameters.Curve, Q = parameters.Q }; - private static RSAParameters PublicPart(RSAParameters parameters) => new RSAParameters { Modulus = parameters.Modulus, Exponent = parameters.Exponent }; @@ -1254,10 +1236,10 @@ private static String GetRsaJwkAlgorithm(String name, String hash) } } - private static (String[] Public, String[] Private) GetRsaUsages(String name) => + private static KeyPairUsages GetRsaUsages(String name) => name == "RSA-OAEP" - ? (new[] { Encrypt_, WrapKey_ }, new[] { Decrypt_, UnwrapKey_ }) - : (new[] { Verify_ }, new[] { Sign_ }); + ? new KeyPairUsages(new[] { Encrypt_, WrapKey_ }, new[] { Decrypt_, UnwrapKey_ }) + : new KeyPairUsages(new[] { Verify_ }, new[] { Sign_ }); private static String[] GetAesUsages(String name) => name == "AES-KW" ? new[] { WrapKey_, UnwrapKey_ } : new[] { Encrypt_, Decrypt_, WrapKey_, UnwrapKey_ }; @@ -1275,57 +1257,13 @@ private static String GetCurve(Algorithm algorithm) return curve == "P-256" || curve == "P-384" || curve == "P-521" ? curve : throw NotSupportedError(); } - private static ECCurve GetNamedCurve(String curve) - { - switch (curve) - { - case "P-256": - return ECCurve.NamedCurves.nistP256; - case "P-384": - return ECCurve.NamedCurves.nistP384; - default: - return ECCurve.NamedCurves.nistP521; - } - } - - private static String GetCurveName(ECCurve curve) + private static Byte[] EncodePoint(EcKeyParameters parameters) { - switch (curve.Oid?.Value) - { - case "1.2.840.10045.3.1.7": - return "P-256"; - case "1.3.132.0.34": - return "P-384"; - case "1.3.132.0.35": - return "P-521"; - } - - switch (curve.Oid?.FriendlyName) - { - case "nistP256": - case "ECDSA_P256": - return "P-256"; - case "nistP384": - case "ECDSA_P384": - return "P-384"; - case "nistP521": - case "ECDSA_P521": - return "P-521"; - } - - return null; - } - - private static Int32 CoordinateLength(String curve) => - curve == "P-256" ? 32 : curve == "P-384" ? 48 : 66; - - private static Byte[] EncodePoint(ECParameters parameters, String curve) - { - var size = CoordinateLength(curve); + var size = EcKeyParameters.CoordinateLength(parameters.Curve); var result = new Byte[1 + 2 * size]; result[0] = 4; - Buffer.BlockCopy(Pad(parameters.Q.X, size), 0, result, 1, size); - Buffer.BlockCopy(Pad(parameters.Q.Y, size), 0, result, 1 + size, size); + Buffer.BlockCopy(Pad(parameters.X, size), 0, result, 1, size); + Buffer.BlockCopy(Pad(parameters.Y, size), 0, result, 1 + size, size); return result; } @@ -1460,19 +1398,48 @@ private static Int32 BlockBits(String hash) => private static Byte[] Hash(String hash, Byte[] data) { - using (var algorithm = IncrementalHash.CreateHash(HashName(hash))) + using (var algorithm = CreateHash(hash)) { - algorithm.AppendData(data); - return algorithm.GetHashAndReset(); + return algorithm.ComputeHash(data); } } private static Byte[] Hmac(String hash, Byte[] key, Byte[] data) { - using (var algorithm = IncrementalHash.CreateHMAC(HashName(hash), key)) + using (var algorithm = CreateHmac(hash, key)) { - algorithm.AppendData(data); - return algorithm.GetHashAndReset(); + return algorithm.ComputeHash(data); + } + } + + // Not IncrementalHash, which .NET Framework 4.6.2 does not have. + private static HashAlgorithm CreateHash(String hash) + { + switch (hash) + { + case "SHA-1": + return SHA1.Create(); + case "SHA-256": + return SHA256.Create(); + case "SHA-384": + return SHA384.Create(); + default: + return SHA512.Create(); + } + } + + private static HMAC CreateHmac(String hash, Byte[] key) + { + switch (hash) + { + case "SHA-1": + return new HMACSHA1(key); + case "SHA-256": + return new HMACSHA256(key); + case "SHA-384": + return new HMACSHA384(key); + default: + return new HMACSHA512(key); } } @@ -1573,6 +1540,41 @@ private static Exception TypeError(String message) => #region Nested types + /// + /// The usages the public and the private key of a pair may have. + /// + private readonly struct KeyPairUsages + { + public KeyPairUsages(String[] @public, String[] @private) + { + Public = @public; + Private = @private; + } + + public String[] Public { get; } + + public String[] Private { get; } + } + + /// + /// The parameters of AES-GCM, with the length of the tag in bytes. + /// + private readonly struct AesGcmParameters + { + public AesGcmParameters(Byte[] iv, Byte[] additionalData, Int32 tagLength) + { + Iv = iv; + AdditionalData = additionalData; + TagLength = tagLength; + } + + public Byte[] Iv { get; } + + public Byte[] AdditionalData { get; } + + public Int32 TagLength { get; } + } + /// /// A normalized algorithm: its name, and the object of a script with its parameters. /// From 69fb879189c9ed1bbd8495b90df3f7cd366f7818 Mon Sep 17 00:00:00 2001 From: Florian Rappl Date: Mon, 23 Nov 2026 09:12:54 +0100 Subject: [PATCH 08/19] Support for .NET 4.6.2 --- src/AngleSharp.Js/Dom/EcKeyParameters.cs | 98 +++- src/AngleSharp.Js/Dom/KeyDer.cs | 556 +++++++++++++++++++++++ src/AngleSharp.Js/Dom/ManagedAesGcm.cs | 193 ++++++++ src/AngleSharp.Js/Dom/WebCrypto.cs | 96 +++- 4 files changed, 913 insertions(+), 30 deletions(-) create mode 100644 src/AngleSharp.Js/Dom/KeyDer.cs create mode 100644 src/AngleSharp.Js/Dom/ManagedAesGcm.cs diff --git a/src/AngleSharp.Js/Dom/EcKeyParameters.cs b/src/AngleSharp.Js/Dom/EcKeyParameters.cs index c026d3b8..db5295e5 100644 --- a/src/AngleSharp.Js/Dom/EcKeyParameters.cs +++ b/src/AngleSharp.Js/Dom/EcKeyParameters.cs @@ -2,11 +2,15 @@ namespace AngleSharp.Js.Dom { using System; using System.Security.Cryptography; +#if NETFRAMEWORK + using Microsoft.Win32.SafeHandles; + using System.Runtime.InteropServices; +#endif /// /// The material of an elliptic curve key on one of the named curves of the Web Cryptography - /// API. It stands in for ECParameters, which .NET Framework 4.6.2 does not have: there the - /// key reaches the platform as a CNG key blob instead. + /// API. It stands in for ECParameters, which .NET Framework 4.6.2 does not have: on .NET + /// Framework the key reaches the platform (CNG) as a key blob instead. /// readonly struct EcKeyParameters { @@ -44,7 +48,8 @@ public static Int32 CoordinateLength(String curve) => /// public static EcKeyParameters Generate(String curve) { -#if NET462 +#if NETFRAMEWORK + // the key has to allow the export explicitly, as its private part is taken out of it var creation = new CngKeyCreationParameters { ExportPolicy = CngExportPolicies.AllowPlaintextExport }; using (var key = CngKey.Create(GetCngAlgorithm(curve), null, creation)) @@ -65,25 +70,92 @@ public static EcKeyParameters Generate(String curve) /// public ECDsa CreateEcdsa() { -#if NET462 - var format = IsPrivate ? CngKeyBlobFormat.EccPrivateBlob : CngKeyBlobFormat.EccPublicBlob; - return new ECDsaCng(CngKey.Import(ToBlob(), format)); +#if NETFRAMEWORK + // ECDsaCng duplicates the handle of the key it is given + using (var key = ImportCngKey(false)) + { + return new ECDsaCng(key); + } #else return ECDsa.Create(ToParameters()); #endif } -#if NET462 +#if NET8_0_OR_GREATER || NETFRAMEWORK + /// + /// Derives the shared secret of ECDH (the x coordinate of the product, not hashed) of + /// this private key and the given public key. Throws a PlatformNotSupportedException + /// if the platform can't give out the secret as it is. + /// + public Byte[] DeriveSecret(EcKeyParameters publicKey) + { +#if NETFRAMEWORK + // ECDiffieHellmanCng only gives out secrets put through a KDF, but CNG itself gives + // out the raw one (BCRYPT_KDF_RAW_SECRET, since Windows 10) - which is how .NET + // implements DeriveRawSecretAgreement on Windows + using (var mine = ImportCngKey(true)) + using (var theirs = publicKey.ImportCngKey(true)) + using (var ecdh = new ECDiffieHellmanCng(mine)) + using (var secret = ecdh.DeriveSecretAgreementHandle(theirs)) + { + // asked for the length first, then for the secret + var status = NCryptDeriveKey(secret, RawSecretKdf, IntPtr.Zero, null, 0, out var length, 0); + var result = new Byte[status == 0 ? length : 0]; + + if (status == 0) + { + status = NCryptDeriveKey(secret, RawSecretKdf, IntPtr.Zero, result, result.Length, out length, 0); + } + + if (status == NotSupportedStatus || status == InvalidParameterStatus) + { + throw new PlatformNotSupportedException(); + } + else if (status != 0) + { + throw new CryptographicException(status); + } + + // CNG gives out the secret as a little endian number + Array.Reverse(result, 0, length); + return length == result.Length ? result : Slice(result, 0, length); + } +#else + using (var mine = ECDiffieHellman.Create(ToParameters())) + using (var theirs = ECDiffieHellman.Create(publicKey.ToParameters())) + { + return mine.DeriveRawSecretAgreement(theirs.PublicKey); + } +#endif + } +#endif + +#if NETFRAMEWORK + private const String RawSecretKdf = "TRUNCATE"; + + private const Int32 NotSupportedStatus = unchecked((Int32)0x80090029); + + private const Int32 InvalidParameterStatus = unchecked((Int32)0x80090027); + // BCRYPT_ECCKEY_BLOB: the magic and the length of a coordinate (each a little endian // UInt32), followed by X, Y and - for a private key - D, each of that length. private const Int32 BlobHeaderLength = 8; - private Byte[] ToBlob() + [DllImport("ncrypt.dll", CharSet = CharSet.Unicode)] + private static extern Int32 NCryptDeriveKey(SafeNCryptSecretHandle hSharedSecret, String pwszKDF, IntPtr pParameterList, Byte[] pbDerivedKey, Int32 cbDerivedKey, out Int32 pcbResult, Int32 dwFlags); + + private CngKey ImportCngKey(Boolean isEcdh) + { + var format = IsPrivate ? CngKeyBlobFormat.EccPrivateBlob : CngKeyBlobFormat.EccPublicBlob; + return CngKey.Import(ToBlob(isEcdh), format); + } + + private Byte[] ToBlob(Boolean isEcdh) { var size = CoordinateLength(Curve); var count = IsPrivate ? 3 : 2; var blob = new Byte[BlobHeaderLength + count * size]; - WriteUInt32(blob, 0, GetMagic(Curve, IsPrivate)); + WriteUInt32(blob, 0, GetMagic(Curve, isEcdh, IsPrivate)); WriteUInt32(blob, 4, (UInt32)size); CopyPadded(X, blob, BlobHeaderLength, size); CopyPadded(Y, blob, BlobHeaderLength + size, size); @@ -106,12 +178,12 @@ private static EcKeyParameters FromBlob(String curve, Byte[] blob) return new EcKeyParameters(curve, x, y, d); } - // The ECDSA magics ("ECS1" to "ECS6"): an ECDH key only ever reaches the platform to be - // checked here, which the ECDSA algorithm of the same curve does just as well. - private static UInt32 GetMagic(String curve, Boolean isPrivate) + // "ECS1" to "ECS6" for ECDSA and "ECK1" to "ECK6" for ECDH: public and private of each + // curve in turn, as little endian UInt32 values. + private static UInt32 GetMagic(String curve, Boolean isEcdh, Boolean isPrivate) { var index = curve == "P-256" ? 1u : curve == "P-384" ? 3u : 5u; - return 0x30534345u + index + (isPrivate ? 1u : 0u); + return (isEcdh ? 0x304B4345u : 0x30534345u) + index + (isPrivate ? 1u : 0u); } private static CngAlgorithm GetCngAlgorithm(String curve) diff --git a/src/AngleSharp.Js/Dom/KeyDer.cs b/src/AngleSharp.Js/Dom/KeyDer.cs new file mode 100644 index 00000000..1468e084 --- /dev/null +++ b/src/AngleSharp.Js/Dom/KeyDer.cs @@ -0,0 +1,556 @@ +#if !NET8_0_OR_GREATER +namespace AngleSharp.Js.Dom +{ + using System; + using System.Collections.Generic; + using System.Security.Cryptography; + using System.Text; + + /// + /// The formats spki (SubjectPublicKeyInfo, RFC 5280) and pkcs8 (PrivateKeyInfo, RFC 5208) + /// of the EC (RFC 5480, RFC 5915) and RSA (RFC 8017) keys, in DER. .NET brings them only + /// since .NET Core 3, so the older targets get them from here. Malformed data throws a + /// CryptographicException. + /// + static class KeyDer + { + private const String EcPublicKeyOid = "1.2.840.10045.2.1"; + private const String RsaEncryptionOid = "1.2.840.113549.1.1.1"; + + private const Byte IntegerTag = 0x02; + private const Byte BitStringTag = 0x03; + private const Byte OctetStringTag = 0x04; + private const Byte NullTag = 0x05; + private const Byte OidTag = 0x06; + private const Byte SequenceTag = 0x30; + private const Byte EcParametersTag = 0xA0; + private const Byte EcPublicKeyTag = 0xA1; + + #region EC + + /// + /// Reads an EC key on the given curve. The public point of a pkcs8 key is optional: the + /// coordinates are null without it. + /// + public static EcKeyParameters ReadEc(String format, Byte[] data, String curve) + { + var info = ReadInfo(format, data); + var algorithm = info.ReadSequence(); + + if (algorithm.ReadOid() != EcPublicKeyOid || GetCurveName(algorithm.ReadOid()) != curve) + { + throw Malformed(); + } + + algorithm.End(); + + if (format == "spki") + { + var point = info.ReadBitString(); + info.End(); + return FromPoint(curve, point, null); + } + + var key = ReadSingle(info.ReadOctetString()); + Byte[] publicPoint = null; + + if (!IsInteger(key.ReadInteger(), 1)) + { + throw Malformed(); + } + + var d = key.ReadOctetString(); + + while (key.HasMore) + { + var tag = key.PeekTag(); + + if (tag == EcParametersTag) + { + var parameters = key.Read(EcParametersTag); + + if (GetCurveName(parameters.ReadOid()) != curve) + { + throw Malformed(); + } + } + else if (tag == EcPublicKeyTag) + { + publicPoint = key.Read(EcPublicKeyTag).ReadBitString(); + } + else + { + throw Malformed(); + } + } + + return publicPoint != null ? FromPoint(curve, publicPoint, d) : new EcKeyParameters(curve, null, null, Pad(d, EcKeyParameters.CoordinateLength(curve))); + } + + public static Byte[] WriteEc(String format, EcKeyParameters key) + { + var size = EcKeyParameters.CoordinateLength(key.Curve); + var point = new Byte[1 + 2 * size]; + point[0] = 4; + Buffer.BlockCopy(Pad(key.X, size), 0, point, 1, size); + Buffer.BlockCopy(Pad(key.Y, size), 0, point, 1 + size, size); + var algorithm = Encode(SequenceTag, EncodeOid(EcPublicKeyOid), EncodeOid(GetCurveOid(key.Curve))); + + if (format == "spki") + { + return Encode(SequenceTag, algorithm, EncodeBitString(point)); + } + + var privateKey = Encode(SequenceTag, + EncodeInteger(1), + Encode(OctetStringTag, Pad(key.D, size)), + Encode(EcPublicKeyTag, EncodeBitString(point))); + return Encode(SequenceTag, EncodeInteger(0), algorithm, Encode(OctetStringTag, privateKey)); + } + + private static EcKeyParameters FromPoint(String curve, Byte[] point, Byte[] d) + { + var size = EcKeyParameters.CoordinateLength(curve); + + // only the uncompressed form of the point + if (point.Length != 1 + 2 * size || point[0] != 4) + { + throw Malformed(); + } + + var x = new Byte[size]; + var y = new Byte[size]; + Buffer.BlockCopy(point, 1, x, 0, size); + Buffer.BlockCopy(point, 1 + size, y, 0, size); + return new EcKeyParameters(curve, x, y, d != null ? Pad(d, size) : null); + } + + private static String GetCurveName(String oid) + { + switch (oid) + { + case "1.2.840.10045.3.1.7": + return "P-256"; + case "1.3.132.0.34": + return "P-384"; + case "1.3.132.0.35": + return "P-521"; + default: + return null; + } + } + + private static String GetCurveOid(String curve) + { + switch (curve) + { + case "P-256": + return "1.2.840.10045.3.1.7"; + case "P-384": + return "1.3.132.0.34"; + default: + return "1.3.132.0.35"; + } + } + + #endregion + + #region RSA + + public static RSAParameters ReadRsa(String format, Byte[] data) + { + var info = ReadInfo(format, data); + var algorithm = info.ReadSequence(); + + if (algorithm.ReadOid() != RsaEncryptionOid) + { + throw Malformed(); + } + + // the parameters are NULL, which some encoders leave out + if (algorithm.HasMore) + { + algorithm.ReadNull(); + } + + algorithm.End(); + + if (format == "spki") + { + var publicKey = ReadSingle(info.ReadBitString()); + info.End(); + var parameters = new RSAParameters + { + Modulus = publicKey.ReadInteger(), + Exponent = publicKey.ReadInteger(), + }; + publicKey.End(); + return parameters; + } + + var key = ReadSingle(info.ReadOctetString()); + + // version 0: two primes, which is all the platform takes + if (!IsInteger(key.ReadInteger(), 0)) + { + throw Malformed(); + } + + var modulus = key.ReadInteger(); + var half = (modulus.Length + 1) / 2; + var result = new RSAParameters + { + Modulus = modulus, + Exponent = key.ReadInteger(), + D = Pad(key.ReadInteger(), modulus.Length), + P = Pad(key.ReadInteger(), half), + Q = Pad(key.ReadInteger(), half), + DP = Pad(key.ReadInteger(), half), + DQ = Pad(key.ReadInteger(), half), + InverseQ = Pad(key.ReadInteger(), half), + }; + key.End(); + return result; + } + + public static Byte[] WriteRsa(String format, RSAParameters key) + { + var algorithm = Encode(SequenceTag, EncodeOid(RsaEncryptionOid), Encode(NullTag)); + + if (format == "spki") + { + var publicKey = Encode(SequenceTag, EncodeInteger(key.Modulus), EncodeInteger(key.Exponent)); + return Encode(SequenceTag, algorithm, EncodeBitString(publicKey)); + } + + var privateKey = Encode(SequenceTag, + EncodeInteger(0), + EncodeInteger(key.Modulus), + EncodeInteger(key.Exponent), + EncodeInteger(key.D), + EncodeInteger(key.P), + EncodeInteger(key.Q), + EncodeInteger(key.DP), + EncodeInteger(key.DQ), + EncodeInteger(key.InverseQ)); + return Encode(SequenceTag, EncodeInteger(0), algorithm, Encode(OctetStringTag, privateKey)); + } + + #endregion + + #region Helpers + + // The outer SEQUENCE of either format, past the version of a PrivateKeyInfo. + private static DerReader ReadInfo(String format, Byte[] data) + { + var info = ReadSingle(data); + + // version 1 is a OneAsymmetricKey (RFC 5958), which may carry the public key too + if (format == "pkcs8") + { + var version = info.ReadInteger(); + + if (!IsInteger(version, 0) && !IsInteger(version, 1)) + { + throw Malformed(); + } + } + + return info; + } + + // The one SEQUENCE the data consists of. + private static DerReader ReadSingle(Byte[] data) + { + var reader = new DerReader(data, 0, data.Length); + var sequence = reader.ReadSequence(); + reader.End(); + return sequence; + } + + private static Boolean IsInteger(Byte[] value, Byte expected) => value.Length == 1 && value[0] == expected; + + private static Byte[] Pad(Byte[] value, Int32 length) + { + var start = 0; + + while (value.Length - start > length && value[start] == 0) + { + start++; + } + + if (value.Length - start > length) + { + throw Malformed(); + } + + var result = new Byte[length]; + Buffer.BlockCopy(value, start, result, length - (value.Length - start), value.Length - start); + return result; + } + + private static Byte[] Encode(Byte tag, params Byte[][] contents) + { + var length = 0; + + for (var i = 0; i < contents.Length; i++) + { + length += contents[i].Length; + } + + var lengthBytes = length < 0x80 ? 0 : length <= 0xFF ? 1 : length <= 0xFFFF ? 2 : 3; + var result = new Byte[2 + lengthBytes + length]; + var offset = 2 + lengthBytes; + result[0] = tag; + + if (lengthBytes == 0) + { + result[1] = (Byte)length; + } + else + { + result[1] = (Byte)(0x80 | lengthBytes); + + for (var i = 0; i < lengthBytes; i++) + { + result[1 + lengthBytes - i] = (Byte)(length >> (8 * i)); + } + } + + for (var i = 0; i < contents.Length; i++) + { + Buffer.BlockCopy(contents[i], 0, result, offset, contents[i].Length); + offset += contents[i].Length; + } + + return result; + } + + private static Byte[] EncodeInteger(Int32 value) => Encode(IntegerTag, new[] { (Byte)value }); + + // The (unsigned, big endian) value as the shortest positive INTEGER. + private static Byte[] EncodeInteger(Byte[] value) + { + var start = 0; + + while (start < value.Length - 1 && value[start] == 0) + { + start++; + } + + var sign = (value[start] & 0x80) != 0 ? 1 : 0; + var content = new Byte[sign + value.Length - start]; + Buffer.BlockCopy(value, start, content, sign, value.Length - start); + return Encode(IntegerTag, content); + } + + private static Byte[] EncodeBitString(Byte[] value) + { + var content = new Byte[1 + value.Length]; + Buffer.BlockCopy(value, 0, content, 1, value.Length); + return Encode(BitStringTag, content); + } + + private static Byte[] EncodeOid(String oid) + { + var arcs = oid.Split('.'); + var content = new List(); + AppendArc(content, 40 * Int64.Parse(arcs[0]) + Int64.Parse(arcs[1])); + + for (var i = 2; i < arcs.Length; i++) + { + AppendArc(content, Int64.Parse(arcs[i])); + } + + return Encode(OidTag, content.ToArray()); + } + + // Base 128, most significant group first, all but the last with the high bit set. + private static void AppendArc(List content, Int64 arc) + { + var start = content.Count; + content.Add((Byte)(arc & 0x7F)); + + while ((arc >>= 7) > 0) + { + content.Insert(start, (Byte)(0x80 | (arc & 0x7F))); + } + } + + private static Exception Malformed() => new CryptographicException("The key data is not valid DER."); + + #endregion + + #region Reader + + /// + /// Reads the elements of a DER encoded constructed value one after another. + /// + private sealed class DerReader + { + private readonly Byte[] _data; + private readonly Int32 _end; + private Int32 _position; + + public DerReader(Byte[] data, Int32 offset, Int32 end) + { + _data = data; + _position = offset; + _end = end; + } + + public Boolean HasMore => _position < _end; + + public Byte PeekTag() => HasMore ? _data[_position] : throw Malformed(); + + public DerReader ReadSequence() => Read(SequenceTag); + + // The contents of the next element, which has to have the given tag. + public DerReader Read(Byte tag) + { + var length = ReadHeader(tag); + var reader = new DerReader(_data, _position, _position + length); + _position += length; + return reader; + } + + // The magnitude of a non-negative INTEGER, big endian, without leading zeros. + public Byte[] ReadInteger() + { + var value = ReadBytes(IntegerTag); + + if (value.Length == 0 || (value[0] & 0x80) != 0) + { + throw Malformed(); + } + + var start = 0; + + while (start < value.Length - 1 && value[start] == 0) + { + start++; + } + + return start == 0 ? value : Slice(value, start, value.Length - start); + } + + public Byte[] ReadOctetString() => ReadBytes(OctetStringTag); + + public Byte[] ReadBitString() + { + var value = ReadBytes(BitStringTag); + + // the keys are whole bytes, so there can't be unused bits + if (value.Length == 0 || value[0] != 0) + { + throw Malformed(); + } + + return Slice(value, 1, value.Length - 1); + } + + public void ReadNull() + { + if (ReadHeader(NullTag) != 0) + { + throw Malformed(); + } + } + + public String ReadOid() + { + var value = ReadBytes(OidTag); + var result = new StringBuilder(); + var arc = 0L; + + for (var i = 0; i < value.Length; i++) + { + if (arc > (Int64.MaxValue >> 7)) + { + throw Malformed(); + } + + arc = (arc << 7) | (value[i] & 0x7Fu); + + if ((value[i] & 0x80) == 0) + { + if (result.Length == 0) + { + var first = Math.Min(arc / 40, 2); + result.Append(first).Append('.').Append(arc - 40 * first); + } + else + { + result.Append('.').Append(arc); + } + + arc = 0; + } + } + + return result.Length > 0 && (value[value.Length - 1] & 0x80) == 0 ? result.ToString() : throw Malformed(); + } + + public void End() + { + if (HasMore) + { + throw Malformed(); + } + } + + private Byte[] ReadBytes(Byte tag) + { + var length = ReadHeader(tag); + var value = Slice(_data, _position, length); + _position += length; + return value; + } + + // The length of the element with the given tag; the position is then at its contents. + private Int32 ReadHeader(Byte tag) + { + if (_end - _position < 2 || _data[_position] != tag) + { + throw Malformed(); + } + + var first = _data[_position + 1]; + var length = 0; + _position += 2; + + if (first < 0x80) + { + length = first; + } + else + { + // the definite long form only, of at most three bytes (16 MB) + var count = first & 0x7F; + + if (count == 0 || count > 3 || _end - _position < count) + { + throw Malformed(); + } + + for (var i = 0; i < count; i++) + { + length = (length << 8) | _data[_position++]; + } + } + + return length <= _end - _position ? length : throw Malformed(); + } + + private static Byte[] Slice(Byte[] value, Int32 offset, Int32 length) + { + var result = new Byte[length]; + Buffer.BlockCopy(value, offset, result, 0, length); + return result; + } + } + + #endregion + } +} +#endif diff --git a/src/AngleSharp.Js/Dom/ManagedAesGcm.cs b/src/AngleSharp.Js/Dom/ManagedAesGcm.cs new file mode 100644 index 00000000..d5beca91 --- /dev/null +++ b/src/AngleSharp.Js/Dom/ManagedAesGcm.cs @@ -0,0 +1,193 @@ +#if !NET8_0_OR_GREATER +namespace AngleSharp.Js.Dom +{ + using System; + using System.Security.Cryptography; + + /// + /// AES-GCM (NIST SP 800-38D) on top of the AES block cipher, for the targets without + /// AesGcm. Only for the 96 bit IVs WebCrypto lets through, which make the first counter + /// block the IV followed by 1. A tag that does not match throws a CryptographicException. + /// + static class ManagedAesGcm + { + private const Int32 BlockSize = 16; + + // The reduction polynomial of GF(2^128) in the bit order of GCM. + private const UInt64 R = 0xE100000000000000; + + public static Byte[] Encrypt(Byte[] key, Byte[] iv, Byte[] data, Byte[] additionalData, Int32 tagLength) + { + var result = new Byte[data.Length + tagLength]; + + using (var aes = CreateAes(key)) + using (var encryptor = aes.CreateEncryptor()) + { + var j0 = GetFirstCounter(iv); + Ctr(encryptor, j0, data, data.Length, result); + var tag = ComputeTag(encryptor, j0, additionalData ?? new Byte[0], result, data.Length); + Buffer.BlockCopy(tag, 0, result, data.Length, tagLength); + } + + return result; + } + + public static Byte[] Decrypt(Byte[] key, Byte[] iv, Byte[] data, Byte[] additionalData, Int32 tagLength) + { + var length = data.Length - tagLength; + var result = new Byte[length]; + + using (var aes = CreateAes(key)) + using (var encryptor = aes.CreateEncryptor()) + { + var j0 = GetFirstCounter(iv); + var tag = ComputeTag(encryptor, j0, additionalData ?? new Byte[0], data, length); + var difference = 0; + + // in constant time, so a tag can't be guessed byte by byte + for (var i = 0; i < tagLength; i++) + { + difference |= tag[i] ^ data[length + i]; + } + + if (difference != 0) + { + throw new CryptographicException("The tag of the data does not match."); + } + + Ctr(encryptor, j0, data, length, result); + } + + return result; + } + + private static Aes CreateAes(Byte[] key) + { + var aes = Aes.Create(); + aes.Key = key; + aes.Mode = CipherMode.ECB; + aes.Padding = PaddingMode.None; + return aes; + } + + private static Byte[] GetFirstCounter(Byte[] iv) + { + var j0 = new Byte[BlockSize]; + Buffer.BlockCopy(iv, 0, j0, 0, 12); + j0[BlockSize - 1] = 1; + return j0; + } + + // GCTR, starting with the block after the first counter block (which is for the tag). + private static void Ctr(ICryptoTransform encryptor, Byte[] j0, Byte[] input, Int32 length, Byte[] output) + { + var counter = (Byte[])j0.Clone(); + var stream = new Byte[BlockSize]; + + for (var offset = 0; offset < length; offset += BlockSize) + { + Increment32(counter); + encryptor.TransformBlock(counter, 0, BlockSize, stream, 0); + + for (var i = 0; i < BlockSize && offset + i < length; i++) + { + output[offset + i] = (Byte)(input[offset + i] ^ stream[i]); + } + } + } + + // The tag: the first counter block encrypted, XOR GHASH of the additional data, the + // first length bytes of the ciphertext and both of their lengths in bits. + private static Byte[] ComputeTag(ICryptoTransform encryptor, Byte[] j0, Byte[] additionalData, Byte[] ciphertext, Int32 length) + { + var block = new Byte[BlockSize]; + encryptor.TransformBlock(new Byte[BlockSize], 0, BlockSize, block, 0); + var hHi = ReadUInt64(block, 0); + var hLo = ReadUInt64(block, 8); + var yHi = 0UL; + var yLo = 0UL; + Absorb(additionalData, additionalData.Length, hHi, hLo, ref yHi, ref yLo); + Absorb(ciphertext, length, hHi, hLo, ref yHi, ref yLo); + yHi ^= (UInt64)additionalData.Length * 8; + yLo ^= (UInt64)length * 8; + Multiply(ref yHi, ref yLo, hHi, hLo); + encryptor.TransformBlock(j0, 0, BlockSize, block, 0); + WriteUInt64(block, 0, ReadUInt64(block, 0) ^ yHi); + WriteUInt64(block, 8, ReadUInt64(block, 8) ^ yLo); + return block; + } + + // GHASH over the data, padded with zeros to whole blocks. + private static void Absorb(Byte[] data, Int32 length, UInt64 hHi, UInt64 hLo, ref UInt64 yHi, ref UInt64 yLo) + { + var block = new Byte[BlockSize]; + + for (var offset = 0; offset < length; offset += BlockSize) + { + var count = Math.Min(BlockSize, length - offset); + Array.Clear(block, 0, BlockSize); + Buffer.BlockCopy(data, offset, block, 0, count); + yHi ^= ReadUInt64(block, 0); + yLo ^= ReadUInt64(block, 8); + Multiply(ref yHi, ref yLo, hHi, hLo); + } + } + + // Y = Y * H in GF(2^128), bit by bit with masks rather than with branches or tables, so + // the time taken does not depend on H (which is derived from the key). + private static void Multiply(ref UInt64 yHi, ref UInt64 yLo, UInt64 hHi, UInt64 hLo) + { + var zHi = 0UL; + var zLo = 0UL; + var vHi = hHi; + var vLo = hLo; + + for (var i = 0; i < 128; i++) + { + var bit = i < 64 ? (yHi >> (63 - i)) & 1 : (yLo >> (127 - i)) & 1; + var mask = 0UL - bit; + zHi ^= vHi & mask; + zLo ^= vLo & mask; + var carry = 0UL - (vLo & 1); + vLo = (vLo >> 1) | (vHi << 63); + vHi = (vHi >> 1) ^ (R & carry); + } + + yHi = zHi; + yLo = zLo; + } + + // Only the rightmost 32 bits are the counter (inc32). + private static void Increment32(Byte[] counter) + { + for (var i = BlockSize - 1; i >= BlockSize - 4; i--) + { + if (++counter[i] != 0) + { + break; + } + } + } + + private static UInt64 ReadUInt64(Byte[] value, Int32 offset) + { + var result = 0UL; + + for (var i = 0; i < 8; i++) + { + result = (result << 8) | value[offset + i]; + } + + return result; + } + + private static void WriteUInt64(Byte[] target, Int32 offset, UInt64 value) + { + for (var i = 7; i >= 0; i--, value >>= 8) + { + target[offset + i] = (Byte)value; + } + } + } +} +#endif diff --git a/src/AngleSharp.Js/Dom/WebCrypto.cs b/src/AngleSharp.Js/Dom/WebCrypto.cs index 54ca670e..e718bdd5 100644 --- a/src/AngleSharp.Js/Dom/WebCrypto.cs +++ b/src/AngleSharp.Js/Dom/WebCrypto.cs @@ -14,7 +14,8 @@ namespace AngleSharp.Js.Dom /// /// The operations of crypto.subtle (Web Cryptography API, W3C), done with the cryptography - /// of .NET. AES-GCM, the formats spki and pkcs8, and ECDH need .NET 8 or later. + /// of .NET. Where the older targets lack it, AES-GCM and the formats spki and pkcs8 come from + /// ManagedAesGcm and KeyDer. ECDH needs .NET 8 or later, or .NET Framework on Windows 10. /// static class WebCrypto { @@ -196,11 +197,7 @@ public static Object GenerateKey(Object algorithm, Boolean extractable, String[] try { - using (var rsa = RSA.Create()) - { - rsa.KeySize = bits; - parameters = rsa.ExportParameters(true); - } + parameters = GenerateRsa(bits); } catch (CryptographicException) { @@ -503,7 +500,8 @@ private static Byte[] AesGcmEncrypt(Algorithm algorithm, Byte[] key, Byte[] data return result; #else - throw NotSupportedError(); + var parameters = GetAesGcmParameters(algorithm); + return ManagedAesGcm.Encrypt(key, parameters.Iv, data, parameters.AdditionalData, parameters.TagLength); #endif } @@ -526,7 +524,14 @@ private static Byte[] AesGcmDecrypt(Algorithm algorithm, Byte[] key, Byte[] data return result; #else - throw NotSupportedError(); + var parameters = GetAesGcmParameters(algorithm); + + if (data.Length < parameters.TagLength) + { + throw OperationError(); + } + + return ManagedAesGcm.Decrypt(key, parameters.Iv, data, parameters.AdditionalData, parameters.TagLength); #endif } @@ -699,11 +704,18 @@ private static Byte[] DeriveBitsCore(Algorithm algorithm, CryptoKey key, Int32? private static Byte[] EcdhSecret(CryptoKey privateKey, CryptoKey publicKey) { -#if NET8_0_OR_GREATER - using (var mine = ECDiffieHellman.Create(privateKey.Ec.Value.ToParameters())) - using (var theirs = ECDiffieHellman.Create(publicKey.Ec.Value.ToParameters())) +#if NET8_0_OR_GREATER || NETFRAMEWORK + try { - return mine.DeriveRawSecretAgreement(theirs.PublicKey); + return privateKey.Ec.Value.DeriveSecret(publicKey.Ec.Value); + } + catch (PlatformNotSupportedException) + { + throw NotSupportedError(); + } + catch (CryptographicException) + { + throw OperationError(); } #else throw NotSupportedError(); @@ -933,7 +945,19 @@ private static EcKeyParameters ImportEcDer(String format, Byte[] data, String cu throw DataError(); } #else - throw NotSupportedError(); + EcKeyParameters parameters; + + try + { + parameters = KeyDer.ReadEc(format, data, curve); + } + catch (CryptographicException) + { + throw DataError(); + } + + // without the public point, which would have to be computed from the private key + return parameters.X != null ? parameters : throw NotSupportedError(); #endif } @@ -983,7 +1007,7 @@ private static CryptoKey ImportRsaKey(String format, Byte[] data, Jwk jwk, Algor try { - using (var rsa = RSA.Create()) + using (var rsa = CreateRsa()) { rsa.ImportParameters(parameters); } @@ -1021,7 +1045,14 @@ private static RSAParameters ImportRsaDer(String format, Byte[] data) throw DataError(); } #else - throw NotSupportedError(); + try + { + return KeyDer.ReadRsa(format, data); + } + catch (CryptographicException) + { + throw DataError(); + } #endif } @@ -1119,7 +1150,7 @@ private static Byte[] ExportDer(String format, CryptoKey key) return isPublic ? rsa.ExportSubjectPublicKeyInfo() : rsa.ExportPkcs8PrivateKey(); } #else - throw NotSupportedError(); + return key.Ec is EcKeyParameters ec ? KeyDer.WriteEc(format, ec) : KeyDer.WriteRsa(format, key.Rsa.Value); #endif } @@ -1181,11 +1212,42 @@ private static RSAParameters PublicPart(RSAParameters parameters) => private static RSA CreateRsa(CryptoKey key) { - var rsa = RSA.Create(); + var rsa = CreateRsa(); rsa.ImportParameters(key.Rsa.Value); return rsa; } + // RSA.Create() of .NET Framework is the CryptoAPI provider, which can neither sign with + // PSS nor encrypt with OAEP of a SHA-2 hash - CNG can. + private static RSA CreateRsa() => +#if NETFRAMEWORK + new RSACng(); +#else + RSA.Create(); +#endif + + private static RSAParameters GenerateRsa(Int32 bits) + { +#if NETFRAMEWORK + // the key has to allow the export explicitly, as its private part is taken out of it + var creation = new CngKeyCreationParameters { ExportPolicy = CngExportPolicies.AllowPlaintextExport }; + creation.Parameters.Add(new CngProperty("Length", BitConverter.GetBytes(bits), CngPropertyOptions.None)); + + // RSACng duplicates the handle of the key it is given + using (var key = CngKey.Create(CngAlgorithm.Rsa, null, creation)) + using (var rsa = new RSACng(key)) + { + return rsa.ExportParameters(true); + } +#else + using (var rsa = RSA.Create()) + { + rsa.KeySize = bits; + return rsa.ExportParameters(true); + } +#endif + } + private static RSASignaturePadding GetRsaPadding(Algorithm algorithm, CryptoKey key) { if (algorithm.Name == "RSA-PSS") From 8a6f00b274b87265e79c77425f14c60a297c5284 Mon Sep 17 00:00:00 2001 From: Florian Rappl Date: Mon, 23 Nov 2026 09:30:37 +0100 Subject: [PATCH 09/19] Adjusted for .NET 4.6.2 --- CHANGELOG.md | 2 +- src/AngleSharp.Js.Tests/WebCryptoTests.cs | 3 + src/AngleSharp.Js.Tests/WorkerTests.cs | 3 + src/AngleSharp.Js/AngleSharp.Js.csproj | 6 + src/AngleSharp.Js/Dom/Crypto.cs | 5 +- src/AngleSharp.Js/Dom/CryptoKey.cs | 2 +- src/AngleSharp.Js/Dom/EcKeyParameters.cs | 296 ------------ src/AngleSharp.Js/Dom/KeyDer.cs | 556 ---------------------- src/AngleSharp.Js/Dom/ManagedAesGcm.cs | 193 -------- src/AngleSharp.Js/Dom/WebCrypto.cs | 350 ++++++-------- 10 files changed, 161 insertions(+), 1255 deletions(-) delete mode 100644 src/AngleSharp.Js/Dom/EcKeyParameters.cs delete mode 100644 src/AngleSharp.Js/Dom/KeyDer.cs delete mode 100644 src/AngleSharp.Js/Dom/ManagedAesGcm.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 3f6a6537..fc05b407 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,7 +14,7 @@ Released on tbd. - Added delegates of the DOM as functions of scripts - Added `BigInteger` as BigInt, `Memory` as an ArrayBuffer - Added exceptions of the DOM (e.g. `WebAssembly.RuntimeError`) being errors of their class -- Added the Web Cryptography API (`crypto.subtle`, also in workers) +- Added the Web Cryptography API (`crypto.subtle`, also in workers; not on .NET Framework) # 1.2.3 diff --git a/src/AngleSharp.Js.Tests/WebCryptoTests.cs b/src/AngleSharp.Js.Tests/WebCryptoTests.cs index 2da359a7..59f609ee 100644 --- a/src/AngleSharp.Js.Tests/WebCryptoTests.cs +++ b/src/AngleSharp.Js.Tests/WebCryptoTests.cs @@ -1,3 +1,5 @@ +// crypto.subtle is not available on .NET Framework +#if !NETFRAMEWORK namespace AngleSharp.Js.Tests { using NUnit.Framework; @@ -329,3 +331,4 @@ public async Task FailuresRejectRatherThanThrow() } } } +#endif diff --git a/src/AngleSharp.Js.Tests/WorkerTests.cs b/src/AngleSharp.Js.Tests/WorkerTests.cs index e3d2ad60..db7a686d 100644 --- a/src/AngleSharp.Js.Tests/WorkerTests.cs +++ b/src/AngleSharp.Js.Tests/WorkerTests.cs @@ -75,6 +75,8 @@ public async Task WorkerRunsAModuleWithItsImports() worker.Terminate(); } +#if !NETFRAMEWORK + // crypto.subtle is not available on .NET Framework [Test] public async Task WorkerHasWebCrypto() { @@ -87,6 +89,7 @@ public async Task WorkerHasWebCrypto() Assert.AreEqual("object,function", worker.EvaluateInWorker("[typeof crypto.subtle, typeof CryptoKey].join()")?.ToString()); worker.Terminate(); } +#endif [Test] public async Task WorkerKnowsItsAddress() diff --git a/src/AngleSharp.Js/AngleSharp.Js.csproj b/src/AngleSharp.Js/AngleSharp.Js.csproj index 305b981f..13364435 100644 --- a/src/AngleSharp.Js/AngleSharp.Js.csproj +++ b/src/AngleSharp.Js/AngleSharp.Js.csproj @@ -25,6 +25,12 @@ + + + + + diff --git a/src/AngleSharp.Js/Dom/Crypto.cs b/src/AngleSharp.Js/Dom/Crypto.cs index c273cc04..8c7ae8c3 100644 --- a/src/AngleSharp.Js/Dom/Crypto.cs +++ b/src/AngleSharp.Js/Dom/Crypto.cs @@ -20,11 +20,14 @@ internal Crypto() { } +#if !NETFRAMEWORK /// - /// Gets the operations of the Web Cryptography API. + /// Gets the operations of the Web Cryptography API, which is not available on .NET + /// Framework. /// [DomName("subtle")] public SubtleCrypto Subtle { get; } = new SubtleCrypto(); +#endif /// /// Fills the given array of integers with random numbers. diff --git a/src/AngleSharp.Js/Dom/CryptoKey.cs b/src/AngleSharp.Js/Dom/CryptoKey.cs index a5e3908f..2ee25742 100644 --- a/src/AngleSharp.Js/Dom/CryptoKey.cs +++ b/src/AngleSharp.Js/Dom/CryptoKey.cs @@ -60,7 +60,7 @@ internal CryptoKey(String type, Boolean extractable, IDictionary internal RSAParameters? Rsa { get; set; } - internal EcKeyParameters? Ec { get; set; } + internal ECParameters? Ec { get; set; } internal Boolean Allows(String usage) => Array.IndexOf(_usages, usage) >= 0; } diff --git a/src/AngleSharp.Js/Dom/EcKeyParameters.cs b/src/AngleSharp.Js/Dom/EcKeyParameters.cs deleted file mode 100644 index db5295e5..00000000 --- a/src/AngleSharp.Js/Dom/EcKeyParameters.cs +++ /dev/null @@ -1,296 +0,0 @@ -namespace AngleSharp.Js.Dom -{ - using System; - using System.Security.Cryptography; -#if NETFRAMEWORK - using Microsoft.Win32.SafeHandles; - using System.Runtime.InteropServices; -#endif - - /// - /// The material of an elliptic curve key on one of the named curves of the Web Cryptography - /// API. It stands in for ECParameters, which .NET Framework 4.6.2 does not have: on .NET - /// Framework the key reaches the platform (CNG) as a key blob instead. - /// - readonly struct EcKeyParameters - { - public EcKeyParameters(String curve, Byte[] x, Byte[] y, Byte[] d) - { - Curve = curve; - X = x; - Y = y; - D = d; - } - - /// - /// Gets the name of the curve, i.e., "P-256", "P-384" or "P-521". - /// - public String Curve { get; } - - public Byte[] X { get; } - - public Byte[] Y { get; } - - /// - /// Gets the private key, which is null for a public key. - /// - public Byte[] D { get; } - - public Boolean IsPrivate => D != null; - - public EcKeyParameters PublicPart => new EcKeyParameters(Curve, X, Y, null); - - public static Int32 CoordinateLength(String curve) => - curve == "P-256" ? 32 : curve == "P-384" ? 48 : 66; - - /// - /// Creates a new key pair on the given curve. - /// - public static EcKeyParameters Generate(String curve) - { -#if NETFRAMEWORK - // the key has to allow the export explicitly, as its private part is taken out of it - var creation = new CngKeyCreationParameters { ExportPolicy = CngExportPolicies.AllowPlaintextExport }; - - using (var key = CngKey.Create(GetCngAlgorithm(curve), null, creation)) - { - return FromBlob(curve, key.Export(CngKeyBlobFormat.EccPrivateBlob)); - } -#else - using (var ecdsa = ECDsa.Create(GetNamedCurve(curve))) - { - return From(ecdsa.ExportParameters(true)).Value; - } -#endif - } - - /// - /// Creates the platform's ECDSA for the key, which also checks the key (e.g. that the - /// point is on the curve) by throwing a CryptographicException. - /// - public ECDsa CreateEcdsa() - { -#if NETFRAMEWORK - // ECDsaCng duplicates the handle of the key it is given - using (var key = ImportCngKey(false)) - { - return new ECDsaCng(key); - } -#else - return ECDsa.Create(ToParameters()); -#endif - } - -#if NET8_0_OR_GREATER || NETFRAMEWORK - /// - /// Derives the shared secret of ECDH (the x coordinate of the product, not hashed) of - /// this private key and the given public key. Throws a PlatformNotSupportedException - /// if the platform can't give out the secret as it is. - /// - public Byte[] DeriveSecret(EcKeyParameters publicKey) - { -#if NETFRAMEWORK - // ECDiffieHellmanCng only gives out secrets put through a KDF, but CNG itself gives - // out the raw one (BCRYPT_KDF_RAW_SECRET, since Windows 10) - which is how .NET - // implements DeriveRawSecretAgreement on Windows - using (var mine = ImportCngKey(true)) - using (var theirs = publicKey.ImportCngKey(true)) - using (var ecdh = new ECDiffieHellmanCng(mine)) - using (var secret = ecdh.DeriveSecretAgreementHandle(theirs)) - { - // asked for the length first, then for the secret - var status = NCryptDeriveKey(secret, RawSecretKdf, IntPtr.Zero, null, 0, out var length, 0); - var result = new Byte[status == 0 ? length : 0]; - - if (status == 0) - { - status = NCryptDeriveKey(secret, RawSecretKdf, IntPtr.Zero, result, result.Length, out length, 0); - } - - if (status == NotSupportedStatus || status == InvalidParameterStatus) - { - throw new PlatformNotSupportedException(); - } - else if (status != 0) - { - throw new CryptographicException(status); - } - - // CNG gives out the secret as a little endian number - Array.Reverse(result, 0, length); - return length == result.Length ? result : Slice(result, 0, length); - } -#else - using (var mine = ECDiffieHellman.Create(ToParameters())) - using (var theirs = ECDiffieHellman.Create(publicKey.ToParameters())) - { - return mine.DeriveRawSecretAgreement(theirs.PublicKey); - } -#endif - } -#endif - -#if NETFRAMEWORK - private const String RawSecretKdf = "TRUNCATE"; - - private const Int32 NotSupportedStatus = unchecked((Int32)0x80090029); - - private const Int32 InvalidParameterStatus = unchecked((Int32)0x80090027); - - // BCRYPT_ECCKEY_BLOB: the magic and the length of a coordinate (each a little endian - // UInt32), followed by X, Y and - for a private key - D, each of that length. - private const Int32 BlobHeaderLength = 8; - - [DllImport("ncrypt.dll", CharSet = CharSet.Unicode)] - private static extern Int32 NCryptDeriveKey(SafeNCryptSecretHandle hSharedSecret, String pwszKDF, IntPtr pParameterList, Byte[] pbDerivedKey, Int32 cbDerivedKey, out Int32 pcbResult, Int32 dwFlags); - - private CngKey ImportCngKey(Boolean isEcdh) - { - var format = IsPrivate ? CngKeyBlobFormat.EccPrivateBlob : CngKeyBlobFormat.EccPublicBlob; - return CngKey.Import(ToBlob(isEcdh), format); - } - - private Byte[] ToBlob(Boolean isEcdh) - { - var size = CoordinateLength(Curve); - var count = IsPrivate ? 3 : 2; - var blob = new Byte[BlobHeaderLength + count * size]; - WriteUInt32(blob, 0, GetMagic(Curve, isEcdh, IsPrivate)); - WriteUInt32(blob, 4, (UInt32)size); - CopyPadded(X, blob, BlobHeaderLength, size); - CopyPadded(Y, blob, BlobHeaderLength + size, size); - - if (IsPrivate) - { - CopyPadded(D, blob, BlobHeaderLength + 2 * size, size); - } - - return blob; - } - - private static EcKeyParameters FromBlob(String curve, Byte[] blob) - { - var size = (Int32)(blob[4] | blob[5] << 8 | blob[6] << 16 | blob[7] << 24); - var hasD = blob.Length >= BlobHeaderLength + 3 * size; - var x = Slice(blob, BlobHeaderLength, size); - var y = Slice(blob, BlobHeaderLength + size, size); - var d = hasD ? Slice(blob, BlobHeaderLength + 2 * size, size) : null; - return new EcKeyParameters(curve, x, y, d); - } - - // "ECS1" to "ECS6" for ECDSA and "ECK1" to "ECK6" for ECDH: public and private of each - // curve in turn, as little endian UInt32 values. - private static UInt32 GetMagic(String curve, Boolean isEcdh, Boolean isPrivate) - { - var index = curve == "P-256" ? 1u : curve == "P-384" ? 3u : 5u; - return (isEcdh ? 0x304B4345u : 0x30534345u) + index + (isPrivate ? 1u : 0u); - } - - private static CngAlgorithm GetCngAlgorithm(String curve) - { - switch (curve) - { - case "P-256": - return CngAlgorithm.ECDsaP256; - case "P-384": - return CngAlgorithm.ECDsaP384; - default: - return CngAlgorithm.ECDsaP521; - } - } - - private static void WriteUInt32(Byte[] target, Int32 offset, UInt32 value) - { - target[offset] = (Byte)value; - target[offset + 1] = (Byte)(value >> 8); - target[offset + 2] = (Byte)(value >> 16); - target[offset + 3] = (Byte)(value >> 24); - } - - // Right-aligned, as the coordinates are big endian numbers. - private static void CopyPadded(Byte[] value, Byte[] target, Int32 offset, Int32 size) - { - var start = 0; - - while (value.Length - start > size && value[start] == 0) - { - start++; - } - - var length = value.Length - start; - - if (length > size) - { - throw new CryptographicException(); - } - - Buffer.BlockCopy(value, start, target, offset + size - length, length); - } - - private static Byte[] Slice(Byte[] value, Int32 offset, Int32 length) - { - var result = new Byte[length]; - Buffer.BlockCopy(value, offset, result, 0, length); - return result; - } -#else - public ECParameters ToParameters() => new ECParameters - { - Curve = GetNamedCurve(Curve), - Q = new ECPoint { X = X, Y = Y }, - D = D, - }; - - /// - /// Gets the key of the given parameters, or null if they are not on one of the named - /// curves of the Web Cryptography API. - /// - public static EcKeyParameters? From(ECParameters parameters) - { - var curve = GetCurveName(parameters.Curve); - return curve != null ? new EcKeyParameters(curve, parameters.Q.X, parameters.Q.Y, parameters.D) : (EcKeyParameters?)null; - } - - private static ECCurve GetNamedCurve(String curve) - { - switch (curve) - { - case "P-256": - return ECCurve.NamedCurves.nistP256; - case "P-384": - return ECCurve.NamedCurves.nistP384; - default: - return ECCurve.NamedCurves.nistP521; - } - } - - private static String GetCurveName(ECCurve curve) - { - switch (curve.Oid?.Value) - { - case "1.2.840.10045.3.1.7": - return "P-256"; - case "1.3.132.0.34": - return "P-384"; - case "1.3.132.0.35": - return "P-521"; - } - - switch (curve.Oid?.FriendlyName) - { - case "nistP256": - case "ECDSA_P256": - return "P-256"; - case "nistP384": - case "ECDSA_P384": - return "P-384"; - case "nistP521": - case "ECDSA_P521": - return "P-521"; - } - - return null; - } -#endif - } -} diff --git a/src/AngleSharp.Js/Dom/KeyDer.cs b/src/AngleSharp.Js/Dom/KeyDer.cs deleted file mode 100644 index 1468e084..00000000 --- a/src/AngleSharp.Js/Dom/KeyDer.cs +++ /dev/null @@ -1,556 +0,0 @@ -#if !NET8_0_OR_GREATER -namespace AngleSharp.Js.Dom -{ - using System; - using System.Collections.Generic; - using System.Security.Cryptography; - using System.Text; - - /// - /// The formats spki (SubjectPublicKeyInfo, RFC 5280) and pkcs8 (PrivateKeyInfo, RFC 5208) - /// of the EC (RFC 5480, RFC 5915) and RSA (RFC 8017) keys, in DER. .NET brings them only - /// since .NET Core 3, so the older targets get them from here. Malformed data throws a - /// CryptographicException. - /// - static class KeyDer - { - private const String EcPublicKeyOid = "1.2.840.10045.2.1"; - private const String RsaEncryptionOid = "1.2.840.113549.1.1.1"; - - private const Byte IntegerTag = 0x02; - private const Byte BitStringTag = 0x03; - private const Byte OctetStringTag = 0x04; - private const Byte NullTag = 0x05; - private const Byte OidTag = 0x06; - private const Byte SequenceTag = 0x30; - private const Byte EcParametersTag = 0xA0; - private const Byte EcPublicKeyTag = 0xA1; - - #region EC - - /// - /// Reads an EC key on the given curve. The public point of a pkcs8 key is optional: the - /// coordinates are null without it. - /// - public static EcKeyParameters ReadEc(String format, Byte[] data, String curve) - { - var info = ReadInfo(format, data); - var algorithm = info.ReadSequence(); - - if (algorithm.ReadOid() != EcPublicKeyOid || GetCurveName(algorithm.ReadOid()) != curve) - { - throw Malformed(); - } - - algorithm.End(); - - if (format == "spki") - { - var point = info.ReadBitString(); - info.End(); - return FromPoint(curve, point, null); - } - - var key = ReadSingle(info.ReadOctetString()); - Byte[] publicPoint = null; - - if (!IsInteger(key.ReadInteger(), 1)) - { - throw Malformed(); - } - - var d = key.ReadOctetString(); - - while (key.HasMore) - { - var tag = key.PeekTag(); - - if (tag == EcParametersTag) - { - var parameters = key.Read(EcParametersTag); - - if (GetCurveName(parameters.ReadOid()) != curve) - { - throw Malformed(); - } - } - else if (tag == EcPublicKeyTag) - { - publicPoint = key.Read(EcPublicKeyTag).ReadBitString(); - } - else - { - throw Malformed(); - } - } - - return publicPoint != null ? FromPoint(curve, publicPoint, d) : new EcKeyParameters(curve, null, null, Pad(d, EcKeyParameters.CoordinateLength(curve))); - } - - public static Byte[] WriteEc(String format, EcKeyParameters key) - { - var size = EcKeyParameters.CoordinateLength(key.Curve); - var point = new Byte[1 + 2 * size]; - point[0] = 4; - Buffer.BlockCopy(Pad(key.X, size), 0, point, 1, size); - Buffer.BlockCopy(Pad(key.Y, size), 0, point, 1 + size, size); - var algorithm = Encode(SequenceTag, EncodeOid(EcPublicKeyOid), EncodeOid(GetCurveOid(key.Curve))); - - if (format == "spki") - { - return Encode(SequenceTag, algorithm, EncodeBitString(point)); - } - - var privateKey = Encode(SequenceTag, - EncodeInteger(1), - Encode(OctetStringTag, Pad(key.D, size)), - Encode(EcPublicKeyTag, EncodeBitString(point))); - return Encode(SequenceTag, EncodeInteger(0), algorithm, Encode(OctetStringTag, privateKey)); - } - - private static EcKeyParameters FromPoint(String curve, Byte[] point, Byte[] d) - { - var size = EcKeyParameters.CoordinateLength(curve); - - // only the uncompressed form of the point - if (point.Length != 1 + 2 * size || point[0] != 4) - { - throw Malformed(); - } - - var x = new Byte[size]; - var y = new Byte[size]; - Buffer.BlockCopy(point, 1, x, 0, size); - Buffer.BlockCopy(point, 1 + size, y, 0, size); - return new EcKeyParameters(curve, x, y, d != null ? Pad(d, size) : null); - } - - private static String GetCurveName(String oid) - { - switch (oid) - { - case "1.2.840.10045.3.1.7": - return "P-256"; - case "1.3.132.0.34": - return "P-384"; - case "1.3.132.0.35": - return "P-521"; - default: - return null; - } - } - - private static String GetCurveOid(String curve) - { - switch (curve) - { - case "P-256": - return "1.2.840.10045.3.1.7"; - case "P-384": - return "1.3.132.0.34"; - default: - return "1.3.132.0.35"; - } - } - - #endregion - - #region RSA - - public static RSAParameters ReadRsa(String format, Byte[] data) - { - var info = ReadInfo(format, data); - var algorithm = info.ReadSequence(); - - if (algorithm.ReadOid() != RsaEncryptionOid) - { - throw Malformed(); - } - - // the parameters are NULL, which some encoders leave out - if (algorithm.HasMore) - { - algorithm.ReadNull(); - } - - algorithm.End(); - - if (format == "spki") - { - var publicKey = ReadSingle(info.ReadBitString()); - info.End(); - var parameters = new RSAParameters - { - Modulus = publicKey.ReadInteger(), - Exponent = publicKey.ReadInteger(), - }; - publicKey.End(); - return parameters; - } - - var key = ReadSingle(info.ReadOctetString()); - - // version 0: two primes, which is all the platform takes - if (!IsInteger(key.ReadInteger(), 0)) - { - throw Malformed(); - } - - var modulus = key.ReadInteger(); - var half = (modulus.Length + 1) / 2; - var result = new RSAParameters - { - Modulus = modulus, - Exponent = key.ReadInteger(), - D = Pad(key.ReadInteger(), modulus.Length), - P = Pad(key.ReadInteger(), half), - Q = Pad(key.ReadInteger(), half), - DP = Pad(key.ReadInteger(), half), - DQ = Pad(key.ReadInteger(), half), - InverseQ = Pad(key.ReadInteger(), half), - }; - key.End(); - return result; - } - - public static Byte[] WriteRsa(String format, RSAParameters key) - { - var algorithm = Encode(SequenceTag, EncodeOid(RsaEncryptionOid), Encode(NullTag)); - - if (format == "spki") - { - var publicKey = Encode(SequenceTag, EncodeInteger(key.Modulus), EncodeInteger(key.Exponent)); - return Encode(SequenceTag, algorithm, EncodeBitString(publicKey)); - } - - var privateKey = Encode(SequenceTag, - EncodeInteger(0), - EncodeInteger(key.Modulus), - EncodeInteger(key.Exponent), - EncodeInteger(key.D), - EncodeInteger(key.P), - EncodeInteger(key.Q), - EncodeInteger(key.DP), - EncodeInteger(key.DQ), - EncodeInteger(key.InverseQ)); - return Encode(SequenceTag, EncodeInteger(0), algorithm, Encode(OctetStringTag, privateKey)); - } - - #endregion - - #region Helpers - - // The outer SEQUENCE of either format, past the version of a PrivateKeyInfo. - private static DerReader ReadInfo(String format, Byte[] data) - { - var info = ReadSingle(data); - - // version 1 is a OneAsymmetricKey (RFC 5958), which may carry the public key too - if (format == "pkcs8") - { - var version = info.ReadInteger(); - - if (!IsInteger(version, 0) && !IsInteger(version, 1)) - { - throw Malformed(); - } - } - - return info; - } - - // The one SEQUENCE the data consists of. - private static DerReader ReadSingle(Byte[] data) - { - var reader = new DerReader(data, 0, data.Length); - var sequence = reader.ReadSequence(); - reader.End(); - return sequence; - } - - private static Boolean IsInteger(Byte[] value, Byte expected) => value.Length == 1 && value[0] == expected; - - private static Byte[] Pad(Byte[] value, Int32 length) - { - var start = 0; - - while (value.Length - start > length && value[start] == 0) - { - start++; - } - - if (value.Length - start > length) - { - throw Malformed(); - } - - var result = new Byte[length]; - Buffer.BlockCopy(value, start, result, length - (value.Length - start), value.Length - start); - return result; - } - - private static Byte[] Encode(Byte tag, params Byte[][] contents) - { - var length = 0; - - for (var i = 0; i < contents.Length; i++) - { - length += contents[i].Length; - } - - var lengthBytes = length < 0x80 ? 0 : length <= 0xFF ? 1 : length <= 0xFFFF ? 2 : 3; - var result = new Byte[2 + lengthBytes + length]; - var offset = 2 + lengthBytes; - result[0] = tag; - - if (lengthBytes == 0) - { - result[1] = (Byte)length; - } - else - { - result[1] = (Byte)(0x80 | lengthBytes); - - for (var i = 0; i < lengthBytes; i++) - { - result[1 + lengthBytes - i] = (Byte)(length >> (8 * i)); - } - } - - for (var i = 0; i < contents.Length; i++) - { - Buffer.BlockCopy(contents[i], 0, result, offset, contents[i].Length); - offset += contents[i].Length; - } - - return result; - } - - private static Byte[] EncodeInteger(Int32 value) => Encode(IntegerTag, new[] { (Byte)value }); - - // The (unsigned, big endian) value as the shortest positive INTEGER. - private static Byte[] EncodeInteger(Byte[] value) - { - var start = 0; - - while (start < value.Length - 1 && value[start] == 0) - { - start++; - } - - var sign = (value[start] & 0x80) != 0 ? 1 : 0; - var content = new Byte[sign + value.Length - start]; - Buffer.BlockCopy(value, start, content, sign, value.Length - start); - return Encode(IntegerTag, content); - } - - private static Byte[] EncodeBitString(Byte[] value) - { - var content = new Byte[1 + value.Length]; - Buffer.BlockCopy(value, 0, content, 1, value.Length); - return Encode(BitStringTag, content); - } - - private static Byte[] EncodeOid(String oid) - { - var arcs = oid.Split('.'); - var content = new List(); - AppendArc(content, 40 * Int64.Parse(arcs[0]) + Int64.Parse(arcs[1])); - - for (var i = 2; i < arcs.Length; i++) - { - AppendArc(content, Int64.Parse(arcs[i])); - } - - return Encode(OidTag, content.ToArray()); - } - - // Base 128, most significant group first, all but the last with the high bit set. - private static void AppendArc(List content, Int64 arc) - { - var start = content.Count; - content.Add((Byte)(arc & 0x7F)); - - while ((arc >>= 7) > 0) - { - content.Insert(start, (Byte)(0x80 | (arc & 0x7F))); - } - } - - private static Exception Malformed() => new CryptographicException("The key data is not valid DER."); - - #endregion - - #region Reader - - /// - /// Reads the elements of a DER encoded constructed value one after another. - /// - private sealed class DerReader - { - private readonly Byte[] _data; - private readonly Int32 _end; - private Int32 _position; - - public DerReader(Byte[] data, Int32 offset, Int32 end) - { - _data = data; - _position = offset; - _end = end; - } - - public Boolean HasMore => _position < _end; - - public Byte PeekTag() => HasMore ? _data[_position] : throw Malformed(); - - public DerReader ReadSequence() => Read(SequenceTag); - - // The contents of the next element, which has to have the given tag. - public DerReader Read(Byte tag) - { - var length = ReadHeader(tag); - var reader = new DerReader(_data, _position, _position + length); - _position += length; - return reader; - } - - // The magnitude of a non-negative INTEGER, big endian, without leading zeros. - public Byte[] ReadInteger() - { - var value = ReadBytes(IntegerTag); - - if (value.Length == 0 || (value[0] & 0x80) != 0) - { - throw Malformed(); - } - - var start = 0; - - while (start < value.Length - 1 && value[start] == 0) - { - start++; - } - - return start == 0 ? value : Slice(value, start, value.Length - start); - } - - public Byte[] ReadOctetString() => ReadBytes(OctetStringTag); - - public Byte[] ReadBitString() - { - var value = ReadBytes(BitStringTag); - - // the keys are whole bytes, so there can't be unused bits - if (value.Length == 0 || value[0] != 0) - { - throw Malformed(); - } - - return Slice(value, 1, value.Length - 1); - } - - public void ReadNull() - { - if (ReadHeader(NullTag) != 0) - { - throw Malformed(); - } - } - - public String ReadOid() - { - var value = ReadBytes(OidTag); - var result = new StringBuilder(); - var arc = 0L; - - for (var i = 0; i < value.Length; i++) - { - if (arc > (Int64.MaxValue >> 7)) - { - throw Malformed(); - } - - arc = (arc << 7) | (value[i] & 0x7Fu); - - if ((value[i] & 0x80) == 0) - { - if (result.Length == 0) - { - var first = Math.Min(arc / 40, 2); - result.Append(first).Append('.').Append(arc - 40 * first); - } - else - { - result.Append('.').Append(arc); - } - - arc = 0; - } - } - - return result.Length > 0 && (value[value.Length - 1] & 0x80) == 0 ? result.ToString() : throw Malformed(); - } - - public void End() - { - if (HasMore) - { - throw Malformed(); - } - } - - private Byte[] ReadBytes(Byte tag) - { - var length = ReadHeader(tag); - var value = Slice(_data, _position, length); - _position += length; - return value; - } - - // The length of the element with the given tag; the position is then at its contents. - private Int32 ReadHeader(Byte tag) - { - if (_end - _position < 2 || _data[_position] != tag) - { - throw Malformed(); - } - - var first = _data[_position + 1]; - var length = 0; - _position += 2; - - if (first < 0x80) - { - length = first; - } - else - { - // the definite long form only, of at most three bytes (16 MB) - var count = first & 0x7F; - - if (count == 0 || count > 3 || _end - _position < count) - { - throw Malformed(); - } - - for (var i = 0; i < count; i++) - { - length = (length << 8) | _data[_position++]; - } - } - - return length <= _end - _position ? length : throw Malformed(); - } - - private static Byte[] Slice(Byte[] value, Int32 offset, Int32 length) - { - var result = new Byte[length]; - Buffer.BlockCopy(value, offset, result, 0, length); - return result; - } - } - - #endregion - } -} -#endif diff --git a/src/AngleSharp.Js/Dom/ManagedAesGcm.cs b/src/AngleSharp.Js/Dom/ManagedAesGcm.cs deleted file mode 100644 index d5beca91..00000000 --- a/src/AngleSharp.Js/Dom/ManagedAesGcm.cs +++ /dev/null @@ -1,193 +0,0 @@ -#if !NET8_0_OR_GREATER -namespace AngleSharp.Js.Dom -{ - using System; - using System.Security.Cryptography; - - /// - /// AES-GCM (NIST SP 800-38D) on top of the AES block cipher, for the targets without - /// AesGcm. Only for the 96 bit IVs WebCrypto lets through, which make the first counter - /// block the IV followed by 1. A tag that does not match throws a CryptographicException. - /// - static class ManagedAesGcm - { - private const Int32 BlockSize = 16; - - // The reduction polynomial of GF(2^128) in the bit order of GCM. - private const UInt64 R = 0xE100000000000000; - - public static Byte[] Encrypt(Byte[] key, Byte[] iv, Byte[] data, Byte[] additionalData, Int32 tagLength) - { - var result = new Byte[data.Length + tagLength]; - - using (var aes = CreateAes(key)) - using (var encryptor = aes.CreateEncryptor()) - { - var j0 = GetFirstCounter(iv); - Ctr(encryptor, j0, data, data.Length, result); - var tag = ComputeTag(encryptor, j0, additionalData ?? new Byte[0], result, data.Length); - Buffer.BlockCopy(tag, 0, result, data.Length, tagLength); - } - - return result; - } - - public static Byte[] Decrypt(Byte[] key, Byte[] iv, Byte[] data, Byte[] additionalData, Int32 tagLength) - { - var length = data.Length - tagLength; - var result = new Byte[length]; - - using (var aes = CreateAes(key)) - using (var encryptor = aes.CreateEncryptor()) - { - var j0 = GetFirstCounter(iv); - var tag = ComputeTag(encryptor, j0, additionalData ?? new Byte[0], data, length); - var difference = 0; - - // in constant time, so a tag can't be guessed byte by byte - for (var i = 0; i < tagLength; i++) - { - difference |= tag[i] ^ data[length + i]; - } - - if (difference != 0) - { - throw new CryptographicException("The tag of the data does not match."); - } - - Ctr(encryptor, j0, data, length, result); - } - - return result; - } - - private static Aes CreateAes(Byte[] key) - { - var aes = Aes.Create(); - aes.Key = key; - aes.Mode = CipherMode.ECB; - aes.Padding = PaddingMode.None; - return aes; - } - - private static Byte[] GetFirstCounter(Byte[] iv) - { - var j0 = new Byte[BlockSize]; - Buffer.BlockCopy(iv, 0, j0, 0, 12); - j0[BlockSize - 1] = 1; - return j0; - } - - // GCTR, starting with the block after the first counter block (which is for the tag). - private static void Ctr(ICryptoTransform encryptor, Byte[] j0, Byte[] input, Int32 length, Byte[] output) - { - var counter = (Byte[])j0.Clone(); - var stream = new Byte[BlockSize]; - - for (var offset = 0; offset < length; offset += BlockSize) - { - Increment32(counter); - encryptor.TransformBlock(counter, 0, BlockSize, stream, 0); - - for (var i = 0; i < BlockSize && offset + i < length; i++) - { - output[offset + i] = (Byte)(input[offset + i] ^ stream[i]); - } - } - } - - // The tag: the first counter block encrypted, XOR GHASH of the additional data, the - // first length bytes of the ciphertext and both of their lengths in bits. - private static Byte[] ComputeTag(ICryptoTransform encryptor, Byte[] j0, Byte[] additionalData, Byte[] ciphertext, Int32 length) - { - var block = new Byte[BlockSize]; - encryptor.TransformBlock(new Byte[BlockSize], 0, BlockSize, block, 0); - var hHi = ReadUInt64(block, 0); - var hLo = ReadUInt64(block, 8); - var yHi = 0UL; - var yLo = 0UL; - Absorb(additionalData, additionalData.Length, hHi, hLo, ref yHi, ref yLo); - Absorb(ciphertext, length, hHi, hLo, ref yHi, ref yLo); - yHi ^= (UInt64)additionalData.Length * 8; - yLo ^= (UInt64)length * 8; - Multiply(ref yHi, ref yLo, hHi, hLo); - encryptor.TransformBlock(j0, 0, BlockSize, block, 0); - WriteUInt64(block, 0, ReadUInt64(block, 0) ^ yHi); - WriteUInt64(block, 8, ReadUInt64(block, 8) ^ yLo); - return block; - } - - // GHASH over the data, padded with zeros to whole blocks. - private static void Absorb(Byte[] data, Int32 length, UInt64 hHi, UInt64 hLo, ref UInt64 yHi, ref UInt64 yLo) - { - var block = new Byte[BlockSize]; - - for (var offset = 0; offset < length; offset += BlockSize) - { - var count = Math.Min(BlockSize, length - offset); - Array.Clear(block, 0, BlockSize); - Buffer.BlockCopy(data, offset, block, 0, count); - yHi ^= ReadUInt64(block, 0); - yLo ^= ReadUInt64(block, 8); - Multiply(ref yHi, ref yLo, hHi, hLo); - } - } - - // Y = Y * H in GF(2^128), bit by bit with masks rather than with branches or tables, so - // the time taken does not depend on H (which is derived from the key). - private static void Multiply(ref UInt64 yHi, ref UInt64 yLo, UInt64 hHi, UInt64 hLo) - { - var zHi = 0UL; - var zLo = 0UL; - var vHi = hHi; - var vLo = hLo; - - for (var i = 0; i < 128; i++) - { - var bit = i < 64 ? (yHi >> (63 - i)) & 1 : (yLo >> (127 - i)) & 1; - var mask = 0UL - bit; - zHi ^= vHi & mask; - zLo ^= vLo & mask; - var carry = 0UL - (vLo & 1); - vLo = (vLo >> 1) | (vHi << 63); - vHi = (vHi >> 1) ^ (R & carry); - } - - yHi = zHi; - yLo = zLo; - } - - // Only the rightmost 32 bits are the counter (inc32). - private static void Increment32(Byte[] counter) - { - for (var i = BlockSize - 1; i >= BlockSize - 4; i--) - { - if (++counter[i] != 0) - { - break; - } - } - } - - private static UInt64 ReadUInt64(Byte[] value, Int32 offset) - { - var result = 0UL; - - for (var i = 0; i < 8; i++) - { - result = (result << 8) | value[offset + i]; - } - - return result; - } - - private static void WriteUInt64(Byte[] target, Int32 offset, UInt64 value) - { - for (var i = 7; i >= 0; i--, value >>= 8) - { - target[offset + i] = (Byte)value; - } - } - } -} -#endif diff --git a/src/AngleSharp.Js/Dom/WebCrypto.cs b/src/AngleSharp.Js/Dom/WebCrypto.cs index e718bdd5..40cbf0e4 100644 --- a/src/AngleSharp.Js/Dom/WebCrypto.cs +++ b/src/AngleSharp.Js/Dom/WebCrypto.cs @@ -14,8 +14,7 @@ namespace AngleSharp.Js.Dom /// /// The operations of crypto.subtle (Web Cryptography API, W3C), done with the cryptography - /// of .NET. Where the older targets lack it, AES-GCM and the formats spki and pkcs8 come from - /// ManagedAesGcm and KeyDer. ECDH needs .NET 8 or later, or .NET Framework on Windows 10. + /// of .NET. AES-GCM, the formats spki and pkcs8, and ECDH need .NET 8 or later. /// static class WebCrypto { @@ -88,7 +87,7 @@ public static Byte[] Sign(Object algorithm, CryptoKey key, Byte[] data) case "HMAC": return Hmac(key.Hash, key.Secret, data); case "ECDSA": - using (var ecdsa = key.Ec.Value.CreateEcdsa()) + using (var ecdsa = ECDsa.Create(key.Ec.Value)) { return ecdsa.SignData(data, HashName(normalized.GetHash())); } @@ -112,10 +111,10 @@ public static Boolean Verify(Object algorithm, CryptoKey key, Byte[] signature, case "HMAC": return AreEqual(Hmac(key.Hash, key.Secret, data), signature); case "ECDSA": - using (var ecdsa = key.Ec.Value.CreateEcdsa()) + using (var ecdsa = ECDsa.Create(key.Ec.Value)) { // the signature is r and s, each as long as a coordinate (IEEE P1363) - return signature.Length == 2 * EcKeyParameters.CoordinateLength(key.Curve) && + return signature.Length == 2 * CoordinateLength(key.Curve) && ecdsa.VerifyData(data, signature, HashName(normalized.GetHash())); } default: @@ -174,15 +173,21 @@ public static Object GenerateKey(Object algorithm, Boolean extractable, String[] var isEcdsa = normalized.Name == "ECDSA"; CheckUsages(usages, isEcdsa ? new[] { Sign_, Verify_ } : new[] { DeriveKey_, DeriveBits_ }); var curve = GetCurve(normalized); - var parameters = EcKeyParameters.Generate(curve); - var publicKey = CreateEcKey(normalized.Name, parameters.PublicPart, true, Intersect(usages, isEcdsa ? new[] { Verify_ } : new String[0])); - var privateKey = CreateEcKey(normalized.Name, parameters, extractable, Intersect(usages, isEcdsa ? new[] { Sign_ } : new[] { DeriveKey_, DeriveBits_ })); + ECParameters parameters; + + using (var ecdsa = ECDsa.Create(GetNamedCurve(curve))) + { + parameters = ecdsa.ExportParameters(true); + } + + var publicKey = CreateEcKey(normalized.Name, curve, PublicPart(parameters), true, Intersect(usages, isEcdsa ? new[] { Verify_ } : new String[0])); + var privateKey = CreateEcKey(normalized.Name, curve, parameters, extractable, Intersect(usages, isEcdsa ? new[] { Sign_ } : new[] { DeriveKey_, DeriveBits_ })); return CreateKeyPair(publicKey, RequireUsages(privateKey)); } default: { - var rsaUsages = GetRsaUsages(normalized.Name); - CheckUsages(usages, rsaUsages.Public.Concat(rsaUsages.Private).ToArray()); + var (publicUsages, privateUsages) = GetRsaUsages(normalized.Name); + CheckUsages(usages, publicUsages.Concat(privateUsages).ToArray()); var bits = normalized.GetInteger("modulusLength") ?? throw TypeError("The modulusLength is missing."); var exponent = normalized.GetBytes("publicExponent"); var hash = normalized.GetHash(); @@ -197,15 +202,19 @@ public static Object GenerateKey(Object algorithm, Boolean extractable, String[] try { - parameters = GenerateRsa(bits); + using (var rsa = RSA.Create()) + { + rsa.KeySize = bits; + parameters = rsa.ExportParameters(true); + } } catch (CryptographicException) { throw OperationError(); } - var publicKey = CreateRsaKey(normalized.Name, hash, PublicPart(parameters), true, Intersect(usages, rsaUsages.Public)); - var privateKey = CreateRsaKey(normalized.Name, hash, parameters, extractable, Intersect(usages, rsaUsages.Private)); + var publicKey = CreateRsaKey(normalized.Name, hash, PublicPart(parameters), true, Intersect(usages, publicUsages)); + var privateKey = CreateRsaKey(normalized.Name, hash, parameters, extractable, Intersect(usages, privateUsages)); return CreateKeyPair(publicKey, RequireUsages(privateKey)); } } @@ -282,9 +291,9 @@ public static Object ExportKey(String format, CryptoKey key) { return (Byte[])key.Secret.Clone(); } - else if (key.Ec is EcKeyParameters ec && key.Type == "public") + else if (key.Ec is ECParameters ec && key.Type == "public") { - return EncodePoint(ec); + return EncodePoint(ec, key.Curve); } throw InvalidAccessError(); @@ -490,52 +499,44 @@ private static void IncrementCounter(Byte[] block, Int32 bits) private static Byte[] AesGcmEncrypt(Algorithm algorithm, Byte[] key, Byte[] data) { #if NET8_0_OR_GREATER - var parameters = GetAesGcmParameters(algorithm); - var result = new Byte[data.Length + parameters.TagLength]; + var (iv, additionalData, tagLength) = GetAesGcmParameters(algorithm); + var result = new Byte[data.Length + tagLength]; - using (var gcm = new AesGcm(key, parameters.TagLength)) + using (var gcm = new AesGcm(key, tagLength)) { - gcm.Encrypt(parameters.Iv, data, result.AsSpan(0, data.Length), result.AsSpan(data.Length), parameters.AdditionalData); + gcm.Encrypt(iv, data, result.AsSpan(0, data.Length), result.AsSpan(data.Length), additionalData); } return result; #else - var parameters = GetAesGcmParameters(algorithm); - return ManagedAesGcm.Encrypt(key, parameters.Iv, data, parameters.AdditionalData, parameters.TagLength); + throw NotSupportedError(); #endif } private static Byte[] AesGcmDecrypt(Algorithm algorithm, Byte[] key, Byte[] data) { #if NET8_0_OR_GREATER - var parameters = GetAesGcmParameters(algorithm); + var (iv, additionalData, tagLength) = GetAesGcmParameters(algorithm); - if (data.Length < parameters.TagLength) + if (data.Length < tagLength) { throw OperationError(); } - var result = new Byte[data.Length - parameters.TagLength]; + var result = new Byte[data.Length - tagLength]; - using (var gcm = new AesGcm(key, parameters.TagLength)) + using (var gcm = new AesGcm(key, tagLength)) { - gcm.Decrypt(parameters.Iv, data.AsSpan(0, result.Length), data.AsSpan(result.Length), result, parameters.AdditionalData); + gcm.Decrypt(iv, data.AsSpan(0, result.Length), data.AsSpan(result.Length), result, additionalData); } return result; #else - var parameters = GetAesGcmParameters(algorithm); - - if (data.Length < parameters.TagLength) - { - throw OperationError(); - } - - return ManagedAesGcm.Decrypt(key, parameters.Iv, data, parameters.AdditionalData, parameters.TagLength); + throw NotSupportedError(); #endif } - private static AesGcmParameters GetAesGcmParameters(Algorithm algorithm) + private static (Byte[] Iv, Byte[] AdditionalData, Int32 TagLength) GetAesGcmParameters(Algorithm algorithm) { var iv = algorithm.GetBytes("iv"); var additionalData = algorithm.GetBytes("additionalData", false); @@ -552,7 +553,7 @@ private static AesGcmParameters GetAesGcmParameters(Algorithm algorithm) throw NotSupportedError(); } - return new AesGcmParameters(iv, additionalData, tagLength / 8); + return (iv, additionalData, tagLength / 8); } private static readonly Byte[] KeyWrapIv = { 0xA6, 0xA6, 0xA6, 0xA6, 0xA6, 0xA6, 0xA6, 0xA6 }; @@ -704,18 +705,11 @@ private static Byte[] DeriveBitsCore(Algorithm algorithm, CryptoKey key, Int32? private static Byte[] EcdhSecret(CryptoKey privateKey, CryptoKey publicKey) { -#if NET8_0_OR_GREATER || NETFRAMEWORK - try - { - return privateKey.Ec.Value.DeriveSecret(publicKey.Ec.Value); - } - catch (PlatformNotSupportedException) - { - throw NotSupportedError(); - } - catch (CryptographicException) +#if NET8_0_OR_GREATER + using (var mine = ECDiffieHellman.Create(privateKey.Ec.Value)) + using (var theirs = ECDiffieHellman.Create(publicKey.Ec.Value)) { - throw OperationError(); + return mine.DeriveRawSecretAgreement(theirs.PublicKey); } #else throw NotSupportedError(); @@ -750,18 +744,19 @@ private static Byte[] Pbkdf2(String hash, Byte[] password, Byte[] salt, Int32 it var result = new Byte[length]; var hashLength = HashLength(hash); - using (var hmac = CreateHmac(hash, password)) + using (var hmac = IncrementalHash.CreateHMAC(HashName(hash), password)) { for (var block = 1; (block - 1) * hashLength < length; block++) { - hmac.TransformBlock(salt, 0, salt.Length, null, 0); - hmac.TransformFinalBlock(new[] { (Byte)(block >> 24), (Byte)(block >> 16), (Byte)(block >> 8), (Byte)block }, 0, 4); - var u = hmac.Hash; + hmac.AppendData(salt); + hmac.AppendData(new[] { (Byte)(block >> 24), (Byte)(block >> 16), (Byte)(block >> 8), (Byte)block }); + var u = hmac.GetHashAndReset(); var t = (Byte[])u.Clone(); for (var i = 1; i < iterations; i++) { - u = hmac.ComputeHash(u); + hmac.AppendData(u); + u = hmac.GetHashAndReset(); for (var k = 0; k < t.Length; k++) { @@ -786,7 +781,7 @@ private static Byte[] Hkdf(String hash, Byte[] secret, Byte[] salt, Byte[] info, var result = new Byte[length]; var previous = new Byte[0]; - for (Int32 i = 1, offset = 0; offset < length; i++, offset += hashLength) + for (var (i, offset) = (1, 0); offset < length; i++, offset += hashLength) { var input = new Byte[previous.Length + info.Length + 1]; Buffer.BlockCopy(previous, 0, input, 0, previous.Length); @@ -859,8 +854,8 @@ private static CryptoKey ImportEcKey(String format, Byte[] data, Jwk jwk, Algori { var isEcdsa = algorithm.Name == "ECDSA"; var curve = GetCurve(algorithm); - var size = EcKeyParameters.CoordinateLength(curve); - EcKeyParameters parameters; + var size = CoordinateLength(curve); + ECParameters parameters; switch (format) { @@ -870,7 +865,11 @@ private static CryptoKey ImportEcKey(String format, Byte[] data, Jwk jwk, Algori throw DataError(); } - parameters = new EcKeyParameters(curve, Slice(data, 1, size), Slice(data, 1 + size, size), null); + parameters = new ECParameters + { + Curve = GetNamedCurve(curve), + Q = new ECPoint { X = Slice(data, 1, size), Y = Slice(data, 1 + size, size) }, + }; break; case "jwk": jwk.CheckType("EC"); @@ -886,8 +885,12 @@ private static CryptoKey ImportEcKey(String format, Byte[] data, Jwk jwk, Algori jwk.CheckAlgorithm(curve == "P-521" ? "ES512" : "ES" + curve.Substring(2)); } - var d = jwk.Get("d") != null ? jwk.GetBytes("d", size) : null; - parameters = new EcKeyParameters(curve, jwk.GetBytes("x", size), jwk.GetBytes("y", size), d); + parameters = new ECParameters + { + Curve = GetNamedCurve(curve), + Q = new ECPoint { X = jwk.GetBytes("x", size), Y = jwk.GetBytes("y", size) }, + D = jwk.Get("d") != null ? jwk.GetBytes("d", size) : null, + }; break; default: parameters = ImportEcDer(format, data, curve); @@ -896,7 +899,7 @@ private static CryptoKey ImportEcKey(String format, Byte[] data, Jwk jwk, Algori try { - using (var ecdsa = parameters.CreateEcdsa()) + using (var ecdsa = ECDsa.Create(parameters)) { // validated by the platform, e.g. that the point is on the curve } @@ -906,7 +909,7 @@ private static CryptoKey ImportEcKey(String format, Byte[] data, Jwk jwk, Algori throw DataError(); } - var isPrivate = parameters.IsPrivate; + var isPrivate = parameters.D != null; if (isPrivate) { @@ -917,10 +920,10 @@ private static CryptoKey ImportEcKey(String format, Byte[] data, Jwk jwk, Algori CheckUsages(usages, isEcdsa ? new[] { Verify_ } : new String[0]); } - return CreateEcKey(algorithm.Name, parameters, extractable, usages); + return CreateEcKey(algorithm.Name, curve, parameters, extractable, usages); } - private static EcKeyParameters ImportEcDer(String format, Byte[] data, String curve) + private static ECParameters ImportEcDer(String format, Byte[] data, String curve) { #if NET8_0_OR_GREATER try @@ -936,8 +939,8 @@ private static EcKeyParameters ImportEcDer(String format, Byte[] data, String cu ecdsa.ImportPkcs8PrivateKey(data, out _); } - var parameters = EcKeyParameters.From(ecdsa.ExportParameters(format == "pkcs8")); - return parameters?.Curve == curve ? parameters.Value : throw DataError(); + var parameters = ecdsa.ExportParameters(format == "pkcs8"); + return GetCurveName(parameters.Curve) == curve ? parameters : throw DataError(); } } catch (CryptographicException) @@ -945,26 +948,14 @@ private static EcKeyParameters ImportEcDer(String format, Byte[] data, String cu throw DataError(); } #else - EcKeyParameters parameters; - - try - { - parameters = KeyDer.ReadEc(format, data, curve); - } - catch (CryptographicException) - { - throw DataError(); - } - - // without the public point, which would have to be computed from the private key - return parameters.X != null ? parameters : throw NotSupportedError(); + throw NotSupportedError(); #endif } private static CryptoKey ImportRsaKey(String format, Byte[] data, Jwk jwk, Algorithm algorithm, Boolean extractable, String[] usages) { var hash = algorithm.GetHash(); - var rsaUsages = GetRsaUsages(algorithm.Name); + var (publicUsages, privateUsages) = GetRsaUsages(algorithm.Name); RSAParameters parameters; switch (format) @@ -1007,7 +998,7 @@ private static CryptoKey ImportRsaKey(String format, Byte[] data, Jwk jwk, Algor try { - using (var rsa = CreateRsa()) + using (var rsa = RSA.Create()) { rsa.ImportParameters(parameters); } @@ -1017,7 +1008,7 @@ private static CryptoKey ImportRsaKey(String format, Byte[] data, Jwk jwk, Algor throw DataError(); } - CheckUsages(usages, parameters.D != null ? rsaUsages.Private : rsaUsages.Public); + CheckUsages(usages, parameters.D != null ? privateUsages : publicUsages); return CreateRsaKey(algorithm.Name, hash, parameters, extractable, usages); } @@ -1045,14 +1036,7 @@ private static RSAParameters ImportRsaDer(String format, Byte[] data) throw DataError(); } #else - try - { - return KeyDer.ReadRsa(format, data); - } - catch (CryptographicException) - { - throw DataError(); - } + throw NotSupportedError(); #endif } @@ -1083,11 +1067,11 @@ private static IDictionary ExportJwk(CryptoKey key) case "ECDH": { var ec = key.Ec.Value; - var size = EcKeyParameters.CoordinateLength(key.Curve); + var size = CoordinateLength(key.Curve); jwk["kty"] = "EC"; jwk["crv"] = key.Curve; - jwk["x"] = ToBase64Url(Pad(ec.X, size)); - jwk["y"] = ToBase64Url(Pad(ec.Y, size)); + jwk["x"] = ToBase64Url(Pad(ec.Q.X, size)); + jwk["y"] = ToBase64Url(Pad(ec.Q.Y, size)); if (key.Type == "private") { @@ -1137,9 +1121,9 @@ private static Byte[] ExportDer(String format, CryptoKey key) } #if NET8_0_OR_GREATER - if (key.Ec is EcKeyParameters ec) + if (key.Ec is ECParameters ec) { - using (var ecdsa = ec.CreateEcdsa()) + using (var ecdsa = ECDsa.Create(ec)) { return isPublic ? ecdsa.ExportSubjectPublicKeyInfo() : ecdsa.ExportPkcs8PrivateKey(); } @@ -1150,7 +1134,7 @@ private static Byte[] ExportDer(String format, CryptoKey key) return isPublic ? rsa.ExportSubjectPublicKeyInfo() : rsa.ExportPkcs8PrivateKey(); } #else - return key.Ec is EcKeyParameters ec ? KeyDer.WriteEc(format, ec) : KeyDer.WriteRsa(format, key.Rsa.Value); + throw NotSupportedError(); #endif } @@ -1179,12 +1163,12 @@ private static CryptoKey CreateAesKey(String name, Byte[] data, Boolean extracta return new CryptoKey("secret", extractable, algorithm, usages) { Secret = data }; } - private static CryptoKey CreateEcKey(String name, EcKeyParameters parameters, Boolean extractable, String[] usages) + private static CryptoKey CreateEcKey(String name, String curve, ECParameters parameters, Boolean extractable, String[] usages) { var algorithm = CreateAlgorithm(name); - algorithm["namedCurve"] = parameters.Curve; - var type = parameters.IsPrivate ? "private" : "public"; - return new CryptoKey(type, extractable, algorithm, usages) { Ec = parameters, Curve = parameters.Curve }; + algorithm["namedCurve"] = curve; + var type = parameters.D != null ? "private" : "public"; + return new CryptoKey(type, extractable, algorithm, usages) { Ec = parameters, Curve = curve }; } private static CryptoKey CreateRsaKey(String name, String hash, RSAParameters parameters, Boolean extractable, String[] usages) @@ -1207,47 +1191,19 @@ private static IDictionary CreateKeyPair(CryptoKey publicKey, Cr private static Dictionary CreateAlgorithm(String name) => new Dictionary { ["name"] = name }; + private static ECParameters PublicPart(ECParameters parameters) => + new ECParameters { Curve = parameters.Curve, Q = parameters.Q }; + private static RSAParameters PublicPart(RSAParameters parameters) => new RSAParameters { Modulus = parameters.Modulus, Exponent = parameters.Exponent }; private static RSA CreateRsa(CryptoKey key) { - var rsa = CreateRsa(); + var rsa = RSA.Create(); rsa.ImportParameters(key.Rsa.Value); return rsa; } - // RSA.Create() of .NET Framework is the CryptoAPI provider, which can neither sign with - // PSS nor encrypt with OAEP of a SHA-2 hash - CNG can. - private static RSA CreateRsa() => -#if NETFRAMEWORK - new RSACng(); -#else - RSA.Create(); -#endif - - private static RSAParameters GenerateRsa(Int32 bits) - { -#if NETFRAMEWORK - // the key has to allow the export explicitly, as its private part is taken out of it - var creation = new CngKeyCreationParameters { ExportPolicy = CngExportPolicies.AllowPlaintextExport }; - creation.Parameters.Add(new CngProperty("Length", BitConverter.GetBytes(bits), CngPropertyOptions.None)); - - // RSACng duplicates the handle of the key it is given - using (var key = CngKey.Create(CngAlgorithm.Rsa, null, creation)) - using (var rsa = new RSACng(key)) - { - return rsa.ExportParameters(true); - } -#else - using (var rsa = RSA.Create()) - { - rsa.KeySize = bits; - return rsa.ExportParameters(true); - } -#endif - } - private static RSASignaturePadding GetRsaPadding(Algorithm algorithm, CryptoKey key) { if (algorithm.Name == "RSA-PSS") @@ -1298,10 +1254,10 @@ private static String GetRsaJwkAlgorithm(String name, String hash) } } - private static KeyPairUsages GetRsaUsages(String name) => + private static (String[] Public, String[] Private) GetRsaUsages(String name) => name == "RSA-OAEP" - ? new KeyPairUsages(new[] { Encrypt_, WrapKey_ }, new[] { Decrypt_, UnwrapKey_ }) - : new KeyPairUsages(new[] { Verify_ }, new[] { Sign_ }); + ? (new[] { Encrypt_, WrapKey_ }, new[] { Decrypt_, UnwrapKey_ }) + : (new[] { Verify_ }, new[] { Sign_ }); private static String[] GetAesUsages(String name) => name == "AES-KW" ? new[] { WrapKey_, UnwrapKey_ } : new[] { Encrypt_, Decrypt_, WrapKey_, UnwrapKey_ }; @@ -1319,13 +1275,57 @@ private static String GetCurve(Algorithm algorithm) return curve == "P-256" || curve == "P-384" || curve == "P-521" ? curve : throw NotSupportedError(); } - private static Byte[] EncodePoint(EcKeyParameters parameters) + private static ECCurve GetNamedCurve(String curve) { - var size = EcKeyParameters.CoordinateLength(parameters.Curve); + switch (curve) + { + case "P-256": + return ECCurve.NamedCurves.nistP256; + case "P-384": + return ECCurve.NamedCurves.nistP384; + default: + return ECCurve.NamedCurves.nistP521; + } + } + + private static String GetCurveName(ECCurve curve) + { + switch (curve.Oid?.Value) + { + case "1.2.840.10045.3.1.7": + return "P-256"; + case "1.3.132.0.34": + return "P-384"; + case "1.3.132.0.35": + return "P-521"; + } + + switch (curve.Oid?.FriendlyName) + { + case "nistP256": + case "ECDSA_P256": + return "P-256"; + case "nistP384": + case "ECDSA_P384": + return "P-384"; + case "nistP521": + case "ECDSA_P521": + return "P-521"; + } + + return null; + } + + private static Int32 CoordinateLength(String curve) => + curve == "P-256" ? 32 : curve == "P-384" ? 48 : 66; + + private static Byte[] EncodePoint(ECParameters parameters, String curve) + { + var size = CoordinateLength(curve); var result = new Byte[1 + 2 * size]; result[0] = 4; - Buffer.BlockCopy(Pad(parameters.X, size), 0, result, 1, size); - Buffer.BlockCopy(Pad(parameters.Y, size), 0, result, 1 + size, size); + Buffer.BlockCopy(Pad(parameters.Q.X, size), 0, result, 1, size); + Buffer.BlockCopy(Pad(parameters.Q.Y, size), 0, result, 1 + size, size); return result; } @@ -1460,48 +1460,19 @@ private static Int32 BlockBits(String hash) => private static Byte[] Hash(String hash, Byte[] data) { - using (var algorithm = CreateHash(hash)) + using (var algorithm = IncrementalHash.CreateHash(HashName(hash))) { - return algorithm.ComputeHash(data); + algorithm.AppendData(data); + return algorithm.GetHashAndReset(); } } private static Byte[] Hmac(String hash, Byte[] key, Byte[] data) { - using (var algorithm = CreateHmac(hash, key)) - { - return algorithm.ComputeHash(data); - } - } - - // Not IncrementalHash, which .NET Framework 4.6.2 does not have. - private static HashAlgorithm CreateHash(String hash) - { - switch (hash) - { - case "SHA-1": - return SHA1.Create(); - case "SHA-256": - return SHA256.Create(); - case "SHA-384": - return SHA384.Create(); - default: - return SHA512.Create(); - } - } - - private static HMAC CreateHmac(String hash, Byte[] key) - { - switch (hash) + using (var algorithm = IncrementalHash.CreateHMAC(HashName(hash), key)) { - case "SHA-1": - return new HMACSHA1(key); - case "SHA-256": - return new HMACSHA256(key); - case "SHA-384": - return new HMACSHA384(key); - default: - return new HMACSHA512(key); + algorithm.AppendData(data); + return algorithm.GetHashAndReset(); } } @@ -1602,41 +1573,6 @@ private static Exception TypeError(String message) => #region Nested types - /// - /// The usages the public and the private key of a pair may have. - /// - private readonly struct KeyPairUsages - { - public KeyPairUsages(String[] @public, String[] @private) - { - Public = @public; - Private = @private; - } - - public String[] Public { get; } - - public String[] Private { get; } - } - - /// - /// The parameters of AES-GCM, with the length of the tag in bytes. - /// - private readonly struct AesGcmParameters - { - public AesGcmParameters(Byte[] iv, Byte[] additionalData, Int32 tagLength) - { - Iv = iv; - AdditionalData = additionalData; - TagLength = tagLength; - } - - public Byte[] Iv { get; } - - public Byte[] AdditionalData { get; } - - public Int32 TagLength { get; } - } - /// /// A normalized algorithm: its name, and the object of a script with its parameters. /// From bf9edd0b39f2fbd6a732675bd0e192ab07558ee1 Mon Sep 17 00:00:00 2001 From: Florian Rappl Date: Mon, 23 Nov 2026 09:34:47 +0100 Subject: [PATCH 10/19] Adjusted notation --- src/AngleSharp.Js/AngleSharp.Js.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/AngleSharp.Js/AngleSharp.Js.csproj b/src/AngleSharp.Js/AngleSharp.Js.csproj index 13364435..a5ebeafe 100644 --- a/src/AngleSharp.Js/AngleSharp.Js.csproj +++ b/src/AngleSharp.Js/AngleSharp.Js.csproj @@ -27,7 +27,7 @@ - + From 004d5f135bc21a5737664f3da5fc24a38a23a9bb Mon Sep 17 00:00:00 2001 From: Florian Rappl Date: Mon, 23 Nov 2026 10:10:30 +0100 Subject: [PATCH 11/19] Adjusted message for .NET 4.6.2 --- src/AngleSharp.Js.Tests/Html5TestTests.cs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/AngleSharp.Js.Tests/Html5TestTests.cs b/src/AngleSharp.Js.Tests/Html5TestTests.cs index d3616658..8cd1e3f0 100644 --- a/src/AngleSharp.Js.Tests/Html5TestTests.cs +++ b/src/AngleSharp.Js.Tests/Html5TestTests.cs @@ -28,8 +28,10 @@ public async Task Html5TestShouldProduceScoreWithoutScriptErrors() TestContext.WriteLine("HTML5test score: {0}", score.TextContent); Assert.Greater(Double.Parse(score.TextContent, CultureInfo.InvariantCulture), 0.0, failureMessage); // AngleSharp.Io before 1.4.0 (the one of these tests) rejects the fetch('') of the page, - // instead of fetching the address of the document. - errors.RemoveAll(error => error.Message.Contains("Value cannot be null. (Parameter 'url')")); + // instead of fetching the address of the document. The message is taken from the runtime, + // as .NET Framework words it differently ("Parameter name: url"). + var nullUrl = new ArgumentNullException("url").Message; + errors.RemoveAll(error => error.Message.Contains(nullUrl)); Assert.IsEmpty(errors, failureMessage); } From 57f1bd89a34e3643df8e9d8794c85f263ea3959a Mon Sep 17 00:00:00 2001 From: Florian Rappl Date: Mon, 23 Nov 2026 14:00:05 +0100 Subject: [PATCH 12/19] Fixed unrelated type resolution --- CHANGELOG.md | 1 + src/AngleSharp.Js.Tests/InteropTests.cs | 24 +++++++++++++++++++ src/AngleSharp.Js/Cache/PrototypeTypeCache.cs | 6 ++++- 3 files changed, 30 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fc05b407..ccb940fd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ Released on tbd. - Fixed import map entries of a prefix not being used - Fixed an `import()` of a module that could not be fetched not rejecting with a `TypeError` - Fixed the DOM of libraries registered by a creator only being missing +- Fixed an object getting the prototype of an unrelated class of another library - Updated a WebIDL namespace to be a plain object, whose members are no longer members of the window too - Added `SharedWorker`, which the scripts of an origin creating it for the same address - Added CSS module scripts (`import sheet from './a.css' with { type: 'css' }`), whose default export is a constructed style sheet diff --git a/src/AngleSharp.Js.Tests/InteropTests.cs b/src/AngleSharp.Js.Tests/InteropTests.cs index 08db1adc..bb6cf144 100644 --- a/src/AngleSharp.Js.Tests/InteropTests.cs +++ b/src/AngleSharp.Js.Tests/InteropTests.cs @@ -47,6 +47,16 @@ public async Task NamespaceIsAnObjectWithItsMembersAndInterfaces() Assert.AreEqual("ok:object,[object Interop],42,function,5,true,undefined,false,-1", result); } + [Test] + public async Task ObjectNamedLikeAnUnrelatedClassOfAnotherLibraryKeepsItsMembers() + { + // the CanvasGradient of a canvas got the prototype of the one of CSS paint worklets, + // whose addColorStop could not be invoked on it + var result = await Run("var own = Interop.ownLocation(); return [own.describe(), typeof own.reload, own instanceof Location].join();"); + + Assert.AreEqual("ok:own,undefined,false", result); + } + [Test] public async Task DelegateIsAFunction() { @@ -143,6 +153,17 @@ public sealed class InteropService { } + /// + /// Named like the Location of AngleSharp, but unrelated to it. + /// + [DomName("Location")] + [DomNoInterfaceObject] + public sealed class OwnLocation + { + [DomName("describe")] + public String Describe() => "own"; + } + public delegate Object Variadic(Object[] arguments); [DomName("Interop")] @@ -153,6 +174,9 @@ public static class InteropNamespace private static readonly Func Add = (a, b) => a + b; private static readonly Variadic Join = arguments => String.Join("|", Array.ConvertAll(arguments, m => m == System.Reflection.Missing.Value ? "Missing" : m.GetType().Name + ":" + m)); + [DomName("ownLocation")] + public static OwnLocation CreateOwnLocation() => new OwnLocation(); + [DomName("twice")] public static Double Twice(this IWindow window, Double value) => 2 * value; diff --git a/src/AngleSharp.Js/Cache/PrototypeTypeCache.cs b/src/AngleSharp.Js/Cache/PrototypeTypeCache.cs index b2ddfdcb..025477b6 100644 --- a/src/AngleSharp.Js/Cache/PrototypeTypeCache.cs +++ b/src/AngleSharp.Js/Cache/PrototypeTypeCache.cs @@ -102,7 +102,11 @@ public static Type GetDomPrototypeType(this Type type, IEnumerable lib { foreach (var lib in libs) { - if (GetDefiningTypes(lib).TryGetValue(name, out var definingType)) + // Unrelated classes of different libraries may carry the same name (the + // CanvasGradient of CSS paint worklets and the one of a canvas); a member + // of one cannot be invoked on the other, so each keeps its own prototype. + if (GetDefiningTypes(lib).TryGetValue(name, out var definingType) && + (definingType.IsAssignableFrom(type) || type.IsAssignableFrom(definingType))) { return definingType; } From ebacd45738613dda458f68a62c3916e18b8d0664 Mon Sep 17 00:00:00 2001 From: Florian Rappl Date: Mon, 23 Nov 2026 14:20:29 +0100 Subject: [PATCH 13/19] Improved docs --- docs/README.md | 3 + docs/general/01-Basics.md | 73 ++++--- docs/tutorials/01-API.md | 246 ++++++++++++++++++++++- docs/tutorials/02-Examples.md | 350 ++++++++++++++++++++++++++++++++- docs/tutorials/03-Questions.md | 113 ++++++++++- 5 files changed, 742 insertions(+), 43 deletions(-) diff --git a/docs/README.md b/docs/README.md index 29d9695b..4552d353 100644 --- a/docs/README.md +++ b/docs/README.md @@ -3,3 +3,6 @@ We have more detailed information regarding the following subjects: - [Getting Started](general/01-Basics.md) +- [API Documentation](tutorials/01-API.md) +- [Examples](tutorials/02-Examples.md) +- [Frequently Asked Questions](tutorials/03-Questions.md) diff --git a/docs/general/01-Basics.md b/docs/general/01-Basics.md index 99931621..953c33a2 100644 --- a/docs/general/01-Basics.md +++ b/docs/general/01-Basics.md @@ -4,11 +4,7 @@ section: "AngleSharp.Js" --- # Getting Started -AngleSharp.Js runs JavaScript against an AngleSharp document. It integrates the -[Jint](https://github.com/sebastienros/jint) interpreter with AngleSharp, so scripts can -read and change the same DOM that your .NET code uses. This is useful when processing pages -whose behavior depends on script execution, evaluating a snippet in a document context, or -hosting JavaScript APIs alongside your application. +AngleSharp.Js runs JavaScript against an AngleSharp document. It integrates the [Jint](https://github.com/sebastienros/jint) interpreter with AngleSharp, so scripts can read and change the same DOM that your .NET code uses. This is useful when processing pages whose behavior depends on script execution, evaluating a snippet in a document context, or hosting JavaScript APIs alongside your application. ## Install and configure @@ -18,13 +14,9 @@ Install the package: Install-Package AngleSharp.Js ``` -Add `WithJs()` to the AngleSharp configuration. Add `WithEventLoop()` when scripts, events, -or resource callbacks must run in the browser-like task queue. Add a loader when the document -needs to fetch external scripts or other resources. +Add `WithJs()` to the AngleSharp configuration. Add `WithEventLoop()` when scripts, events, or resource callbacks must run in the browser-like task queue. Add a loader when the document needs to fetch external scripts or other resources. -For many real-world scripts, `WithJs()` alone is not enough. AngleSharp.Js exposes interfaces -from the AngleSharp services present in the browsing context, so you usually want to include -AngleSharp.Io and AngleSharp.Css to provide most of the required API surface. +For many real-world scripts, `WithJs()` alone is not enough. AngleSharp.Js exposes interfaces from the AngleSharp services present in the browsing context, so you usually want to include AngleSharp.Io and AngleSharp.Css to provide most of the required API surface. ```cs var configuration = Configuration.Default @@ -42,12 +34,9 @@ var document = await context.OpenAsync("https://example.com"); await document.WaitUntilAvailable(); ``` -Some highly specialized scripts may also depend on additional AngleSharp packages. For example, -in niche scenarios, libraries such as AngleSharp.Wasm can be relevant. +Some highly specialized scripts may also depend on additional AngleSharp packages. For example, in niche scenarios, libraries such as AngleSharp.Wasm can be relevant. -`WithJs()` registers the JavaScript scripting service, support for inline event attributes -such as `onclick`, a navigation handler for `javascript:` URLs, and a default `navigator` -when the configuration does not already provide one. +`WithJs()` registers the JavaScript scripting service, support for inline event attributes such as `onclick`, a navigation handler for `javascript:` URLs, structured cloning (for `postMessage` and workers) and the host for custom elements. It does not register a loader, an event loop or a navigator; `WithNavigator()` from AngleSharp.Io provides a full `navigator`. ### Customize the event loop @@ -93,11 +82,21 @@ var configuration = Configuration.Default }); ``` +### Configure the Jint engine + +Register an `EngineCreator` to construct the Jint engine yourself, for example to limit the statements, time or memory a script may use. The delegate runs once per window and must build the engine from the supplied options: + +```cs +var configuration = Configuration.Default + .With(new EngineCreator((window, options) => new Jint.Engine(options + .MaxStatements(1_000_000) + .TimeoutInterval(TimeSpan.FromSeconds(5))))) + .WithJs(); +``` + ## Execute JavaScript -HTML `")) + .WaitUntilAvailable(); + +var output = document.GetElementById("out").TextContent; // "2,4,6" +``` + +## Interact with the page: click, then inspect + +Events dispatched from .NET reach JavaScript listeners, and the other way round. + +```cs +var config = Configuration.Default.WithJs().WithEventLoop(); +var document = await BrowsingContext.New(config).OpenAsync(req => req.Content(@" + 0 + ")) + .WaitUntilAvailable(); + +var button = (IHtmlElement)document.GetElementById("btn"); // AngleSharp.Html.Dom +button.DoClick(); +button.DoClick(); + +await document.WhenStable(); +var clicks = document.GetElementById("n").TextContent; // "2" +``` + +Inline handlers such as `