Lightpanda: the headless browser designed for AI and automation
webapi: generateKey/importKey normalize their algorithm by name
orezraey06414423dd84
diff --git a/src/browser/tests/crypto.html b/src/browser/tests/crypto.htmlindex 93abac9a4..b6c596a31 100644--- a/src/browser/tests/crypto.html+++ b/src/browser/tests/crypto.html@@ -2438,6 +2438,98 @@});</script>+<script id=generate-import-by-name type=module>+ const state = await testing.async();+ const subtle = crypto.subtle;+ const outcome = async (fn) => {+ try {+ const r = await fn();+ return r instanceof CryptoKey ? `${r.type}:${r.algorithm.name}` : `pair:${r.privateKey.algorithm.name}`;+ } catch (err) {+ return err.name;+ }+ };+ const e = new Uint8Array([1, 0, 1]);+ const raw = new Uint8Array(16);+ const ec = await subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, ["sign", "verify"]);+ const spki = await subtle.exportKey("spki", ec.publicKey);+ const aes = await subtle.generateKey({ name: "AES-GCM", length: 128 }, true, ["encrypt"]);+ const kw = await subtle.generateKey({ name: "AES-KW", length: 128 }, true, ["wrapKey", "unwrapKey"]);+ const wrapped = await subtle.wrapKey("raw", aes, kw, "AES-KW");+ const gen = (algo, usages) => outcome(() => subtle.generateKey(algo, true, usages));++ // The name picks the algorithm, then its params are read: another+ // algorithm's member is ignored, a missing one of its own is a TypeError,+ // and an [EnforceRange] one out of range is a TypeError too.+ const results = {+ genAesStrayHash: await gen({ name: "AES-GCM", length: 128, hash: "SHA-256" }, ["encrypt"]),+ genEd25519StrayHash: await gen({ name: "Ed25519", hash: "SHA-256" }, ["sign"]),+ genEd25519StrayCurve: await gen({ name: "Ed25519", namedCurve: "P-256" }, ["sign"]),+ genX25519StrayCurve: await gen({ name: "X25519", namedCurve: "P-256" }, ["deriveBits"]),+ genHmacStrayCurve: await gen({ name: "HMAC", hash: "SHA-256", namedCurve: "P-256" }, ["sign"]),+ genAesLengthWrapped: await gen({ name: "AES-GCM", length: 2 ** 32 + 128 }, ["encrypt"]),+ genAesLengthOverShort: await gen({ name: "AES-GCM", length: 2 ** 16 + 128 }, ["encrypt"]),+ genAesLengthNegative: await gen({ name: "AES-GCM", length: -1 }, ["encrypt"]),+ genAesLengthFraction: await gen({ name: "AES-GCM", length: 128.9 }, ["encrypt"]),+ genAesNoLength: await gen({ name: "AES-GCM" }, ["encrypt"]),+ genHmacNoHash: await gen({ name: "HMAC" }, ["sign"]),+ genEcdsaNoCurve: await gen({ name: "ECDSA" }, ["sign"]),+ genRsaNoModulus: await gen({ name: "RSA-OAEP", hash: "SHA-256", publicExponent: e }, ["encrypt"]),+ // The hash is normalized with the algorithm, before the usages.+ genRsaBadHashBadUsage: await gen({ name: "RSA-OAEP", hash: "SHA-999", modulusLength: 2048, publicExponent: e }, ["sign"]),+ genHmacBadHashBadUsage: await gen({ name: "HMAC", hash: "SHA-999" }, ["encrypt"]),+ // Anything but an object converts to a name: an unknown one.+ genNumber: await gen(5, ["sign"]),+ genNull: await gen(null, ["sign"]),+ genHkdf: await gen("HKDF", ["deriveBits"]),+ importEcdsaStrayHash: await outcome(() => subtle.importKey("spki", spki, { name: "ECDSA", namedCurve: "P-256", hash: "SHA-256" }, true, ["verify"])),+ importAesStrayCurve: await outcome(() => subtle.importKey("raw", raw, { name: "AES-GCM", namedCurve: "P-256" }, true, ["encrypt"])),+ importEcdsaNoCurve: await outcome(() => subtle.importKey("spki", spki, { name: "ECDSA" }, true, ["verify"])),+ importHmacNoHash: await outcome(() => subtle.importKey("raw", raw, "HMAC", true, ["sign"])),+ importRsaBadHashBadUsage: await outcome(() => subtle.importKey("spki", spki, { name: "RSA-OAEP", hash: "SHA-999" }, true, ["sign"])),+ importUnknown: await outcome(() => subtle.importKey("raw", raw, "foo", true, ["encrypt"])),+ // unwrapKey normalizes the unwrapped key's algorithm before the key checks.+ unwrapUnknownWrongKey: await outcome(() => subtle.unwrapKey("raw", wrapped, aes, "AES-KW", "foo", true, ["encrypt"])),+ unwrapAesStrayHash: await outcome(() => subtle.unwrapKey("raw", wrapped, kw, "AES-KW", { name: "AES-GCM", hash: "SHA-256" }, true, ["encrypt"])),+ };+ const expected = {+ genAesStrayHash: "secret:AES-GCM",+ genEd25519StrayHash: "pair:Ed25519",+ genEd25519StrayCurve: "pair:Ed25519",+ genX25519StrayCurve: "pair:X25519",+ genHmacStrayCurve: "secret:HMAC",+ genAesLengthWrapped: "TypeError",+ genAesLengthOverShort: "TypeError",+ genAesLengthNegative: "TypeError",+ genAesLengthFraction: "secret:AES-GCM",+ genAesNoLength: "TypeError",+ genHmacNoHash: "TypeError",+ genEcdsaNoCurve: "TypeError",+ genRsaNoModulus: "TypeError",+ genRsaBadHashBadUsage: "NotSupportedError",+ genHmacBadHashBadUsage: "NotSupportedError",+ genNumber: "NotSupportedError",+ genNull: "NotSupportedError",+ genHkdf: "NotSupportedError",+ importEcdsaStrayHash: "public:ECDSA",+ importAesStrayCurve: "secret:AES-GCM",+ importEcdsaNoCurve: "TypeError",+ importHmacNoHash: "TypeError",+ importRsaBadHashBadUsage: "NotSupportedError",+ importUnknown: "NotSupportedError",+ unwrapUnknownWrongKey: "NotSupportedError",+ unwrapAesStrayHash: "secret:AES-GCM",+ };++ state.resolve();+ await state.done(() => {+ // Compared with the case name, so a failure says which one.+ for (const [name, want] of Object.entries(expected)) {+ testing.expectEqual(`${name}: ${want}`, `${name}: ${results[name]}`);+ }+ });+</script>+<script id="digest" type=module>const state = await testing.async();async function hash(algo, data) {diff --git a/src/browser/webapi/SubtleCrypto.zig b/src/browser/webapi/SubtleCrypto.zigindex 99ac92365..5de7a20b5 100644--- a/src/browser/webapi/SubtleCrypto.zig+++ b/src/browser/webapi/SubtleCrypto.zig@@ -35,7 +35,6 @@ const OKP = @import("crypto/OKP.zig");const common = @import("crypto/common.zig");const log = lp.log;-const String = lp.String;const Execution = js.Execution;const missing_name = algorithm.missing_name;@@ -50,30 +49,27 @@ _pad: bool = false,/// Generate a new key (for symmetric algorithms) or key pair (for public-key algorithms).pub fn generateKey(_: *const SubtleCrypto,- algo: algorithm.Init,+ algo_value: js.Value,extractable: bool,key_usages: []const []const u8,exec: *const Execution,) !js.Promise {- const local = exec.js.local.?;- switch (algo) {+ switch (try algorithm.Init.fromJs(algo_value, exec.js.local.?)) {.hmac_key_gen => |params| return HMAC.init(params, extractable, key_usages, exec),.aes_key_gen => |params| return AES.generate(params, extractable, key_usages, exec),.ec_key_gen => |params| return EC.generate(params, extractable, key_usages, exec),.rsa_hashed_key_gen => |params| return RSA.generate(params, extractable, key_usages, exec),- .name => |js_name| return generateKeyFromName(try js_name.toSSO(false), extractable, key_usages, exec),- .object => |object| return generateKeyFromName(try object.name.toSSO(false), extractable, key_usages, exec),- .invalid => return local.typeError("invalid algorithm"),+ .named => |name| return generateKeyFromName(name, extractable, key_usages, exec),}}fn generateKeyFromName(- name: String,+ name: []const u8,extractable: bool,key_usages: []const []const u8,exec: *const Execution,) !js.Promise {- if (OKP.curveOf(name.str())) |curve| {+ if (OKP.curveOf(name)) |curve| {return OKP.generate(curve, extractable, key_usages, exec);}@@ -83,11 +79,10 @@ fn generateKeyFromName(// error name; leaves real key generation to a future change.const allowed: []const []const u8 = blk: {- const str = name.str();- if (eqlIgnoreCase(str, "Ed448")) {+ if (eqlIgnoreCase(name, "Ed448")) {break :blk &.{ "sign", "verify" };}- if (eqlIgnoreCase(str, "X448")) {+ if (eqlIgnoreCase(name, "X448")) {break :blk &.{ "deriveKey", "deriveBits" };}return error.NotSupported;@@ -118,6 +113,20 @@ fn generateKeyFromName(/// Imports a key from an external, portable format and returns a `CryptoKey`.pub fn importKey(_: *const SubtleCrypto,+ format: []const u8,+ key_data: algorithm.KeyData,+ algo_value: js.Value,+ extractable: bool,+ key_usages: []const []const u8,+ exec: *const Execution,+) !js.Promise {+ const algo = try algorithm.Import.fromJs(algo_value, exec.js.local.?);+ return importNormalized(format, key_data, algo, extractable, key_usages, exec);+}++/// importKey, once its algorithm is normalized: unwrapKey normalizes the+/// unwrapped key's algorithm itself, before unwrapping.+fn importNormalized(format: []const u8,key_data: algorithm.KeyData,algo: algorithm.Import,@@ -126,7 +135,7 @@ pub fn importKey(exec: *const Execution,) !js.Promise {const local = exec.js.local.?;- const name = algo.algoName() orelse return local.typeError(missing_name);+ const name = algo.algoName();// Asymmetric algorithms (EC, OKP). Usage validation runs first (bad/empty// usages → SyntaxError) so the failure-path tests pass regardless of whether@@ -162,7 +171,7 @@ pub fn importKey(}}if (RSA.scheme(name)) |scheme| {- const hash_name = try importHash(algo, local) orelse return local.typeError("RSA import requires a hash");+ const hash_name = (try algo.hash(local)).?;const is_jwk = std.mem.eql(u8, format, "jwk");switch (key_data) {.bytes => |b| {@@ -190,8 +199,8 @@ pub fn importKey(return AES.importJwk(name, jwk, extractable, key_usages, exec);}if (eqlIgnoreCase(name, "HMAC")) {- const length = try HMAC.lengthParam(importLength(algo), local);- const hash_name = try importHash(algo, local) orelse return local.typeError("HMAC import requires a hash");+ const length = try HMAC.lengthParam(algo.length(), local);+ const hash_name = (try algo.hash(local)).?;return HMAC.importJwk(hash_name, jwk, length, extractable, key_usages, exec);}// HKDF and PBKDF2 keys only come in "raw".@@ -233,8 +242,8 @@ pub fn importKey(}}if (eqlIgnoreCase(name, "HMAC")) {- const length = try HMAC.lengthParam(importLength(algo), local);- const hash_name = try importHash(algo, local) orelse return local.typeError("HMAC import requires a hash");+ const length = try HMAC.lengthParam(algo.length(), local);+ const hash_name = (try algo.hash(local)).?;return HMAC.import(hash_name, raw, length, extractable, key_usages, exec);}@@ -242,25 +251,6 @@ pub fn importKey(return error.NotSupported;}-/// The hash of an importKey algorithm that carries one (HMAC, RSA): those-/// params {name, hash} match the `.hmac` variant of the Import union (same-/// shape), so the hash is read there. Null for the other variants.-fn importHash(algo: algorithm.Import, local: *const js.Local) !?[]const u8 {- return switch (algo) {- .hmac => |h| try h.hash.name(local),- else => null,- };-}--/// The `length` member of an HMAC importKey algorithm, unconverted (see-/// HMAC.lengthParam). Null when absent, or for the other variants.-fn importLength(algo: algorithm.Import) ?js.Value {- return switch (algo) {- .hmac => |h| h.length,- else => null,- };-}-/// Whether the requested format/key-data describe a private key. The format/// alone decides for DER/raw variants; for JWK the presence of `d` marks it.fn importKind(format: []const u8, key_data: algorithm.KeyData) bool {@@ -576,28 +566,20 @@ pub fn wrapKey(/// Unwraps a key: decrypts `wrapped_key` with `unwrapping_key` (or unwraps it/// with AES-KW) and imports the result in `format`, a JWK being its JSON text.pub fn unwrapKey(- self: *const SubtleCrypto,+ _: *const SubtleCrypto,format: []const u8,wrapped_key: js.TypedArray(u8),unwrapping_key: *CryptoKey,algo: algorithm.Encrypt,- unwrapped_key_algo: algorithm.Import,+ unwrapped_key_value: js.Value,extractable: bool,key_usages: []const []const u8,exec: *const Execution,) !js.Promise {const local = exec.js.local.?;const name = try wrapAlgorithmName(algo, local);- // The unwrapped key's algorithm is normalized next, before the key checks:- // its name and, for HMAC and RSA, which take one, a known hash. Another- // algorithm's stray `hash` is ignored, as importKey does.- const unwrapped_name = unwrapped_key_algo.algoName() orelse return local.typeError(missing_name);- if (eqlIgnoreCase(unwrapped_name, "HMAC") or RSA.scheme(unwrapped_name) != null) {- const hash_name = try importHash(unwrapped_key_algo, local) orelse return local.typeError("the unwrapped key's algorithm requires a hash");- if (common.canonicalHash(hash_name) == null) {- return error.NotSupported;- }- }+ // The unwrapped key's algorithm is normalized next, before the key checks.+ const unwrapped_key_algo = try algorithm.Import.fromJs(unwrapped_key_value, local);try checkWrappingKey(name, unwrapping_key, .unwrap);const bytes = try cryptBytes(algo, unwrapping_key, wrapped_key.values, .unwrap, exec);@@ -607,7 +589,7 @@ pub fn unwrapKey(.{ .bytes = .{ .values = bytes } };// importKey rejects a secret or private key with no usages (SyntaxError),// the last check unwrapKey asks for.- return self.importKey(format, key_data, unwrapped_key_algo, extractable, key_usages, exec);+ return importNormalized(format, key_data, unwrapped_key_algo, extractable, key_usages, exec);}/// What `cryptBytes` is for, which decides the direction and the usage the keydiff --git a/src/browser/webapi/crypto/AES.zig b/src/browser/webapi/crypto/AES.zigindex cbee981f5..0084beda3 100644--- a/src/browser/webapi/crypto/AES.zig+++ b/src/browser/webapi/crypto/AES.zig@@ -67,7 +67,8 @@ pub fn validate(params: algorithm.Init.AesKeyGen, key_usages: []const []const u8}}- if (params.length != 128 and params.length != 192 and params.length != 256) {+ const length = params.length.value;+ if (length != 128 and length != 192 and length != 256) {return error.OperationError;}@@ -90,7 +91,7 @@ pub fn generate(const allowed = allowedUsages(params.name).?;const mask = common.usageMask(allowed, key_usages) catch unreachable;- const key = try exec.local_arena.alloc(u8, params.length / 8);+ const key = try exec.local_arena.alloc(u8, params.length.value / 8);const res = crypto.RAND_bytes(key.ptr, key.len);lp.assert(res == 1, "AES.generate", .{ .res = res });diff --git a/src/browser/webapi/crypto/RSA.zig b/src/browser/webapi/crypto/RSA.zigindex 9aa19475b..9a5a01bca 100644--- a/src/browser/webapi/crypto/RSA.zig+++ b/src/browser/webapi/crypto/RSA.zig@@ -149,12 +149,6 @@ fn hashOfJwkAlg(s: *const Scheme, alg: []const u8) ?[]const u8 {const max_modulus_length = 4096;-/// RsaKeyGenParams' `modulusLength`, an [EnforceRange] unsigned long: a value-/// outside u32 (NaN, undefined, the infinities) is a TypeError.-fn modulusLength(params: algorithm.Init.RsaHashedKeyGen, local: *const js.Local) !u32 {- return js.enforceRange(u32, try params.modulusLength.toF64()) catch local.typeError("modulusLength is out of range");-}-/// Generates an RSA key pair of `modulusLength` bits with the given public/// exponent. Mirrors EC.generate: each key keeps the EVP_PKEY of its half, and/// the requested usages are split across the pair (validate() rejected illegal@@ -169,7 +163,7 @@ pub fn generate(// Normalization: the algorithm name, then the dictionary's members, then// the hash (validate). The usages come after.const s = scheme(params.name) orelse return error.NotSupported;- const requested_bits = try modulusLength(params, local);+ const requested_bits = params.modulusLength.value;const requested_hash = try params.hash.name(local);try validate(params, requested_hash, key_usages);diff --git a/src/browser/webapi/crypto/algorithm.zig b/src/browser/webapi/crypto/algorithm.zigindex a4395ace0..de71aa946 100644--- a/src/browser/webapi/crypto/algorithm.zig+++ b/src/browser/webapi/crypto/algorithm.zig@@ -52,45 +52,62 @@ pub const Hash = union(enum) {}};-/// Passed for `generateKey()`.+/// Algorithm for `generateKey()`, normalized as the spec does: its name picks+/// the algorithm (an unknown one is NotSupportedError), then the value is+/// converted to that algorithm's params dictionary (a TypeError without a+/// required member or out of an [EnforceRange] member's range). Taken as a+/// js.Value, not probed by shape, so another algorithm's member (a `hash` on+/// AES, a `namedCurve` on Ed25519) is ignored.pub const Init = union(enum) {/// For RSASSA-PKCS1-v1_5, RSA-PSS, or RSA-OAEP: pass an RsaHashedKeyGenParams object.rsa_hashed_key_gen: RsaHashedKeyGen,- /// Must be before `hmac_key_gen`, since we need to ignore this param even- /// if it has a 'hash' property, and if it's after, we'll match that instead.ec_key_gen: EcKeyGen,/// For HMAC: pass an HmacKeyGenParams object.hmac_key_gen: HmacKeyGen,/// For AES variants: pass an AesKeyGenParams object.aes_key_gen: AesKeyGen,-- /// don't use []const u8 here, we don't want non-strings coerced. Let those- /// fall to the invalid case- /// Can be Ed25519 or X25519.- object: struct { name: js.String },- /// Can be Ed25519 or X25519.- name: js.String,-- invalid: js.Value,+ /// An algorithm whose params are just its name (Ed25519, X25519, Ed448,+ /// X448), as the caller spelled it.+ named: []const u8,++ pub fn fromJs(value: js.Value, local: *const js.Local) !Init {+ const name = try identifierName(value, local);+ if (isOneOf(name, &.{ "RSASSA-PKCS1-v1_5", "RSA-PSS", "RSA-OAEP" })) {+ const params = try convert(RsaHashedKeyGen, value, local);+ _ = try params.hash.canonical(local);+ return .{ .rsa_hashed_key_gen = params };+ }+ if (isOneOf(name, &.{ "ECDSA", "ECDH" })) {+ return .{ .ec_key_gen = try convert(EcKeyGen, value, local) };+ }+ if (isOneOf(name, &.{"HMAC"})) {+ const params = try convert(HmacKeyGen, value, local);+ _ = try params.hash.canonical(local);+ return .{ .hmac_key_gen = params };+ }+ if (isOneOf(name, &.{ "AES-CTR", "AES-CBC", "AES-GCM", "AES-KW" })) {+ return .{ .aes_key_gen = try convert(AesKeyGen, value, local) };+ }+ if (isOneOf(name, &.{ "Ed25519", "X25519", "Ed448", "X448" })) {+ return .{ .named = name };+ }+ return error.NotSupported;+ }/// https://developer.mozilla.org/en-US/docs/Web/API/RsaHashedKeyGenParamspub const RsaHashedKeyGen = struct {hash: Hash,/// This should be at least 2048./// Some organizations are now recommending that it should be 4096.- /// An [EnforceRange] unsigned long, kept as a value: this dictionary- /// is probed before the others, so converting it here would reject- /// another algorithm's object that happens to carry one. RSA's- /// generateKey converts it (RSA.modulusLength). It stays required, so- /// an object without one is probed as the other dictionaries.- modulusLength: js.Value,+ modulusLength: js.EnforceRange(u32),name: []const u8,publicExponent: js.TypedArray(u8),};/// https://developer.mozilla.org/en-US/docs/Web/API/AesKeyGenParamspub const AesKeyGen = struct {- length: u32,+ /// An [EnforceRange] unsigned short.+ length: js.EnforceRange(u16),name: []const u8,};@@ -105,9 +122,8 @@ pub const Init = union(enum) {/// Its also possible to pass this in an object.hash: Hash,/// If omitted, default is the block size of the chosen hash function.- /// An [EnforceRange] unsigned long, kept as a value: HMAC.init converts- /// it (HMAC.lengthParam) once the name is known to be HMAC's, since- /// another algorithm's object can be probed into this dictionary.+ /// An [EnforceRange] unsigned long, kept as a value for HMAC.lengthParam,+ /// which converts null to 0 as WebIDL does rather than to no length.length: ?js.Value = null,/// Always HMAC.name: []const u8,@@ -130,8 +146,7 @@ pub const Derive = union(enum) {ecdh_or_x25519: Init.EcdhKeyDeriveParams,pub fn fromJs(value: js.Value, local: *const js.Local) !Derive {- const identifier = try convert(Hash, value, local);- const name = try identifier.name(local);+ const name = try identifierName(value, local);if (std.ascii.eqlIgnoreCase(name, "PBKDF2")) {const params = try convert(Pbkdf2Params, value, local);_ = try params.hash.canonical(local);@@ -148,15 +163,6 @@ pub const Derive = union(enum) {return error.NotSupported;}- /// `value` as `T`. A value that isn't one (a string for a dictionary, a- /// missing member) is a TypeError; the page's own exception stays pending.- fn convert(comptime T: type, value: js.Value, local: *const js.Local) !T {- return local.jsValueToZig(T, value) catch |err| switch (err) {- error.JsException, error.OutOfMemory => err,- else => local.typeError("algorithm is missing a required member"),- };- }-pub const Pbkdf2Params = struct {hash: Hash,/// An [EnforceRange] unsigned long: converted once the name is known@@ -188,32 +194,49 @@ pub const DerivedKey = union(enum) {name: []const u8,};-/// Algorithm passed to `importKey()`. HMAC carries a hash, so it must be probed-/// before the bare-`{name}` object; the plain string is the final fallback (any-/// JS value coerces to a string).+/// Algorithm for `importKey()` and unwrapKey's unwrapped key, normalized as+/// Init is: by its name, then that algorithm's params. RSA and HMAC carry a+/// hash, checked here (a TypeError without a name, NotSupportedError if+/// unknown); EC a namedCurve; the others only their name.pub const Import = union(enum) {+ rsa: struct { hash: Hash, name: []const u8 },hmac: struct {hash: Hash,- /// HMAC's [EnforceRange] unsigned long, kept as a value: RSA imports- /// share this variant and ignore it. HMAC.lengthParam converts it.+ /// As HmacKeyGen's, converted by HMAC.lengthParam.length: ?js.Value = null,name: []const u8,},ec: struct { name: []const u8, namedCurve: []const u8 },- object: struct { name: []const u8 },- /// An object without a `name`: a TypeError, as for every algorithm- /// identifier. Probed before the string, which would coerce it.- nameless: js.Object,- name: []const u8,+ /// AES, HKDF, PBKDF2, Ed25519, X25519, Ed448, X448.+ named: []const u8,- /// Null for an object without a name.- pub fn algoName(self: Import) ?[]const u8 {+ pub fn fromJs(value: js.Value, local: *const js.Local) !Import {+ const name = try identifierName(value, local);+ if (isOneOf(name, &.{ "RSASSA-PKCS1-v1_5", "RSA-PSS", "RSA-OAEP" })) {+ const params = try convert(@FieldType(Import, "rsa"), value, local);+ _ = try params.hash.canonical(local);+ return .{ .rsa = params };+ }+ if (isOneOf(name, &.{"HMAC"})) {+ const params = try convert(@FieldType(Import, "hmac"), value, local);+ _ = try params.hash.canonical(local);+ return .{ .hmac = params };+ }+ if (isOneOf(name, &.{ "ECDSA", "ECDH" })) {+ return .{ .ec = try convert(@FieldType(Import, "ec"), value, local) };+ }+ if (isOneOf(name, &.{ "AES-CTR", "AES-CBC", "AES-GCM", "AES-KW", "HKDF", "PBKDF2", "Ed25519", "X25519", "Ed448", "X448" })) {+ return .{ .named = name };+ }+ return error.NotSupported;+ }++ pub fn algoName(self: Import) []const u8 {return switch (self) {+ .rsa => |r| r.name,.hmac => |h| h.name,.ec => |e| e.name,- .object => |o| o.name,- .nameless => null,- .name => |n| n,+ .named => |n| n,};}@@ -224,8 +247,52 @@ pub const Import = union(enum) {else => "",};}++ /// The hash of an RSA or HMAC import, already checked by fromJs.+ pub fn hash(self: Import, local: *const js.Local) !?[]const u8 {+ return switch (self) {+ .rsa => |r| try r.hash.name(local),+ .hmac => |h| try h.hash.name(local),+ else => null,+ };+ }++ /// The unconverted `length` of an HMAC import (HMAC.lengthParam).+ pub fn length(self: Import) ?js.Value {+ return switch (self) {+ .hmac => |h| h.length,+ else => null,+ };+ }};+/// The name of an AlgorithmIdentifier, `(object or DOMString)`: an object's+/// `name`, required (a TypeError without one), or the value as a string.+/// HashAlgorithmIdentifier has the same conversion.+fn identifierName(value: js.Value, local: *const js.Local) ![]const u8 {+ const identifier = try convert(Hash, value, local);+ return identifier.name(local);+}++/// Whether `name` is one of `names`, ASCII case-insensitively, as algorithm+/// names are matched.+fn isOneOf(name: []const u8, comptime names: []const []const u8) bool {+ inline for (names) |n| {+ if (std.ascii.eqlIgnoreCase(name, n)) return true;+ }+ return false;+}++/// `value` as `T`. A value that isn't one (a string for a dictionary, a+/// missing member, one out of an [EnforceRange] range) is a TypeError; the+/// page's own exception stays pending.+fn convert(comptime T: type, value: js.Value, local: *const js.Local) !T {+ return local.jsValueToZig(T, value) catch |err| switch (err) {+ error.JsException, error.OutOfMemory => err,+ else => local.typeError("algorithm has a missing or invalid member"),+ };+}+/// Key material handed to `importKey()`: either a BufferSource (raw/spki/pkcs8)/// or a JSON Web Key object (jwk). `bytes` is probed first — a JWK is a plain/// object and won't coerce to a TypedArray.