"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var X509_exports = {};
__export(X509_exports, {
  X509: () => X509
});
module.exports = __toCommonJS(X509_exports);
var import_DerCodec = require("#codec/DerCodec.js");
var import_MatterError = require("#MatterError.js");
var import_Bytes = require("#util/Bytes.js");
var import_CryptoError = require("./CryptoError.js");
var import_Pem = require("./Pem.js");
var import_X962 = require("./X962.js");
/**
 * @license
 * Copyright 2022-2026 Matter.js Authors
 * SPDX-License-Identifier: Apache-2.0
 */
var X509;
((X5092) => {
  async function sign(crypto, key, cert) {
    return {
      ...cert,
      signature: (await crypto.signEcdsa(key, certificateToDer(cert))).der
    };
  }
  X5092.sign = sign;
  function certificateToPem(cert) {
    return import_Pem.Pem.encode(certificateToDer(cert));
  }
  X5092.certificateToPem = certificateToPem;
  function certificateToDer(cert) {
    const { serialNumber, signatureAlgorithm, issuer, validity, subject, publicKey, extensions } = cert;
    const { basicConstraints } = extensions;
    if (basicConstraints && !basicConstraints.isCa && basicConstraints.pathLen !== void 0) {
      throw new import_CryptoError.CertificateError("Path length must be undefined for non-CA certificates.");
    }
    let ast = {
      version: (0, import_DerCodec.ContextTagged)(0, 2),
      // v3
      serialNumber: (0, import_DerCodec.DatatypeOverride)(import_DerCodec.DerType.Integer, serialNumber),
      signatureAlgorithm: signatureAlgorithm ?? import_X962.X962.EcdsaWithSHA256,
      issuer,
      validity,
      subject,
      publicKeyInfo: publicKey,
      extensions: (0, import_DerCodec.ContextTagged)(3, extensionsToAst(extensions))
    };
    if ("signature" in cert) {
      ast = {
        ast,
        signatureAlgorithm: cert.signatureAlgorithm,
        signature: (0, import_DerCodec.DerBitString)(cert.signature)
      };
    }
    return import_DerCodec.DerCodec.encode(ast);
  }
  X5092.certificateToDer = certificateToDer;
  X5092.KeyUsageFlags = [
    "digitalSignature",
    "nonRepudiation",
    "keyEncipherment",
    "dataEncipherment",
    "keyAgreement",
    "keyCertSign",
    "cRLSign",
    "encipherOnly",
    "decipherOnly"
  ];
  let Extensions;
  ((Extensions2) => {
    Extensions2.BASIC_CONSTRAINTS = 0x551d13n;
    Extensions2.KEY_USAGE = 0x551d0fn;
    Extensions2.EXTENDED_KEY_USAGE = 0x551d25n;
    Extensions2.SUBJECT_KEY_IDENTIFIER = 0x551d0en;
    Extensions2.AUTHORITY_KEY_IDENTIFIER = 0x551d23n;
  })(Extensions = X5092.Extensions || (X5092.Extensions = {}));
  function SubjectKeyIdentifier(identifier) {
    return (0, import_DerCodec.DerObject)(Extensions.SUBJECT_KEY_IDENTIFIER, { value: import_DerCodec.DerCodec.encode(identifier) });
  }
  X5092.SubjectKeyIdentifier = SubjectKeyIdentifier;
  function AuthorityKeyIdentifier(identifier) {
    return (0, import_DerCodec.DerObject)(Extensions.AUTHORITY_KEY_IDENTIFIER, {
      value: import_DerCodec.DerCodec.encode({ id: (0, import_DerCodec.ContextTaggedBytes)(0, identifier) })
    });
  }
  X5092.AuthorityKeyIdentifier = AuthorityKeyIdentifier;
  function BasicConstraints(constraints) {
    const toEncode = { ...constraints };
    if (toEncode?.isCa === false) {
      delete toEncode.isCa;
    }
    return (0, import_DerCodec.DerObject)(Extensions.BASIC_CONSTRAINTS, { critical: true, value: import_DerCodec.DerCodec.encode(toEncode) });
  }
  X5092.BasicConstraints = BasicConstraints;
  function ExtendedKeyUsage(values) {
    if (values === void 0) {
      return;
    }
    const data = {};
    values.forEach((value) => {
      switch (value) {
        case 1:
          data.serverAuth = (0, import_DerCodec.ObjectId)(ExtendedKeyUsage.SERVER_AUTH);
          break;
        case 2:
          data.clientAuth = (0, import_DerCodec.ObjectId)(ExtendedKeyUsage.CLIENT_AUTH);
          break;
        case 3:
          data.codeSigning = (0, import_DerCodec.ObjectId)(ExtendedKeyUsage.CODE_SIGNING);
          break;
        case 4:
          data.emailProtection = (0, import_DerCodec.ObjectId)(ExtendedKeyUsage.EMAIL_PROTECTION);
          break;
        case 5:
          data.timeStamping = (0, import_DerCodec.ObjectId)(ExtendedKeyUsage.TIME_STAMPING);
          break;
        case 6:
          data.ocspSigning = (0, import_DerCodec.ObjectId)(ExtendedKeyUsage.OCSP_SIGNING);
          break;
        default:
          throw new import_DerCodec.DerError(`Unsupported extended key usage value ${value}`);
      }
    });
    return (0, import_DerCodec.DerObject)(Extensions.EXTENDED_KEY_USAGE, {
      critical: true,
      value: import_DerCodec.DerCodec.encode(data)
    });
  }
  X5092.ExtendedKeyUsage = ExtendedKeyUsage;
  ((ExtendedKeyUsage2) => {
    ExtendedKeyUsage2.SERVER_AUTH = 0x2b06010505070301n;
    ExtendedKeyUsage2.CLIENT_AUTH = 0x2b06010505070302n;
    ExtendedKeyUsage2.CODE_SIGNING = 0x2b06010505070303n;
    ExtendedKeyUsage2.EMAIL_PROTECTION = 0x2b06010505070304n;
    ExtendedKeyUsage2.TIME_STAMPING = 0x2b06010505070308n;
    ExtendedKeyUsage2.OCSP_SIGNING = 0x2b06010505070309n;
  })(ExtendedKeyUsage = X5092.ExtendedKeyUsage || (X5092.ExtendedKeyUsage = {}));
  function KeyUsage(value) {
    if (typeof value !== "number") {
      value = encodeKeyUsage(value);
    }
    return (0, import_DerCodec.DerObject)(Extensions.KEY_USAGE, {
      critical: true,
      value: import_DerCodec.DerCodec.encode((0, import_DerCodec.DatatypeOverride)(import_DerCodec.DerType.BitString, value))
    });
  }
  X5092.KeyUsage = KeyUsage;
})(X509 || (X509 = {}));
const ExtensionEncoders = {
  basicConstraints: X509.BasicConstraints,
  keyUsage: X509.KeyUsage,
  extendedKeyUsage: X509.ExtendedKeyUsage,
  subjectKeyIdentifier: X509.SubjectKeyIdentifier,
  authorityKeyIdentifier: X509.AuthorityKeyIdentifier,
  futureExtension: (future) => (0, import_DerCodec.RawBytes)(import_Bytes.Bytes.concat(...future ?? []))
};
function extensionsToAst(extensions) {
  const ast = {};
  for (const key in extensions) {
    const value = extensions[key];
    if (value === void 0) {
      continue;
    }
    const encoder = ExtensionEncoders[key];
    if (encoder === void 0) {
      throw new import_MatterError.ImplementationError(`Unsupported X.509 certificate extension ${key}`);
    }
    ast[key] = encoder(value);
  }
  return ast;
}
function encodeKeyUsage(flags) {
  let bit = 1;
  let encoded = 0;
  for (const flag of X509.KeyUsageFlags) {
    if (flags[flag]) {
      encoded |= bit;
    }
    bit <<= 1;
  }
  return encoded;
}
//# sourceMappingURL=X509.js.map
