"use strict";
/*
 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0.
 */
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Pkcs11Lib = exports.TlsConnectionOptions = exports.ServerTlsContext = exports.ClientTlsContext = exports.TlsContext = exports.TlsContextOptions = exports.tls_cipher_preference_is_supported = exports.TlsCipherPreference = exports.SocketOptions = exports.ClientBootstrap = exports.InputStream = exports.is_alpn_available = exports.enable_logging = exports.error_code_to_name = exports.error_code_to_string = exports.SocketDomain = exports.SocketType = exports.TlsVersion = exports.LogLevel = exports.setLogLevel = void 0;
/**
 *
 * A module containing a grab bag of support for core network I/O functionality, including sockets, TLS, DNS, logging,
 * error handling, streams, and connection -> thread mapping.
 *
 * Categories include:
 * - Network: socket configuration
 * - TLS: tls configuration
 * - Logging: logging controls and configuration
 * - IO: everything else
 *
 * @packageDocumentation
 * @module io
 * @mergeTarget
 */
const binding_1 = __importDefault(require("./binding"));
const native_resource_1 = require("./native_resource");
const io_1 = require("../common/io");
// Do not re-export the logging functions in common; they are package-private
var io_2 = require("../common/io");
Object.defineProperty(exports, "setLogLevel", { enumerable: true, get: function () { return io_2.setLogLevel; } });
Object.defineProperty(exports, "LogLevel", { enumerable: true, get: function () { return io_2.LogLevel; } });
Object.defineProperty(exports, "TlsVersion", { enumerable: true, get: function () { return io_2.TlsVersion; } });
Object.defineProperty(exports, "SocketType", { enumerable: true, get: function () { return io_2.SocketType; } });
Object.defineProperty(exports, "SocketDomain", { enumerable: true, get: function () { return io_2.SocketDomain; } });
const error_1 = require("./error");
/**
 * Convert a native error code into a human-readable string
 * @param error_code - An error code returned from a native API call, or delivered
 * via callback.
 * @returns Long-form description of the error
 * @see CrtError
 *
 * nodejs only.
 *
 * @category System
 */
function error_code_to_string(error_code) {
    return binding_1.default.error_code_to_string(error_code);
}
exports.error_code_to_string = error_code_to_string;
/**
 * Convert a native error code into a human-readable identifier
 * @param error_code - An error code returned from a native API call, or delivered
 * via callback.
 * @return error name as a string
 * @see CrtError
 *
 * nodejs only.
 *
 * @category System
 */
function error_code_to_name(error_code) {
    return binding_1.default.error_code_to_name(error_code);
}
exports.error_code_to_name = error_code_to_name;
/**
 * Enables logging of the native AWS CRT libraries.
 * @param level - The logging level to filter to. It is not possible to log less than WARN.
 *
 * nodejs only.
 * @category Logging
 */
function enable_logging(level) {
    binding_1.default.io_logging_enable(level);
    (0, io_1.setLogLevel)(level);
}
exports.enable_logging = enable_logging;
/**
 * Returns true if ALPN is available on this platform natively
 * @return true if ALPN is supported natively, false otherwise
 *
 * nodejs only.
 * @category TLS
*/
function is_alpn_available() {
    return binding_1.default.is_alpn_available();
}
exports.is_alpn_available = is_alpn_available;
/**
 * Wraps a ```Readable``` for reading by native code, used to stream
 *  data into the AWS CRT libraries.
 *
 * nodejs only.
 * @category IO
 */
class InputStream extends native_resource_1.NativeResource {
    constructor(source) {
        super(binding_1.default.io_input_stream_new(16 * 1024));
        this.source = source;
        this.source.on('data', (data) => {
            data = Buffer.isBuffer(data) ? data : Buffer.from(data.toString());
            binding_1.default.io_input_stream_append(this.native_handle(), data);
        });
        this.source.on('end', () => {
            binding_1.default.io_input_stream_append(this.native_handle(), undefined);
        });
    }
}
exports.InputStream = InputStream;
/**
 * Represents native resources required to bootstrap a client connection
 * Things like a host resolver, event loop group, etc. There should only need
 * to be 1 of these per application, in most cases.
 *
 * nodejs only.
 * @category IO
 */
