https-server-mkcert.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. const https = require('https');
  2. const fs = require('fs');
  3. const path = require('path');
  4. const { execSync } = require('child_process');
  5. const selfsigned = require('../');
  6. async function main() {
  7. // Get mkcert's CAROOT path
  8. let caroot;
  9. try {
  10. caroot = execSync('mkcert -CAROOT', { encoding: 'utf8' }).trim();
  11. } catch (err) {
  12. console.error('Error: mkcert is not installed or not in PATH');
  13. console.error('Install mkcert: https://github.com/FiloSottile/mkcert');
  14. process.exit(1);
  15. }
  16. const caKeyPath = path.join(caroot, 'rootCA-key.pem');
  17. const caCertPath = path.join(caroot, 'rootCA.pem');
  18. // Check if CA files exist
  19. if (!fs.existsSync(caKeyPath) || !fs.existsSync(caCertPath)) {
  20. console.error('Error: mkcert CA files not found');
  21. console.error('Run "mkcert -install" first to create the local CA');
  22. process.exit(1);
  23. }
  24. console.log('Using mkcert CA from:', caroot);
  25. // Read CA certificate and key
  26. const caKey = fs.readFileSync(caKeyPath, 'utf8');
  27. const caCert = fs.readFileSync(caCertPath, 'utf8');
  28. // Generate a certificate signed by mkcert's CA
  29. const pems = await selfsigned.generate([
  30. { name: 'commonName', value: 'localhost' }
  31. ], {
  32. days: 365,
  33. keySize: 2048,
  34. algorithm: 'sha256',
  35. ca: {
  36. key: caKey,
  37. cert: caCert
  38. }
  39. });
  40. // Create HTTPS server with the generated certificate
  41. const server = https.createServer({
  42. key: pems.private,
  43. cert: pems.cert
  44. }, (req, res) => {
  45. res.writeHead(200, { 'Content-Type': 'text/plain' });
  46. res.end('Hello from HTTPS server with mkcert CA!\n');
  47. });
  48. const port = 3443;
  49. server.listen(port, () => {
  50. console.log(`HTTPS server running at https://localhost:${port}/`);
  51. console.log('Certificate fingerprint:', pems.fingerprint);
  52. console.log('\nSince this certificate is signed by mkcert\'s CA,');
  53. console.log('your browser should trust it automatically (if mkcert -install was run).');
  54. console.log('\nTest with: curl https://localhost:' + port);
  55. });
  56. }
  57. main().catch(console.error);