# @push.rocks/smartnginx

A TypeScript library for controlling Nginx from Node.js, with support for generating and managing Nginx configurations dynamically.

# readme.md for @push.rocks/smartnginx

Control Nginx programmatically from Node.js with full TypeScript support 🚀

## Issue Reporting and Security

For reporting bugs, issues, or security vulnerabilities, please visit [community.foss.global/](https://community.foss.global/). This is the central community hub for all issue reporting. Developers who sign and comply with our contribution agreement and go through identification can also get a [code.foss.global/](https://code.foss.global/) account to submit Pull Requests directly.

## Features

- 🎯 **Dynamic Configuration** - Generate and manage Nginx configs on the fly
- 🔒 **SSL/TLS Ready** - Built-in support for SSL certificates with automatic HTTP→HTTPS redirects
- 🔄 **Hot Reload** - Apply configuration changes without downtime
- 📦 **Zero-Config Defaults** - Self-signed certificates auto-generated for immediate testing
- 🎛️ **Reverse Proxy Made Easy** - Set up proxy hosts with a single method call
- 🧠 **Smart Diffing** - Only reloads Nginx when configurations actually change
- 📝 **TypeScript First** - Full type definitions included

## Install

```bash
pnpm add @push.rocks/smartnginx
# or
npm install @push.rocks/smartnginx
```

> **Prerequisites**: Nginx must be installed and available in your system PATH.

## Quick Start

```typescript
import { SmartNginx } from '@push.rocks/smartnginx';

// Create a SmartNginx instance with a default fallback URL
const nginx = new SmartNginx({
  defaultProxyUrl: 'https://your-default-site.com'
});

// Add a reverse proxy host
nginx.addHostCandidate({
  hostName: 'api.example.com',
  destination: 'localhost',
  destinationPort: 3000,
  privateKey: '<your-ssl-private-key>',
  publicKey: '<your-ssl-certificate>'
});

// Deploy and start Nginx
await nginx.deploy();
```

That's it! Your reverse proxy is now running 🎉

## Usage

### Creating the SmartNginx Instance

The `SmartNginx` class is your main interface for managing Nginx:

```typescript
import { SmartNginx } from '@push.rocks/smartnginx';

const nginx = new SmartNginx({
  defaultProxyUrl: 'https://fallback.example.com',  // Where unmatched requests go
  logger: myCustomLogger  // Optional: pass a @push.rocks/smartlog instance
});
```

### Adding Host Configurations

Each host represents a domain/subdomain with its proxy rules and SSL certificates:

```typescript
// Add a host using addHostCandidate()
const myHost = nginx.addHostCandidate({
  hostName: 'app.example.com',        // Domain name
  destination: '127.0.0.1',           // Backend server address
  destinationPort: 8080,              // Backend port
  privateKey: sslPrivateKeyPem,       // SSL private key (PEM format)
  publicKey: sslCertificatePem        // SSL certificate (PEM format)
});
```

### Multi-Host Setup

Run multiple sites through a single Nginx instance:

```typescript
// Production API
nginx.addHostCandidate({
  hostName: 'api.myapp.com',
  destination: 'localhost',
  destinationPort: 3000,
  privateKey: apiPrivateKey,
  publicKey: apiCertificate
});

// Admin panel
nginx.addHostCandidate({
  hostName: 'admin.myapp.com',
  destination: 'localhost',
  destinationPort: 4000,
  privateKey: adminPrivateKey,
  publicKey: adminCertificate
});

// Staging environment
nginx.addHostCandidate({
  hostName: 'staging.myapp.com',
  destination: '192.168.1.100',
  destinationPort: 8080,
  privateKey: stagingPrivateKey,
  publicKey: stagingCertificate
});

// Deploy all at once
await nginx.deploy();
```

### Deploying Configurations

The `deploy()` method is smart about changes:

```typescript
// First deploy - writes configs and starts Nginx
await nginx.deploy();

// Add more hosts dynamically
nginx.addHostCandidate({
  hostName: 'newsite.example.com',
  destination: 'localhost',
  destinationPort: 5000,
  privateKey: newPrivateKey,
  publicKey: newCertificate
});

// Second deploy - detects changes, updates configs, hot-reloads Nginx
await nginx.deploy();

// If you call deploy() with no changes, it skips the reload (efficient!)
await nginx.deploy(); // → "hosts have not diverged, skipping nginx reload"
```

### Querying Deployed Hosts

```typescript
// Get all deployed hosts
const hosts = await nginx.listDeployedHosts();
console.log(`Running ${hosts.length} hosts`);

// Find a specific host by domain
const apiHost = nginx.getDeployedNginxHostByHostName('api.example.com');
if (apiHost) {
  console.log(`API proxying to ${apiHost.destination}:${apiHost.destinationPort}`);
}
```

### Removing Hosts

```typescript
const hostToRemove = nginx.getDeployedNginxHostByHostName('staging.myapp.com');
if (hostToRemove) {
  await nginx.removeDeployedHost(hostToRemove);
  // Nginx automatically reloaded with updated config
}
```

### Stopping Nginx

```typescript
// Gracefully stop the Nginx process
await nginx.stop();
```

## Generated Configuration

SmartNginx generates production-ready Nginx configurations:

**For each host, you get:**
- HTTP (port 80) → HTTPS (port 443) automatic redirect
- Upstream with keepalive connections (100 idle connections)
- WebSocket-friendly proxy settings (HTTP/1.1, no buffering)
- Proper proxy headers (`X-Real-IP`, `X-Forwarded-For`, `X-Forwarded-Proto`)
- Smart failover (`proxy_next_upstream` on errors, timeouts, 404/429/500/502)

**Default server:**
- Self-signed certificate for unmatched domains
- Redirects to your configured `defaultProxyUrl`

## Architecture

```
┌─────────────────────────────────────────────────────────────┐
│                      SmartNginx                             │
├─────────────────────────────────────────────────────────────┤
│  hostCandidates[]  →  deploy()  →  deployedHosts[]         │
│                          ↓                                  │
│                    NginxProcess                             │
│                    (start/reload/stop)                      │
└─────────────────────────────────────────────────────────────┘
                           ↓
┌─────────────────────────────────────────────────────────────┐
│                    Generated Files                          │
├─────────────────────────────────────────────────────────────┤
│  nginxconfig/                                               │
│  ├── nginx.conf              (main config)                  │
│  └── hosts/                                                 │
│      ├── default.private.pem (self-signed key)             │
│      ├── default.public.pem  (self-signed cert)            │
│      ├── api.example.com.conf                              │
│      ├── api.example.com.private.pem                       │
│      └── api.example.com.public.pem                        │
└─────────────────────────────────────────────────────────────┘
```

## API Reference

### SmartNginx

| Method | Description |
|--------|-------------|
| `addHostCandidate(config)` | Add a new host configuration |
| `deploy()` | Write configs and start/reload Nginx |
| `listDeployedHosts()` | Get all currently deployed hosts |
| `getDeployedNginxHostByHostName(hostname)` | Find a host by domain name |
| `removeDeployedHost(host)` | Remove a host and reload Nginx |
| `stop()` | Gracefully stop Nginx |

### IHostConfig

```typescript
interface IHostConfig {
  hostName: string;        // Domain name (e.g., 'api.example.com')
  destination: string;     // Backend server IP/hostname
  destinationPort: number; // Backend port
  privateKey: string;      // SSL private key (PEM)
  publicKey: string;       // SSL certificate (PEM)
}
```

### NginxHost

Each host instance exposes:
- `hostName` - The configured domain
- `destination` - Backend address
- `destinationPort` - Backend port
- `configString` - The generated Nginx config (after deploy)
- `deploy()` - Write this host's config files

## License and Legal Information

This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository.

**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.

### Trademarks

This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.

### Company Information

Task Venture Capital GmbH
Registered at District court Bremen HRB 35230 HB, Germany

For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.

By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.

# changelog.md for @push.rocks/smartnginx

## 2025-11-27 - 2.0.54 - fix(package)
Pin package manager to pnpm@10.18.1 in package.json

- Added packageManager field to package.json to pin pnpm to 10.18.1 with integrity hash
- No runtime code changes; only package metadata updated

## 2025-11-27 - 2.0.53 - fix(core)
Refactor filesystem usage to smartfs async provider, update dependencies, tests and nginx config paths

- Replace @push.rocks/smartfile usage with @push.rocks/smartfs and introduce a shared SmartFs instance in plugins
- Convert sync file operations to async fs APIs (plugins.fs.file(...).write / plugins.fs.directory(...).create) in SmartNginx and NginxHost
- Adjust package.json: update test/build scripts, replace dependencies/devDependencies to new packages (@push.rocks/smartfs, @git.zone/*), and update versions
- Update test imports to new tapbundle path and node:path; export default tap.start() and remove unused Qenv instantiation
- Update internal path imports to 'node:path' and refactor smartnginx.plugins exports
- Change generated nginx certificate/config paths in configs from /mnt/HC_Volume_11396573/... to /mnt/data/... and regenerate default cert files
- Remove CI config (.gitlab-ci.yml) from repository

## 2024-05-29 - 2.0.52 - maintenance
Various metadata and TypeScript configuration updates; release 2.0.52.

- Update package description.
- Update tsconfig.
- Update npmextra.json (githost) entries across multiple commits.
- Release tag for 2.0.52.

## 2023-07-26 - 2.0.51 - maintenance
Org migration and core fixes; release 2.0.51.

- Switch to new organization scheme.
- fix(core): miscellaneous updates.
- Release tag for 2.0.51.

## 2019-01-09..2019-08-20 - 2.0.19..2.0.50 - maintenance (multiple patch releases)
Series of incremental patch releases with small fixes and cleanups.

- Many patch releases across the 2.0.x line (2.0.19 through 2.0.50).
- Multiple "fix(core): update" commits addressing internal issues.
- CI and cleanup fixes (including 2.0.38 cleanup).
- Release tags for each patch.

## 2018-08-10 - 2.0.0 - breaking
Major release and scope / packaging changes.

- 2.0.0 release with core updates.
- BREAKING CHANGE: change scope to @pushrocks (package scope/name changed).
- Various CI and core fixes accompanying the major release.

## 2016-08-03..2016-07-25 - 1.0.6..1.0.0 - release / maintenance
1.x series consolidations, dependency updates and interface exports.

- Update dependencies and types.
- Consolidate naming and start exporting interfaces.
- Add license.
- Release tags for 1.0.0 through 1.0.6.

## 2016-07-06..2016-07-25 - 0.0.0..0.1.0 - initial development
Initial implementation and feature work establishing core functionality.

- Initial project setup, README and CI added.
- Implement nginx communication and child process handling.
- Start storing generated configs to filesystem and improve config handling.
- Add snippets support and tests; multiple README improvements.
- Early releases and version tags (0.0.0 through 0.1.0).