class ClientBootstrap extends native_resource_1.NativeResource {
    constructor() {
        super(binding_1.default.io_client_bootstrap_new());
    }
}
exports.ClientBootstrap = ClientBootstrap;
/**
 * Standard Berkeley socket style options.
 *
 * nodejs only.
 * @category Network
*/
class SocketOptions extends native_resource_1.NativeResource {
    constructor(type = io_1.SocketType.STREAM, domain = io_1.SocketDomain.IPV6, connect_timeout_ms = 5000, keepalive = false, keep_alive_interval_sec = 0, keep_alive_timeout_sec = 0, keep_alive_max_failed_probes = 0) {
        super(binding_1.default.io_socket_options_new(type, domain, connect_timeout_ms, keep_alive_interval_sec, keep_alive_timeout_sec, keep_alive_max_failed_probes, keepalive));
    }
}
exports.SocketOptions = SocketOptions;
/**
 * Each TlsCipherPreference represents an ordered list of TLS Ciphers to use when negotiating a TLS Connection. At
 * present, the ability to configure arbitrary orderings of TLS Ciphers is not allowed, and only a curated list of
 * vetted TlsCipherPref's are exposed.
 */
var TlsCipherPreference;
(function (TlsCipherPreference) {
    /**
     * The underlying platform's default TLS Cipher Preference ordering. This is usually the best option, as it will be
     * automatically updated as the underlying OS or platform changes, and will always be supported on all platforms.
     */
    TlsCipherPreference[TlsCipherPreference["Default"] = 0] = "Default";
    /**
     * A TLS Cipher Preference ordering that supports TLS 1.0 through TLS 1.3, and has Kyber Round 3 as its highest
     * priority post-quantum key exchange algorithm. PQ algorithms in this preference list will always be used in hybrid
     * mode, and will be combined with a classical ECDHE key exchange that is performed in addition to the PQ key
     * exchange. This preference makes a best-effort to negotiate a PQ algorithm, but if the peer does not support any
     * PQ algorithms the TLS connection will fall back to a single classical algorithm for key exchange (such as ECDHE
     * or RSA).
     * NIST has announced that they plan to eventually standardize Kyber. However, the NIST standardization process might
     * introduce minor changes that could cause the final Kyber standard to differ from the Kyber Round 3 implementation
     * available in this preference list.
     */
    TlsCipherPreference[TlsCipherPreference["PQ_TLSv1_0_2021_05"] = 6] = "PQ_TLSv1_0_2021_05";
    /**
     * Recommended default policy with post-quantum algorithm support. This policy may change over time.
     */
    TlsCipherPreference[TlsCipherPreference["PQ_Default"] = 8] = "PQ_Default";
    /**
     * A TLS Cipher Preference ordering that supports TLS 1.2 through TLS 1.3, and does not include CBC cipher suites.
     * It is FIPS-complaint.
     */
    TlsCipherPreference[TlsCipherPreference["TLSv1_2_2025_07"] = 9] = "TLSv1_2_2025_07";
})(TlsCipherPreference = exports.TlsCipherPreference || (exports.TlsCipherPreference = {}));
/**
 * Returns true if the supplied TlsCipherPreference is supported on the current platform, false otherwise.
 *
 * @param tls_cipher_preference - cipher preference to check support for
 *
 * nodejs only.
 * @category TLS
 */
function tls_cipher_preference_is_supported(tls_cipher_preference) {
    return binding_1.default.io_tls_cipher_preference_is_supported(tls_cipher_preference);
}
exports.tls_cipher_preference_is_supported = tls_cipher_preference_is_supported;
/**
 * Options for creating a {@link ClientTlsContext} or {@link ServerTlsContext}.
 *
 * nodejs only.
 * @category TLS
 */
