npm package: @multicloud-io/multicloud-connection-js
Description: Shared TypeScript/JavaScript library for connecting to Multicloud servers with mTLS authentication
Author: Multicloud Team
Latest version: 1.0.18

# Multicloud Connection Library (TypeScript/JavaScript)

A comprehensive TypeScript/JavaScript library for connecting to Multicloud servers with mTLS authentication, configuration management, and full REST API support.

🔒 **IMPORTANT**: This library is designed for **server-side use only**. Never expose Multicloud credentials or use this library in client/browser environments.

## 🚀 Quick Start

### Installation

```bash
npm install @multicloud/connection-js
```

### Basic Usage

```typescript
import { MulticloudConfig, MulticloudRESTClient } from '@multicloud/connection-js';

// Basic usage with default configuration
const params = MulticloudConfig.getConnectionParams();
const client = new MulticloudRESTClient(params);
const clusters = await client.getClusters();
```

### Quick Helper Functions

```typescript
import { createMulticloudClient, isMulticloudEnabled } from '@multicloud/connection-js';

// Check if multicloud is configured
if (isMulticloudEnabled()) {
  // Create client with defaults
  const client = createMulticloudClient({ debug: true });
  const clusters = await client.getClusters();
} else {
  // Use fallback/mock data
}
```

## 📖 Features

### Configuration Management
- **Multiple Configuration Sources**: Environment variables, YAML files, and direct parameters
- **Precedence Handling**: Direct overrides > Environment variables > Config file > Defaults
- **Variable Substitution**: Support for `${variable}` syntax in YAML files
- **Flexible Environment Prefixes**: Customize environment variable names per project

### Authentication
- **mTLS Client Certificates**: Full support for mutual TLS authentication
- **JWT Access Tokens**: Support for Keycloak-issued JWT tokens via Authorization header
- **SSL Verification Controls**: Enable/disable SSL verification for development
- **Certificate Management**: Automatic certificate loading with proper error handling
- **Security Validation**: Production mode requires certificates

### REST API Client
- **Complete API Coverage**: All Multicloud endpoints (clusters, jobs, servers)
- **Proper Error Handling**: Structured exceptions for different error types
- **Connection Testing**: Built-in connectivity diagnostics
- **Timeout Management**: Configurable request timeouts
- **Debug Logging**: Optional verbose logging for troubleshooting

## 🔧 Configuration

### Environment Variables

The library supports configurable environment variable prefixes (default: `MULTICLOUD_`):

```bash
# Default prefix (MULTICLOUD_)
MULTICLOUD_URL=https://backend.multicloud.io:8443
MULTICLOUD_CLIENT_CERT=/path/to/client.crt
MULTICLOUD_CLIENT_KEY=/path/to/client.key
MULTICLOUD_VERIFY_SSL=false
MULTICLOUD_TIMEOUT=15000
MULTICLOUD_DEBUG=true

# Custom prefix (MY_APP_MULTICLOUD_)
MY_APP_MULTICLOUD_URL=https://backend.multicloud.io:8443
MY_APP_MULTICLOUD_CLIENT_CERT=/path/to/client.crt
# ... etc
```

### Configuration File

Default location: `~/.multicloud/config.yaml`

```yaml
multicloud_url: https://backend.multicloud.io:8443
verify_ssl: false
timeout: 15
debug: false

certificates:
  dir: ~/.multicloud
  client-cert: ${dir}/multicloud-client.crt
  client-key: ${dir}/multicloud-client.key
```

### Configuration Precedence

1. **Direct overrides** (highest priority)
2. **Environment variables**
3. **Configuration file**
4. **Default values** (lowest priority)

## 🛠️ API Reference

### MulticloudConfig

```typescript
// Get connection parameters with default settings
const params = MulticloudConfig.getConnectionParams();

// Get connection parameters with overrides
const params = MulticloudConfig.getConnectionParams(
  { debug: true, timeout: 10000 },
  { envPrefix: 'MY_APP_MULTICLOUD_' }
);

// Check if multicloud is enabled
const enabled = MulticloudConfig.isEnabled();

// Get configuration info for debugging
const info = MulticloudConfig.getConfigInfo();
```

### MulticloudRESTClient

```typescript
const client = new MulticloudRESTClient(params);

// Test connection
const connected = await client.testConnection();

// Cluster operations
const clusters = await client.getClusters();
const appClusters = await client.getApplicationClusters(1);
const cluster = await client.getCluster(123);

// Job operations
const jobs = await client.getJobs();
const job = await client.getJob(456);
const newJob = await client.createJob({ name: 'My Job', clusterId: 123 });

// Server operations
const servers = await client.getServers();
const server = await client.getServer(789);
await client.restartServer(789);
```

### JWT Authentication

