### Create an HTTPS Server with Self-Signed Certificate Source: https://context7.com/jfromaniello/selfsigned/llms.txt Provides a complete Node.js example of creating an HTTPS server using the `selfsigned` module to generate a certificate on the fly. It configures the server with necessary extensions like Subject Alternative Names (SANs) and demonstrates how to start the server and access it. The example includes generating the certificate, creating the HTTPS server instance, and handling requests. ```javascript const https = require('https'); const selfsigned = require('selfsigned'); async function startServer() { // Generate self-signed certificate const pems = await selfsigned.generate( [{ name: 'commonName', value: 'localhost' }], { algorithm: 'sha256', keySize: 2048, extensions: [ { name: 'basicConstraints', cA: false }, { name: 'keyUsage', digitalSignature: true, keyEncipherment: true }, { name: 'extKeyUsage', serverAuth: true }, { name: 'subjectAltName', altNames: [ { type: 2, value: 'localhost' }, { type: 7, ip: '127.0.0.1' }, { type: 7, ip: '::1' } ] } ] } ); // Create HTTPS server const server = https.createServer({ key: pems.private, cert: pems.cert }, (req, res) => { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ message: 'Hello from HTTPS!', fingerprint: pems.fingerprint })); }); server.listen(3443, () => { console.log('HTTPS server: https://localhost:3443'); console.log('Fingerprint:', pems.fingerprint); console.log('Test: curl -k https://localhost:3443'); }); } startServer().catch(console.error); ``` -------------------------------- ### Migration from v4.x to v5.x Source: https://github.com/jfromaniello/selfsigned/blob/master/README.md Details the breaking changes and provides migration examples from version 4.x to 5.x. ```APIDOC ## Migration from v4.x Version 5.0 introduces breaking changes: ### Breaking Changes 1. **Async-only API**: The `generate()` function is now async and returns a Promise. Synchronous generation is no longer supported. 2. **No callback support**: Callbacks have been removed. Use `async`/`await` or `.then()`. 3. **Minimum Node.js version**: Now requires Node.js >= 15.6.0 (was >= 10). 4. **Dependencies**: Replaced `node-forge` with `@peculiar/x509` and `pkijs` (66% smaller bundle size). 5. **`days` option removed**: Use `notAfterDate` instead. Default validity is 365 days from `notBeforeDate`. ### Migration Examples **Old (v4.x):** ```javascript // Sync const pems = selfsigned.generate(attrs, { days: 365 }); // Callback selfsigned.generate(attrs, { days: 365 }, function(err, pems) { if (err) throw err; console.log(pems); }); ``` **New (v5.x):** ```javascript // Async/await (default 365 days validity) const pems = await selfsigned.generate(attrs); // Custom validity with notAfterDate const notAfter = new Date(); notAfter.setDate(notAfter.getDate() + 30); // 30 days const pems = await selfsigned.generate(attrs, { notAfterDate: notAfter }); // Or with .then() selfsigned.generate(attrs) .then(pems => console.log(pems)) .catch(err => console.error(err)); ``` ``` -------------------------------- ### Install selfsigned Package Source: https://github.com/jfromaniello/selfsigned/blob/master/README.md Installs the 'selfsigned' package using npm. This package is required for generating self-signed certificates in Node.js. ```bash npm install selfsigned ``` -------------------------------- ### Migrate Selfsigned from v4.x to v5.x Source: https://github.com/jfromaniello/selfsigned/blob/master/README.md Provides examples of how to update code from the synchronous/callback-based v4.x API to the new asynchronous Promise-based v5.x API. ```javascript // Old v4.x Sync const pems = selfsigned.generate(attrs, { days: 365 }); // Old v4.x Callback selfsigned.generate(attrs, { days: 365 }, function(err, pems) { if (err) throw err; console.log(pems); }); ``` ```javascript // New v5.x Async/await const pems = await selfsigned.generate(attrs); // New v5.x Custom validity const notAfter = new Date(); notAfter.setDate(notAfter.getDate() + 30); const pems = await selfsigned.generate(attrs, { notAfterDate: notAfter }); // New v5.x .then() selfsigned.generate(attrs) .then(pems => console.log(pems)) .catch(err => console.error(err)); ``` -------------------------------- ### Integrate selfsigned with mkcert for Development Source: https://github.com/jfromaniello/selfsigned/blob/master/README.md Provides a practical example of using 'selfsigned' in conjunction with 'mkcert' to generate browser-trusted development certificates on-the-fly without managing certificate files. This enhances developer experience by eliminating security warnings and the need to store sensitive files. ```javascript const https = require('https'); const fs = require('fs'); const path = require('path'); const { execSync } = require('child_process'); const selfsigned = require('selfsigned'); // Get mkcert's CA (requires: brew install mkcert && mkcert -install) const caroot = execSync('mkcert -CAROOT', { encoding: 'utf8' }).trim(); const pems = await selfsigned.generate([ { name: 'commonName', value: 'localhost' } ], { algorithm: 'sha256', ca: { key: fs.readFileSync(path.join(caroot, 'rootCA-key.pem'), 'utf8'), cert: fs.readFileSync(path.join(caroot, 'rootCA.pem'), 'utf8') } }); // Start server with browser-trusted certificate - no files written to disk https.createServer({ key: pems.private, cert: pems.cert }, app).listen(443); ``` -------------------------------- ### Generate Certificate with Encrypted Private Key (JavaScript) Source: https://context7.com/jfromaniello/selfsigned/llms.txt Generates a certificate with its private key encrypted using AES-256-CBC encryption in PKCS#8 format. The example shows how to generate the certificate with a passphrase, verify encryption, and decrypt the private key for use with an HTTPS server. ```javascript const selfsigned = require('selfsigned'); const crypto = require('crypto'); const https = require('https'); // Generate certificate with encrypted private key const pems = await selfsigned.generate( [{ name: 'commonName', value: 'secure.localhost' }], { algorithm: 'sha256', passphrase: 'my-secret-passphrase' } ); // Private key is encrypted (PKCS#8 format) console.log(pems.private.includes('ENCRYPTED')); // true // Decrypt the key for use const privateKey = crypto.createPrivateKey({ key: pems.private, passphrase: 'my-secret-passphrase' }); // Use with HTTPS server (passphrase required) const server = https.createServer({ key: pems.private, passphrase: 'my-secret-passphrase', cert: pems.cert }, (req, res) => { res.end('Secure server with encrypted key'); }).listen(443); ``` -------------------------------- ### Convert PEM Certificates to PKCS#7 Format Source: https://context7.com/jfromaniello/selfsigned/llms.txt Shows how to convert PEM-formatted certificates generated by selfsigned into PKCS#7 format using the dedicated `selfsigned/pkcs7` module. This is useful for systems or applications that require certificates in PKCS#7 format. The example covers both standard certificates and client certificates. ```javascript const selfsigned = require('selfsigned'); const { createPkcs7 } = require('selfsigned/pkcs7'); // Generate certificate const pems = await selfsigned.generate( [{ name: 'commonName', value: 'example.com' }], { algorithm: 'sha256' } ); // Convert to PKCS#7 format const pkcs7 = createPkcs7(pems.cert); console.log(pkcs7); // -----BEGIN PKCS7----- // ...base64 encoded data... // -----END PKCS7----- // Also works with client certificates const clientPems = await selfsigned.generate(null, { clientCertificate: true }); const clientPkcs7 = createPkcs7(clientPems.clientcert); ``` -------------------------------- ### Set Custom Validity Period for Certificate Source: https://github.com/jfromaniello/selfsigned/blob/master/README.md Provides examples of setting custom validity periods for self-signed certificates using `notBeforeDate` and `notAfterDate` options, including using date-fns and vanilla JavaScript. ```javascript // Using date-fns const { addDays, addYears } = require('date-fns'); const pems = await selfsigned.generate(null, { notBeforeDate: new Date(), notAfterDate: addDays(new Date(), 30) // Valid for 30 days }); // Or with vanilla JS const notBefore = new Date(); const notAfter = new Date(notBefore); notAfter.setFullYear(notAfter.getFullYear() + 2); // Valid for 2 years const pems = await selfsigned.generate({ notBeforeDate: notBefore, notAfterDate: notAfter }); ``` -------------------------------- ### Migrate Certificate Generation to Async/Await Source: https://github.com/jfromaniello/selfsigned/blob/master/CHANGELOG.md Demonstrates the transition from synchronous function calls to the new Promise-based async/await pattern required in v5.x. ```javascript // Old (v4.x) const pems = selfsigned.generate(attrs, options); // New (v5.x) const pems = await selfsigned.generate(attrs, options); ``` -------------------------------- ### PKCS#7 Support Source: https://github.com/jfromaniello/selfsigned/blob/master/README.md Demonstrates how to generate PKCS#7 formatted certificates using a separate module. ```APIDOC ## PKCS#7 Support PKCS#7 formatting is available through a separate module for better tree-shaking. ### Method `POST` (Conceptual - actual implementation is function calls) ### Endpoint `selfsigned.generate()` and `selfsigned/pkcs7.createPkcs7()` ### Description Generates a certificate using `selfsigned.generate` and then formats it into PKCS#7 using `createPkcs7` from the `selfsigned/pkcs7` module. ### Request Example ```javascript const selfsigned = require('selfsigned'); const { createPkcs7 } = require('selfsigned/pkcs7'); const pems = await selfsigned.generate(attrs); const pkcs7 = createPkcs7(pems.cert); console.log(pkcs7); // PKCS#7 formatted certificate ``` ### Client Certificate PKCS#7 Example You can also create PKCS#7 for client certificates: ```javascript const pems = await selfsigned.generate(null, { clientCertificate: true }); const clientPkcs7 = createPkcs7(pems.clientcert); ``` ``` -------------------------------- ### Generate Client Certificates with Selfsigned Source: https://github.com/jfromaniello/selfsigned/blob/master/README.md Demonstrates how to generate client certificates signed by a server key using the selfsigned library. It includes basic usage and advanced configuration options for custom common names and cryptographic parameters. ```javascript const pems = await selfsigned.generate(null, { clientCertificate: true }); console.log(pems); ``` ```javascript const pems = await selfsigned.generate(null, { clientCertificate: { cn: 'jdoe', keyType: 'rsa', keySize: 4096, curve: 'P-256', algorithm: 'sha256', notBeforeDate: new Date(), notAfterDate: new Date('2026-01-01') } }); ``` ```javascript const pems = await selfsigned.generate(null, { clientCertificate: { cn: 'FooBar' } }); ``` -------------------------------- ### Generate CA-Signed Certificates (JavaScript) Source: https://context7.com/jfromaniello/selfsigned/llms.txt Demonstrates generating a certificate signed by an existing Certificate Authority (CA). This involves first creating a CA certificate and then generating a server certificate signed by that CA. It also shows how to integrate with mkcert for browser-trusted development certificates. ```javascript const selfsigned = require('selfsigned'); const fs = require('fs'); // First, create a CA certificate const ca = await selfsigned.generate( [ { name: 'commonName', value: 'Development CA' }, { name: 'organizationName', value: 'My Company' } ], { algorithm: 'sha256' } ); // Generate a certificate signed by the CA const serverCert = await selfsigned.generate( [{ name: 'commonName', value: 'localhost' }], { algorithm: 'sha256', ca: { key: ca.private, cert: ca.cert } } ); // Using mkcert CA for browser-trusted development certificates const { execSync } = require('child_process'); const path = require('path'); const caroot = execSync('mkcert -CAROOT', { encoding: 'utf8' }).trim(); const mkcertPems = await selfsigned.generate( [{ name: 'commonName', value: 'localhost' }], { algorithm: 'sha256', ca: { key: fs.readFileSync(path.join(caroot, 'rootCA-key.pem'), 'utf8'), cert: fs.readFileSync(path.join(caroot, 'rootCA.pem'), 'utf8') } } ); ``` -------------------------------- ### Advanced EC Certificate Generation Options Source: https://github.com/jfromaniello/selfsigned/blob/master/README.md Illustrates advanced configurations for EC certificate generation, including adding client certificate options, using passphrases for encrypted private keys, and reusing existing EC key pairs. ```javascript const pems = await selfsigned.generate(null, { keyType: 'ec', passphrase: 'secret' }); ``` ```javascript const pems = await selfsigned.generate(null, { keyType: 'ec', clientCertificate: true }); ``` ```javascript const pems = await selfsigned.generate(null, { keyType: 'ec', curve: 'P-256', keyPair: { publicKey: existingPublicKey, privateKey: existingPrivateKey } }); ``` -------------------------------- ### Reuse Existing Key Pairs with Selfsigned Source: https://context7.com/jfromaniello/selfsigned/llms.txt Demonstrates how to use pre-generated RSA or EC key pairs with the selfsigned module instead of generating new ones. This is useful for maintaining key consistency across different operations. The code shows the process for both RSA and EC key types and verifies that the original keys are preserved. ```javascript const selfsigned = require('selfsigned'); const crypto = require('crypto'); // Generate a key pair externally const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', { modulusLength: 2048, publicKeyEncoding: { type: 'spki', format: 'pem' }, privateKeyEncoding: { type: 'pkcs8', format: 'pem' } }); // Use existing keys with selfsigned const pems = await selfsigned.generate( [{ name: 'commonName', value: 'reused-key.local' }], { algorithm: 'sha256', keyPair: { privateKey: privateKey, publicKey: publicKey } } ); // Keys are preserved console.log(pems.private === privateKey); // true console.log(pems.public === publicKey); // true // Also works with EC keys const ecKeyPair = crypto.generateKeyPairSync('ec', { namedCurve: 'prime256v1', publicKeyEncoding: { type: 'spki', format: 'pem' }, privateKeyEncoding: { type: 'pkcs8', format: 'pem' } }); const ecPems = await selfsigned.generate(null, { keyType: 'ec', curve: 'P-256', keyPair: { privateKey: ecKeyPair.privateKey, publicKey: ecKeyPair.publicKey } }); ``` -------------------------------- ### Generate Certificate with Custom Extensions Source: https://github.com/jfromaniello/selfsigned/blob/master/README.md Shows how to generate a certificate with custom extensions, including basic constraints, key usage, and subject alternative names (DNS, IPv4, IPv6), using the `extensions` option. ```javascript const pems = await selfsigned.generate( [{ name: 'commonName', value: 'localhost' }], { extensions: [ { name: 'basicConstraints', cA: false }, { name: 'keyUsage', digitalSignature: true, keyEncipherment: true }, { name: 'subjectAltName', altNames: [ { type: 2, value: 'localhost' }, // DNS { type: 7, ip: '127.0.0.1' }, // IPv4 { type: 7, ip: '::1' } // IPv6 ] } ] } ); ``` -------------------------------- ### Configure Certificate Generation Options Source: https://github.com/jfromaniello/selfsigned/blob/master/README.md Demonstrates how to use the options object with 'selfsigned.generate()' to customize certificate parameters such as key type, key size, validity dates, algorithm, and extensions. ```javascript const pems = await selfsigned.generate(null, { keyType: 'rsa', // key type: 'rsa' or 'ec' (default: 'rsa') keySize: 2048, // the size for the private key in bits (default: 2048, RSA only) curve: 'P-256', // elliptic curve: 'P-256', 'P-384', or 'P-521' (default: 'P-256', EC only) notBeforeDate: new Date(), // start of certificate validity (default: now) notAfterDate: new Date('2026-01-01'), // end of certificate validity (default: notBeforeDate + 365 days) algorithm: 'sha256', // sign the certificate with specified algorithm (default: 'sha1') extensions: [{ name: 'basicConstraints', cA: true }], // certificate extensions array clientCertificate: true, // generate client cert (default: false) - can also be an options object ca: { key: '...', cert: '...' }, // CA key and cert for signing (default: self-signed) passphrase: 'secret' // encrypt the private key with a passphrase (default: none) }); ``` -------------------------------- ### Generate Certificate with Custom Key Pair Source: https://github.com/jfromaniello/selfsigned/blob/master/README.md Shows how to generate a certificate using your own pre-existing public and private keys, bypassing the library's key generation process. This is useful when you need to manage your keys separately. ```javascript const pems = await selfsigned.generate(null, { keyPair: { publicKey: '-----BEGIN PUBLIC KEY-----...', privateKey: '-----BEGIN PRIVATE KEY-----...' } }); ``` -------------------------------- ### Extended Key Usage (extKeyUsage) Extension Configuration Source: https://github.com/jfromaniello/selfsigned/blob/master/README.md Explains how to configure the `extKeyUsage` extension to specify the intended purposes of the certificate, such as server authentication, client authentication, or code signing. ```javascript { name: 'extKeyUsage', serverAuth: true, // TLS server authentication clientAuth: true, // TLS client authentication codeSigning: true, emailProtection: true, timeStamping: true } ``` -------------------------------- ### Generate Basic Self-Signed Certificate with Selfsigned Source: https://context7.com/jfromaniello/selfsigned/llms.txt Demonstrates the basic usage of the `selfsigned.generate()` function to create a self-signed certificate with default options. It returns PEM-formatted private key, public key, and certificate. Requires Node.js >= 15.6.0. ```javascript const selfsigned = require('selfsigned'); // Basic certificate generation with default options const pems = await selfsigned.generate(); console.log(pems); // { // private: '-----BEGIN PRIVATE KEY-----\n...', // public: '-----BEGIN PUBLIC KEY-----\n...', // cert: '-----BEGIN CERTIFICATE-----\n...', // fingerprint: 'XX:XX:XX...' // } ``` -------------------------------- ### Key Usage Extension Configuration Source: https://github.com/jfromaniello/selfsigned/blob/master/README.md Details the configuration options for the `keyUsage` extension, allowing specification of various cryptographic purposes like digital signature, key encipherment, and more. ```javascript { name: 'keyUsage', digitalSignature: true, nonRepudiation: true, keyEncipherment: true, dataEncipherment: true, keyAgreement: true, keyCertSign: true, // for CA certificates cRLSign: true, // for CA certificates encipherOnly: true, decipherOnly: true, critical: true } ``` -------------------------------- ### Create PKCS#7 Formatted Certificates Source: https://github.com/jfromaniello/selfsigned/blob/master/README.md Shows how to use the selfsigned/pkcs7 module to convert standard certificate PEMs into PKCS#7 format for better compatibility. ```javascript const selfsigned = require('selfsigned'); const { createPkcs7 } = require('selfsigned/pkcs7'); const pems = await selfsigned.generate(attrs); const pkcs7 = createPkcs7(pems.cert); console.log(pkcs7); ``` ```javascript const pems = await selfsigned.generate(null, { clientCertificate: true }); const clientPkcs7 = createPkcs7(pems.clientcert); ``` -------------------------------- ### Client Certificate Options Source: https://github.com/jfromaniello/selfsigned/blob/master/README.md Provides detailed options for customizing client certificate generation. ```APIDOC ## Client Certificate Options The `clientCertificate` option can be `true` for defaults, or an options object for full control: ### Method `POST` (Conceptual - actual implementation is a function call) ### Endpoint `selfsigned.generate()` ### Parameters #### Request Body (Conceptual - Options Object for `clientCertificate`) - **cn** (string) - Optional - Common name for the certificate (default: 'John Doe jdoe123'). - **keyType** (string) - Optional - Key type: 'rsa' or 'ec' (default: inherits from parent). - **keySize** (number) - Optional - Key size in bits (default: 2048, RSA only). - **curve** (string) - Optional - Elliptic curve name (default: 'P-256', EC only). - **algorithm** (string) - Optional - Signature algorithm (default: inherits from parent or 'sha1'). - **notBeforeDate** (Date) - Optional - Validity start date (default: now). - **notAfterDate** (Date) - Optional - Validity end date (default: notBeforeDate + 1 year). ### Request Example ```javascript const pems = await selfsigned.generate(null, { clientCertificate: { cn: 'jdoe', keyType: 'rsa', keySize: 4096, curve: 'P-256', algorithm: 'sha256', notBeforeDate: new Date(), notAfterDate: new Date('2026-01-01') } }); ``` Simple example with just a custom CN: ```javascript const pems = await selfsigned.generate(null, { clientCertificate: { cn: 'FooBar' } }); ``` ``` -------------------------------- ### Encrypt Private Key with Passphrase Source: https://github.com/jfromaniello/selfsigned/blob/master/README.md Demonstrates how to encrypt the generated private key using a passphrase with AES-256-CBC. The encrypted key is stored in PKCS#8 format. It also shows how to decrypt the key using Node.js 'crypto' module or directly with an HTTPS server. ```javascript const pems = await selfsigned.generate({ passphrase: 'my-secret-passphrase' }); ``` ```javascript const crypto = require('crypto'); // Decrypt the key const privateKey = crypto.createPrivateKey({ key: pems.private, passphrase: 'my-secret-passphrase' }); ``` ```javascript const https = require('https'); https.createServer({ key: pems.private, passphrase: 'my-secret-passphrase', cert: pems.cert }, app).listen(443); ``` -------------------------------- ### Certificate Output Structure Source: https://github.com/jfromaniello/selfsigned/blob/master/README.md Illustrates the structure of the output from the 'selfsigned.generate()' function, which includes the private key, public key, certificate, and fingerprint. ```javascript { private: '-----BEGIN PRIVATE KEY-----\n...', public: '-----BEGIN PUBLIC KEY-----\n...', cert: '-----BEGIN CERTIFICATE-----\n...', fingerprint: 'XX:XX:XX...' } ``` -------------------------------- ### Generate Certificate with Custom Extensions (JavaScript) Source: https://context7.com/jfromaniello/selfsigned/llms.txt Generates a self-signed certificate with customizable extensions such as basicConstraints, keyUsage, extKeyUsage, and subjectAltName. It supports various SAN types including DNS, IP addresses (IPv4/IPv6), email, and URIs. Also demonstrates generating a CA certificate with signing capabilities. ```javascript const selfsigned = require('selfsigned'); // Certificate with Subject Alternative Names (SAN) including IPv6 const pems = await selfsigned.generate( [{ name: 'commonName', value: 'localhost' }], { algorithm: 'sha256', extensions: [ { name: 'basicConstraints', cA: false, critical: true }, { name: 'keyUsage', digitalSignature: true, keyEncipherment: true, critical: true }, { name: 'extKeyUsage', serverAuth: true, clientAuth: true }, { name: 'subjectAltName', altNames: [ { type: 2, value: 'localhost' }, // DNS { type: 2, value: '*.localhost' }, // Wildcard DNS { type: 7, ip: '127.0.0.1' }, // IPv4 { type: 7, ip: '::1' }, // IPv6 { type: 1, value: 'admin@example.com' }, // Email { type: 6, value: 'http://example.com' } // URI ] } ] } ); // CA certificate with certificate signing capability const caCert = await selfsigned.generate( [{ name: 'commonName', value: 'My Root CA' }], { algorithm: 'sha256', extensions: [ { name: 'basicConstraints', cA: true, pathLenConstraint: 0, critical: true }, { name: 'keyUsage', keyCertSign: true, cRLSign: true, critical: true } ] } ); ``` -------------------------------- ### Generate Self-Signed Certificates with Elliptic Curve (EC) Keys Source: https://context7.com/jfromaniello/selfsigned/llms.txt Demonstrates generating certificates using Elliptic Curve (EC) cryptography, offering equivalent security to RSA with smaller key sizes and faster performance. Supports P-256, P-384, and P-521 curves. ```javascript const selfsigned = require('selfsigned'); // EC certificate with P-256 curve (default, 128-bit security) const pemsEC = await selfsigned.generate(null, { keyType: 'ec' }); // EC certificate with P-384 curve (192-bit security) const pems384 = await selfsigned.generate(null, { keyType: 'ec', curve: 'P-384', algorithm: 'sha384' }); // EC certificate with P-521 curve (256-bit security, strongest) const pems521 = await selfsigned.generate(null, { keyType: 'ec', curve: 'P-521', algorithm: 'sha512' }); // EC certificate with custom attributes const attrs = [ { name: 'commonName', value: 'ec-server.example.com' }, { name: 'organizationName', value: 'EC Test Corp' } ]; const pemsCustom = await selfsigned.generate(attrs, { keyType: 'ec' }); ``` -------------------------------- ### createPkcs7() Source: https://context7.com/jfromaniello/selfsigned/llms.txt Converts a PEM-encoded certificate into the PKCS#7 format. ```APIDOC ## createPkcs7(cert) ### Description Utility function to convert a standard PEM certificate string into a PKCS#7 formatted string. ### Parameters - **cert** (String) - Required - The PEM-encoded certificate string. ### Request Example const pkcs7 = createPkcs7(pems.cert); ### Response #### Success Response (200) - **pkcs7** (String) - The certificate in PKCS#7 format. ``` -------------------------------- ### Sign Certificate with Existing CA Source: https://github.com/jfromaniello/selfsigned/blob/master/README.md Explains how to generate a certificate that is signed by an existing Certificate Authority (CA) instead of being self-signed. This is beneficial for development environments where browser trust is required. ```javascript const fs = require('fs'); const selfsigned = require('selfsigned'); const pems = await selfsigned.generate([ { name: 'commonName', value: 'localhost' } ], { algorithm: 'sha256', ca: { key: fs.readFileSync('/path/to/ca.key', 'utf8'), cert: fs.readFileSync('/path/to/ca.crt', 'utf8') } }); ``` -------------------------------- ### Generate Client Certificates Source: https://github.com/jfromaniello/selfsigned/blob/master/README.md Generates client certificates signed by the original server key. The output includes additional client certificate fields. ```APIDOC ## Generate Client Certificates For environments where servers require client certificates, you can generate client keys signed by the original (server) key. ### Method `POST` (Conceptual - actual implementation is a function call) ### Endpoint `selfsigned.generate()` ### Parameters #### Request Body (Conceptual - Options Object) - **clientCertificate** (boolean | object) - Optional - If `true`, generates default client certificates. If an object, provides custom options for client certificate generation. ### Request Example ```javascript const pems = await selfsigned.generate(null, { clientCertificate: true }); console.log(pems); ``` ### Response #### Success Response (200) - **private** (string) - The generated private key. - **public** (string) - The generated public key. - **cert** (string) - The generated server certificate. - **fingerprint** (string) - The fingerprint of the server certificate. - **clientprivate** (string) - The generated client private key. - **clientpublic** (string) - The generated client public key. - **clientcert** (string) - The generated client certificate. #### Response Example ```json { "private": "-----BEGIN PRIVATE KEY-----\n...", "public": "-----BEGIN PUBLIC KEY-----\n...", "cert": "-----BEGIN CERTIFICATE-----\n...", "fingerprint": "XX:XX:XX:...", "clientprivate": "-----BEGIN PRIVATE KEY-----\n...", "clientpublic": "-----BEGIN PUBLIC KEY-----\n...", "clientcert": "-----BEGIN CERTIFICATE-----\n..." } ``` ``` -------------------------------- ### Generate Self-Signed Certificate with Custom Attributes and Options Source: https://context7.com/jfromaniello/selfsigned/llms.txt Shows how to generate a self-signed certificate with custom subject attributes (like common name) and configure options such as the hashing algorithm and key size. This allows for more specific certificate configurations. ```javascript const selfsigned = require('selfsigned'); // Certificate with custom common name and SHA-256 algorithm const attrs = [{ name: 'commonName', value: 'localhost' }]; const pems = await selfsigned.generate(attrs, { algorithm: 'sha256', keySize: 2048 }); // Certificate with full subject attributes const fullAttrs = [ { name: 'commonName', value: 'example.com' }, { name: 'countryName', value: 'US' }, { shortName: 'ST', value: 'California' }, { name: 'localityName', value: 'San Francisco' }, { name: 'organizationName', value: 'My Company' }, { shortName: 'OU', value: 'Engineering' } ]; const pemsFull = await selfsigned.generate(fullAttrs, { algorithm: 'sha256' }); ``` -------------------------------- ### Basic Constraints Extension Configuration Source: https://github.com/jfromaniello/selfsigned/blob/master/README.md Defines the structure for configuring the `basicConstraints` extension, specifying whether the certificate is a Certificate Authority (CA) and its path length constraint. ```javascript { name: 'basicConstraints', cA: true, // is this a CA certificate? pathLenConstraint: 0, // max depth of valid cert chain (optional) critical: true // mark as critical extension } ``` -------------------------------- ### Client Certificates Source: https://context7.com/jfromaniello/selfsigned/llms.txt Generate client certificates for mutual TLS (mTLS) authentication, either basic or with custom options, including EC certificates. ```APIDOC ## Client Certificates Generate client certificates signed by the server certificate for mutual TLS (mTLS) authentication scenarios. ### Request Example ```javascript const selfsigned = require('selfsigned'); // Basic client certificate generation const pems = await selfsigned.generate(null, { clientCertificate: true }); console.log(pems); // { // private: '-----BEGIN PRIVATE KEY-----\n...', // public: '-----BEGIN PUBLIC KEY-----\n...', // cert: '-----BEGIN CERTIFICATE-----\n...', // fingerprint: 'XX:XX:XX:...', // clientprivate: '-----BEGIN PRIVATE KEY-----\n...', // clientpublic: '-----BEGIN PUBLIC KEY-----\n...', // clientcert: '-----BEGIN CERTIFICATE-----\n...' // } // Client certificate with custom options const customClientPems = await selfsigned.generate( [{ name: 'commonName', value: 'server.example.com' }], { algorithm: 'sha256', clientCertificate: { cn: 'client-user-123', keySize: 4096, algorithm: 'sha256', notBeforeDate: new Date(), notAfterDate: new Date('2026-01-01') } } ); // EC client certificate const ecClientPems = await selfsigned.generate(null, { keyType: 'ec', curve: 'P-256', clientCertificate: { cn: 'ec-client', keyType: 'ec', curve: 'P-256' } }); ``` ### Response Example ```json { "private": "-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----", "public": "-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----", "cert": "-----BEGIN CERTIFICATE-----\n...\n-----END CERTIFICATE-----", "fingerprint": "XX:XX:XX:...", "clientprivate": "-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----", "clientpublic": "-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----", "clientcert": "-----BEGIN CERTIFICATE-----\n...\n-----END CERTIFICATE-----" } ``` ``` -------------------------------- ### Define X.509 Certificate Attributes Source: https://github.com/jfromaniello/selfsigned/blob/master/README.md Shows how to define standard X.509 attributes for certificate generation, including common name, country, state, locality, organization, and organizational unit. ```javascript const attrs = [ { name: 'commonName', value: 'example.org' }, { name: 'countryName', value: 'US' }, { shortName: 'ST', value: 'Virginia' }, { name: 'localityName', value: 'Blacksburg' }, { name: 'organizationName', value: 'Test' }, { shortName: 'OU', value: 'Test' } ]; ``` -------------------------------- ### Generate Client Certificates for mTLS (JavaScript) Source: https://context7.com/jfromaniello/selfsigned/llms.txt Generates client certificates for mutual TLS (mTLS) authentication. This includes basic client certificate generation, creating client certificates with custom options like key size and validity dates, and generating Elliptic Curve (EC) client certificates. ```javascript const selfsigned = require('selfsigned'); // Basic client certificate generation const pems = await selfsigned.generate(null, { clientCertificate: true }); console.log(pems); // { // private: '-----BEGIN PRIVATE KEY-----\n...', // public: '-----BEGIN PUBLIC KEY-----\n...', // cert: '-----BEGIN CERTIFICATE-----\n...', // fingerprint: 'XX:XX:XX:...', // clientprivate: '-----BEGIN PRIVATE KEY-----\n...', // clientpublic: '-----BEGIN PUBLIC KEY-----\n...', // clientcert: '-----BEGIN CERTIFICATE-----\n...' // } // Client certificate with custom options const customClientPems = await selfsigned.generate( [{ name: 'commonName', value: 'server.example.com' }], { algorithm: 'sha256', clientCertificate: { cn: 'client-user-123', keySize: 4096, algorithm: 'sha256', notBeforeDate: new Date(), notAfterDate: new Date('2026-01-01') } } ); // EC client certificate const ecClientPems = await selfsigned.generate(null, { keyType: 'ec', curve: 'P-256', clientCertificate: { cn: 'ec-client', keyType: 'ec', curve: 'P-256' } }); ``` -------------------------------- ### Subject Alternative Name (subjectAltName) Extension Configuration Source: https://github.com/jfromaniello/selfsigned/blob/master/README.md Illustrates the configuration for the `subjectAltName` extension, enabling the inclusion of various identifiers like email addresses, DNS names, URIs, and IP addresses. ```javascript { name: 'subjectAltName', altNames: [ { type: 1, value: 'user@example.com' }, // email (rfc822Name) { type: 2, value: 'example.com' }, // DNS name { type: 2, value: '*.example.com' }, // wildcard DNS { type: 6, value: 'http://example.com/webid' }, // URI { type: 7, ip: '127.0.0.1' }, // IPv4 address { type: 7, ip: '::1' } // IPv6 address ] } ``` -------------------------------- ### Configure Custom Validity Period for Self-Signed Certificates Source: https://context7.com/jfromaniello/selfsigned/llms.txt Illustrates how to set a custom validity period for generated certificates using the `notBeforeDate` and `notAfterDate` options. This is useful for controlling certificate lifespans, such as for short-term testing or long-term deployment. ```javascript const selfsigned = require('selfsigned'); // Certificate valid for 30 days const notBefore = new Date(); const notAfter = new Date(); notAfter.setDate(notAfter.getDate() + 30); const pems = await selfsigned.generate( [{ name: 'commonName', value: 'short-lived.local' }], { algorithm: 'sha256', notBeforeDate: notBefore, notAfterDate: notAfter } ); // Certificate valid for 2 years starting from a specific date const startDate = new Date('2025-01-01T00:00:00Z'); const endDate = new Date('2027-01-01T00:00:00Z'); const longLivedPems = await selfsigned.generate( [{ name: 'commonName', value: 'long-lived.local' }], { algorithm: 'sha256', notBeforeDate: startDate, notAfterDate: endDate } ); ``` -------------------------------- ### Default Extensions Used by selfsigned Source: https://github.com/jfromaniello/selfsigned/blob/master/README.md Lists the default certificate extensions applied by the 'selfsigned' module when no custom extensions are explicitly provided. ```javascript [ { name: 'basicConstraints', cA: false, critical: true }, { name: 'keyUsage', digitalSignature: true, keyEncipherment: true, critical: true }, { name: 'extKeyUsage', serverAuth: true, clientAuth: true }, { name: 'subjectAltName', altNames: [ { type: 2, value: commonName }, // For localhost, also includes: { type: 7, ip: '127.0.0.1' } kwamba ] ``` -------------------------------- ### generate() - Certificate Generation Source: https://context7.com/jfromaniello/selfsigned/llms.txt Generates a new self-signed X.509 certificate with optional subject attributes and configuration settings. ```APIDOC ## generate(attributes, options) ### Description Generates a self-signed X.509 certificate asynchronously. Returns an object containing the private key, public key, certificate, and fingerprint. ### Method Function Call (Async) ### Parameters #### Attributes (Array) - **name** (string) - Optional - The attribute name (e.g., 'commonName', 'countryName'). - **value** (string) - Optional - The value for the attribute. #### Options (Object) - **algorithm** (string) - Optional - Hashing algorithm (e.g., 'sha256'). - **keySize** (number) - Optional - Size of the RSA key (default 2048). - **keyType** (string) - Optional - Type of key ('rsa' or 'ec'). - **curve** (string) - Optional - Elliptic curve type ('P-256', 'P-384', 'P-521'). - **notBeforeDate** (Date) - Optional - Start date of validity. - **notAfterDate** (Date) - Optional - End date of validity. ### Request Example const pems = await selfsigned.generate([{ name: 'commonName', value: 'localhost' }], { algorithm: 'sha256' }); ### Response #### Success Response - **private** (string) - PEM encoded private key. - **public** (string) - PEM encoded public key. - **cert** (string) - PEM encoded certificate. - **fingerprint** (string) - Certificate fingerprint. ``` -------------------------------- ### Generate Basic Self-Signed Certificate Source: https://github.com/jfromaniello/selfsigned/blob/master/README.md Generates a self-signed X.509 certificate with a common name using the 'selfsigned' module. The function is async and returns a Promise containing the certificate details. ```javascript const selfsigned = require('selfsigned'); const attrs = [{ name: 'commonName', value: 'contoso.com' }]; const pems = await selfsigned.generate(attrs); console.log(pems); ``` -------------------------------- ### Certificate Extensions Source: https://context7.com/jfromaniello/selfsigned/llms.txt Customize certificate extensions such as basicConstraints, keyUsage, extKeyUsage, and subjectAltName to control certificate usage and validity. ```APIDOC ## Certificate Extensions Customize certificate extensions including basicConstraints, keyUsage, extKeyUsage, and subjectAltName. Extensions control how the certificate can be used and what hosts/IPs it's valid for. ### Request Example ```javascript const selfsigned = require('selfsigned'); // Certificate with Subject Alternative Names (SAN) including IPv6 const pems = await selfsigned.generate( [{ name: 'commonName', value: 'localhost' }], { algorithm: 'sha256', extensions: [ { name: 'basicConstraints', cA: false, critical: true }, { name: 'keyUsage', digitalSignature: true, keyEncipherment: true, critical: true }, { name: 'extKeyUsage', serverAuth: true, clientAuth: true }, { name: 'subjectAltName', altNames: [ { type: 2, value: 'localhost' }, // DNS { type: 2, value: '*.localhost' }, // Wildcard DNS { type: 7, ip: '127.0.0.1' }, // IPv4 { type: 7, ip: '::1' }, // IPv6 { type: 1, value: 'admin@example.com' }, // Email { type: 6, value: 'http://example.com' } // URI ] } ] } ); // CA certificate with certificate signing capability const caCert = await selfsigned.generate( [{ name: 'commonName', value: 'My Root CA' }], { algorithm: 'sha256', extensions: [ { name: 'basicConstraints', cA: true, pathLenConstraint: 0, critical: true }, { name: 'keyUsage', keyCertSign: true, cRLSign: true, critical: true } ] } ); ``` ### Response Example ```json { "private": "-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----", "public": "-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----", "cert": "-----BEGIN CERTIFICATE-----\n...\n-----END CERTIFICATE-----", "fingerprint": "XX:XX:XX:..." } ``` ``` -------------------------------- ### Remove Callback Support Source: https://github.com/jfromaniello/selfsigned/blob/master/CHANGELOG.md Shows the removal of callback-based certificate generation in favor of the modern Promise-based API. ```javascript // Old (v4.x) selfsigned.generate(attrs, options, function(err, pems) { ... }); // New (v5.x) const pems = await selfsigned.generate(attrs, options); ``` -------------------------------- ### selfsigned.generate() Source: https://context7.com/jfromaniello/selfsigned/llms.txt Generates a self-signed certificate using provided attributes and configuration options, including support for existing key pairs. ```APIDOC ## selfsigned.generate(attrs, options) ### Description Generates a self-signed certificate and private key. Can accept existing key pairs to maintain consistency across sessions. ### Parameters #### attrs - **attrs** (Array) - Optional - Array of objects defining certificate attributes (e.g., commonName). #### options - **options** (Object) - Required - Configuration object including algorithm, keySize, and keyPair. - **options.keyPair** (Object) - Optional - Existing { publicKey, privateKey } to use. - **options.algorithm** (String) - Optional - Hashing algorithm (default: 'sha256'). ### Request Example await selfsigned.generate([{ name: 'commonName', value: 'localhost' }], { algorithm: 'sha256' }); ### Response #### Success Response (200) - **private** (String) - The private key in PEM format. - **public** (String) - The public key in PEM format. - **cert** (String) - The generated certificate in PEM format. - **fingerprint** (String) - The certificate fingerprint. ```