class TlsContextOptions {
    constructor() {
        /** Minimum version of TLS to support. Uses OS/system default if unspecified. */
        this.min_tls_version = io_1.TlsVersion.Default;
        /** List of ALPN protocols to be used on platforms which support ALPN */
        this.alpn_list = [];
        /**
         * In client mode, this turns off x.509 validation. Don't do this unless you are testing.
         * It is much better to just override the default trust store and pass the self-signed
         * certificate as the ca_file argument.
         *
         * In server mode (ServerTlsContext), this defaults to false. If you want to enforce mutual TLS on the server,
         * set this to true.
         */
        this.verify_peer = true;
        /**
         * Set to true to disable certificate revocation checking during TLS negotiation.
         *
         * On Windows (SChannel), this prevents the TLS handshake from making outbound network calls
         * to CRL/OCSP revocation endpoints, which can block for minutes when the endpoints are unreachable
         * (e.g., in private subnets without internet access).
         *
         * On Linux (s2n), this disables validation of OCSP stapled responses provided by the server.
         *
         * On Apple platforms, this is a no-op as revocation checking is not enabled by default.
         *
         * Default is false (revocation checking enabled where available).
         */
        this.no_certificate_revocation = false;
    }
    /**
     * Overrides the default system trust store.
     * @param ca_dirpath - Only used on Unix-style systems where all trust anchors are
     * stored in a directory (e.g. /etc/ssl/certs).
     * @param ca_filepath - Single file containing all trust CAs, in PEM format
     */
    override_default_trust_store_from_path(ca_dirpath, ca_filepath) {
        this.ca_dirpath = ca_dirpath;
        this.ca_filepath = ca_filepath;
    }
    /**
     * Overrides the default system trust store.
     * @param certificate_authority - String containing all trust CAs, in PEM format
     */
    override_default_trust_store(certificate_authority) {
        this.certificate_authority = certificate_authority;
    }
    /**
     * Create options configured for mutual TLS in client mode,
     * with client certificate and private key provided as in-memory strings.
     * @param certificate - Client certificate file contents, in PEM format
     * @param private_key - Client private key file contents, in PEM format
     *
     * @returns newly configured TlsContextOptions object
     */
    static create_client_with_mtls(certificate, private_key) {
        let opt = new TlsContextOptions();
        opt.certificate = certificate;
        opt.private_key = private_key;
        opt.verify_peer = true;
        return opt;
    }
    /**
     * Create options configured for mutual TLS in client mode,
     * with client certificate and private key provided via filepath.
     * @param certificate_filepath - Path to client certificate, in PEM format
     * @param private_key_filepath - Path to private key, in PEM format
     *
     * @returns newly configured TlsContextOptions object
     */
    static create_client_with_mtls_from_path(certificate_filepath, private_key_filepath) {
        let opt = new TlsContextOptions();
        opt.certificate_filepath = certificate_filepath;
        opt.private_key_filepath = private_key_filepath;
        opt.verify_peer = true;
        return opt;
    }
    /**
     * Create options for mutual TLS in client mode,
     * with client certificate and private key bundled in a single PKCS#12 file.
     * @param pkcs12_filepath - Path to PKCS#12 file containing client certificate and private key.
     * @param pkcs12_password - PKCS#12 password
     *
     * @returns newly configured TlsContextOptions object
    */
    static create_client_with_mtls_pkcs12_from_path(pkcs12_filepath, pkcs12_password) {
        let opt = new TlsContextOptions();
        opt.pkcs12_filepath = pkcs12_filepath;
        opt.pkcs12_password = pkcs12_password;
        opt.verify_peer = true;
        return opt;
    }
    /**
     * @deprecated Renamed [[create_client_with_mtls_pkcs12_from_path]]
     */
    static create_client_with_mtls_pkcs_from_path(pkcs12_filepath, pkcs12_password) {
        return this.create_client_with_mtls_pkcs12_from_path(pkcs12_filepath, pkcs12_password);
    }
    /**
     * Create options configured for mutual TLS in client mode,
     * using a PKCS#11 library for private key operations.
     *
     * NOTE: This configuration only works on Unix devices.
     *
     * @param options - PKCS#11 options
     *
     * @returns newly configured TlsContextOptions object
     */
    static create_client_with_mtls_pkcs11(options) {
        let opt = new TlsContextOptions();
        opt.pkcs11_options = options;
        opt.verify_peer = true;
        return opt;
    }
    /**
     * Create options configured for mutual TLS in client mode,
     * using a certificate in a Windows certificate store.
     *
     * NOTE: Windows only.
     *
     * @param certificate_path - Path to certificate in a Windows certificate store.
     *      The path must use backslashes and end with the certificate's thumbprint.
     *      Example: `CurrentUser\MY\A11F8A9B5DF5B98BA3508FBCA575D09570E0D2C6`
     */
    static create_client_with_mtls_windows_cert_store_path(certificate_path) {
        let opt = new TlsContextOptions();
        opt.windows_cert_store_path = certificate_path;
        opt.verify_peer = true;
        return opt;
    }
    /**
     * Creates TLS context with peer verification disabled, along with a certificate and private key
     * @param certificate_filepath - Path to certificate, in PEM format
     * @param private_key_filepath - Path to private key, in PEM format
     *
     * @returns newly configured TlsContextOptions object
     */
    static create_server_with_mtls_from_path(certificate_filepath, private_key_filepath) {
        let opt = new TlsContextOptions();
        opt.certificate_filepath = certificate_filepath;
        opt.private_key_filepath = private_key_filepath;
        opt.verify_peer = false;
        return opt;
    }
    /**
     * Creates TLS context with peer verification disabled, along with a certificate and private key
     * in PKCS#12 format
     * @param pkcs12_filepath - Path to certificate, in PKCS#12 format
     * @param pkcs12_password - PKCS#12 Password
     *
     * @returns newly configured TlsContextOptions object
     */
    static create_server_with_mtls_pkcs_from_path(pkcs12_filepath, pkcs12_password) {
        let opt = new TlsContextOptions();
        opt.pkcs12_filepath = pkcs12_filepath;
        opt.pkcs12_password = pkcs12_password;
        opt.verify_peer = false;
        return opt;
    }
}
exports.TlsContextOptions = TlsContextOptions;
/**
 * Abstract base TLS context used for client/server TLS communications over sockets.
 *
 * @see ClientTlsContext
 * @see ServerTlsContext
 *
 * nodejs only.
 * @category TLS
 */