```typescript
// Frontend passes access token after user login to Keycloak
const client = createMulticloudClient({
  accessToken: userJwtToken  // Obtained from Keycloak after user authentication
});

// Updating token dynamically (e.g., after token refresh)
client.setAccessToken(newAccessToken);

// Clearing token (e.g., on user logout)
client.clearAccessToken();

// Mixed authentication (mTLS + JWT for service-to-service + user context)
const client = createMulticloudClient({
  clientCert: '/path/to/cert.pem',
  clientKey: '/path/to/key.pem',
  accessToken: userJwtToken  // User's JWT token from frontend login
});
```

### Exception Handling

```typescript
import {
  MulticloudConnectionError,
  MulticloudAuthenticationError,
  MulticloudConfigurationError,
  MulticloudNetworkError,
  MulticloudResponseError
} from '@multicloud/connection-js';

try {
  const client = createMulticloudClient();
  const clusters = await client.getClusters();
} catch (error) {
  if (error instanceof MulticloudAuthenticationError) {
    // Handle certificate/auth issues
  } else if (error instanceof MulticloudNetworkError) {
    // Handle network/connectivity issues
  } else if (error instanceof MulticloudConfigurationError) {
    // Handle configuration problems
  }
}
```

## 🌍 Multi-Project Usage

### Different Environment Prefixes

```typescript
// Project A uses default prefix
const clientA = createMulticloudClient();

// Project B uses custom prefix
const clientB = createMulticloudClient(
  {},
  { envPrefix: 'PROJECT_B_MULTICLOUD_' }
);
```

### Different Configuration Files

```typescript
const client = createMulticloudClient(
  {},
  { configFile: '/etc/myapp/multicloud.yaml' }
);
```

### Production vs Development

```typescript
const client = createMulticloudClient(
  {},
  { isProduction: process.env.NODE_ENV === 'production' }
);
```

## 🧪 Testing and Development

### Build the Library

```bash
npm run build
```

### Development Mode

```bash
npm run build:watch
```

### Testing

```bash
npm test
```

## 📦 Integration Examples

### Next.js API Route

```typescript
// pages/api/clusters.ts
import { createMulticloudClient, isMulticloudEnabled } from '@multicloud/connection-js';

export default async function handler(req, res) {
  try {
    if (!isMulticloudEnabled()) {
      return res.status(503).json({ error: 'Multicloud not configured' });
    }

    const client = createMulticloudClient();
    const clusters = await client.getClusters();
    res.json(clusters);
  } catch (error) {
    console.error('Multicloud error:', error);
    res.status(500).json({ error: 'Failed to fetch clusters' });
  }
}
```

### Express.js Middleware

```typescript
import express from 'express';
import { createMulticloudClient } from '@multicloud/connection-js';

const app = express();

app.get('/api/clusters', async (req, res) => {
  try {
    const client = createMulticloudClient();
    const clusters = await client.getClusters();
    res.json(clusters);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});
```

### CLI Application

```typescript
#!/usr/bin/env node
import { createMulticloudClient, MulticloudConnectionError } from '@multicloud/connection-js';

async function main() {
  try {
    const client = createMulticloudClient({ debug: true });
    const clusters = await client.getClusters();
    
    console.log('Available clusters:');
    clusters.forEach(cluster => {
      console.log(`- ${cluster.name} (${cluster.region})`);
    });
  } catch (error) {
    if (error instanceof MulticloudConnectionError) {
      console.error('Failed to connect to Multicloud:', error.message);
      process.exit(1);
    }
    throw error;
  }
}

main().catch(console.error);
```

## 🔍 Debugging

### Enable Debug Logging

```typescript
const client = createMulticloudClient({ debug: true });
```

### Check Configuration

```typescript
import { MulticloudConfig } from '@multicloud/connection-js';

const info = MulticloudConfig.getConfigInfo();
console.log('Configuration info:', info);
```

### Test Connection

```typescript
const client = createMulticloudClient();
try {
  const connected = await client.testConnection();
  console.log('Connection test:', connected ? 'SUCCESS' : 'FAILED');
} catch (error) {
  console.error('Connection test failed:', error.message);
}
```

## 🤝 Contributing

1. **Install dependencies**: `npm install`
2. **Make changes**: Edit source files in `src/`
3. **Build**: `npm run build`
4. **Test**: `npm test`
5. **Submit PR**: Create a pull request with your changes

## 📄 License

MIT - See LICENSE file for details.

## 🔗 Related Documentation

- **[Python Version](../python/README.md)** - Python implementation of the same library
- **[Connection Guide](../docs/connection/multicloud-connection-guide.md)** - Detailed connection documentation
- **[Multi-Project Usage](../docs/connection/reuse-across-projects.md)** - Advanced usage patterns