class TlsContext extends native_resource_1.NativeResource {
    constructor(ctx_opt) {
        if (ctx_opt == null || ctx_opt == undefined) {
            throw new error_1.CrtError("TlsContext constructor: ctx_opt not defined");
        }
        super(binding_1.default.io_tls_ctx_new(ctx_opt.min_tls_version, ctx_opt.ca_filepath, ctx_opt.ca_dirpath, ctx_opt.certificate_authority, (ctx_opt.alpn_list && ctx_opt.alpn_list.length > 0) ? ctx_opt.alpn_list.join(';') : undefined, ctx_opt.certificate_filepath, ctx_opt.certificate, ctx_opt.private_key_filepath, ctx_opt.private_key, ctx_opt.pkcs12_filepath, ctx_opt.pkcs12_password, ctx_opt.pkcs11_options, ctx_opt.windows_cert_store_path, ctx_opt.tls_cipher_preference, ctx_opt.verify_peer, ctx_opt.no_certificate_revocation));
    }
}
exports.TlsContext = TlsContext;
/**
 * TLS context used for client TLS communications over sockets. If no
 * options are supplied, the context will default to enabling peer verification
 * only.
 *
 * nodejs only.
 * @category TLS
 */
class ClientTlsContext extends TlsContext {
    constructor(ctx_opt) {
        if (!ctx_opt) {
            ctx_opt = new TlsContextOptions();
            ctx_opt.verify_peer = true;
        }
        super(ctx_opt);
    }
}
exports.ClientTlsContext = ClientTlsContext;
/**
 * TLS context used for server TLS communications over sockets. If no
 * options are supplied, the context will default to disabling peer verification
 * only.
 *
 * nodejs only.
 * @category TLS
 */
class ServerTlsContext extends TlsContext {
    constructor(ctx_opt) {
        if (!ctx_opt) {
            ctx_opt = new TlsContextOptions();
            ctx_opt.verify_peer = false;
        }
        super(ctx_opt);
    }
}
exports.ServerTlsContext = ServerTlsContext;
/**
 * TLS options that are unique to a given connection using a shared TlsContext.
 *
 * nodejs only.
 * @category TLS
 */
class TlsConnectionOptions extends native_resource_1.NativeResource {
    constructor(tls_ctx, server_name, alpn_list = []) {
        if (tls_ctx == null || tls_ctx == undefined) {
            throw new error_1.CrtError("TlsConnectionOptions constructor: tls_ctx not defined");
        }
        super(binding_1.default.io_tls_connection_options_new(tls_ctx.native_handle(), server_name, (alpn_list && alpn_list.length > 0) ? alpn_list.join(';') : undefined));
        this.tls_ctx = tls_ctx;
        this.server_name = server_name;
        this.alpn_list = alpn_list;
    }
}
exports.TlsConnectionOptions = TlsConnectionOptions;
/**
 * Handle to a loaded PKCS#11 library.
 *
 * For most use cases, a single instance of Pkcs11Lib should be used
 * for the lifetime of your application.
 *
 * nodejs only.
 * @category TLS
 */
class Pkcs11Lib extends native_resource_1.NativeResource {
    /**
     * @param path - Path to PKCS#11 library.
     * @param behavior - Specifies how `C_Initialize()` and `C_Finalize()`
     *                   will be called on the PKCS#11 library.
     */
    constructor(path, behavior = Pkcs11Lib.InitializeFinalizeBehavior.DEFAULT) {
        super(binding_1.default.io_pkcs11_lib_new(path, behavior));
    }
    /**
     * Release the PKCS#11 library immediately, without waiting for the GC.
     */
    close() {
        binding_1.default.io_pkcs11_lib_close(this.native_handle());
    }
}
exports.Pkcs11Lib = Pkcs11Lib;
(function (Pkcs11Lib) {
    /**
     * Controls `C_Initialize()` and `C_Finalize()` are called on the PKCS#11 library.
     */
    let InitializeFinalizeBehavior;
    (function (InitializeFinalizeBehavior) {
        /**
         * Default behavior that accommodates most use cases.
         *
         * `C_Initialize()` is called on creation, and "already-initialized"
         * errors are ignored. `C_Finalize()` is never called, just in case
         * another part of your application is still using the PKCS#11 library.
         */
        InitializeFinalizeBehavior[InitializeFinalizeBehavior["DEFAULT"] = 0] = "DEFAULT";
        /**
         * Skip calling `C_Initialize()` and `C_Finalize()`.
         *
         * Use this if your application has already initialized the PKCS#11 library,
         * and you do not want `C_Initialize()` called again.
         */
        InitializeFinalizeBehavior[InitializeFinalizeBehavior["OMIT"] = 1] = "OMIT";
        /**
         * `C_Initialize()` is called on creation and `C_Finalize()` is called on cleanup.
         *
         * If `C_Initialize()` reports that's it's already initialized, this is
         * treated as an error. Use this if you need perfect cleanup (ex: running
         * valgrind with --leak-check).
         */
        InitializeFinalizeBehavior[InitializeFinalizeBehavior["STRICT"] = 2] = "STRICT";
    })(InitializeFinalizeBehavior = Pkcs11Lib.InitializeFinalizeBehavior || (Pkcs11Lib.InitializeFinalizeBehavior = {}));
})(Pkcs11Lib = exports.Pkcs11Lib || (exports.Pkcs11Lib = {}));
//# sourceMappingURL=io.js.map