npm package: @subu1979/saml2
Description: Comprehensive SAML 2.0 implementation for Node.js covering all major use cases
Author: subu1979
Latest version: 1.0.0

# SAML 2.0 - Comprehensive Node.js Implementation

A complete, production-ready SAML 2.0 implementation for Node.js that covers all major use cases from the OASIS specifications.

## 🚀 Features

### Core SAML 2.0 Use Cases Implemented

1. **Web Browser SSO Profile**
   - SP-Initiated Single Sign-On (Redirect/POST bindings)
   - IdP-Initiated Single Sign-On (POST binding)
   - Support for ForceAuthn and Passive authentication

2. **Enhanced Client/Proxy (ECP) Profile**
   - PAOS binding support
   - SOAP envelope handling
   - ECP-specific authentication flows

3. **Single Logout Profile**
   - SP-initiated logout
   - IdP-initiated logout
   - Multiple SP logout support
   - Session termination

4. **Identity Federation**
   - Metadata generation (SP and IdP)
   - Federation discovery
   - Trust establishment
   - Certificate management

5. **Attribute Management**
   - Standard attribute mapping
   - Custom attribute support
   - Attribute filtering and validation
   - eduPerson attribute support

6. **Security Features**
   - XML signature validation
   - Certificate validation
   - Replay protection
   - Clock skew tolerance
   - Encryption support

## 📋 Prerequisites

- Node.js 16.0.0 or higher
- npm or yarn package manager
- OpenSSL for certificate generation

## 🛠️ Installation

1. **Clone the repository**
   ```bash
   git clone <repository-url>
cd saml2
   ```

2. **Install dependencies**
   ```bash
   npm install
   ```

3. **Set up environment variables**
   ```bash
   cp .env.example .env
   # Edit .env with your configuration
   ```

4. **Generate certificates** (or use your own)
   ```bash
   # Create certificates directory
   mkdir -p certs
   
   # Generate self-signed certificates (for development)
   openssl req -x509 -newkey rsa:2048 -keyout certs/idp-private-key.pem -out certs/idp-certificate.pem -days 365 -nodes
   openssl req -x509 -newkey rsa:2048 -keyout certs/sp-private-key.pem -out certs/sp-certificate.pem -days 365 -nodes
   ```

5. **Start the application**
   ```bash
   npm start
   # or for development
   npm run dev
   ```

## ⚙️ Configuration

### Environment Variables

Create a `.env` file with the following configuration:

```env
# Server Configuration
NODE_ENV=development
PORT=3000
SESSION_SECRET=your-super-secret-session-key

# Identity Provider (IdP) Configuration
IDP_ENTITY_ID=http://localhost:3000
IDP_SSO_URL=http://localhost:3000/saml/sso
IDP_SLO_URL=http://localhost:3000/saml/slo
IDP_PRIVATE_KEY_PATH=./certs/idp-private-key.pem
IDP_CERTIFICATE_PATH=./certs/idp-certificate.pem

# Service Provider (SP) Configuration
SP_ENTITY_ID=http://localhost:3001
SP_ACS_URL=http://localhost:3001/saml/acs
SP_SLO_URL=http://localhost:3001/saml/slo
SP_PRIVATE_KEY_PATH=./certs/sp-private-key.pem
SP_CERTIFICATE_PATH=./certs/sp-certificate.pem

# Security Configuration
SECURITY_SIGNATURE_ALGORITHM=sha256
SECURITY_DIGEST_ALGORITHM=sha256
SECURITY_CLOCK_SKEW=300
SECURITY_REPLAY_PROTECTION=true
```

### SAML Configuration

The application uses a centralized configuration system in `src/config/saml.js` that supports:

- Multiple binding types (HTTP-Redirect, HTTP-POST, PAOS)
- Configurable security settings
- Attribute mapping and filtering
- Federation settings
- Logging configuration

## 🔐 Usage Examples

### 1. SP-Initiated SSO

```javascript
// Redirect user to IdP for authentication
GET /saml/login?relayState=/dashboard&forceAuthn=true
```

### 2. IdP-Initiated SSO

```javascript
// IdP redirects user with SAML response
GET /saml/sso?SAMLResponse=<base64-encoded-response>&RelayState=/dashboard
```

### 3. Enhanced Client/Proxy (ECP)

```javascript
// Send ECP request
POST /saml/ecp
Content-Type: application/soap+xml
SOAPAction: http://www.oasis-open.org/committees/security

{
  "relayState": "/dashboard",
  "soapAction": "http://www.oasis-open.org/committees/security"
}
```

### 4. Single Logout

```javascript
// Initiate logout
GET /saml/logout?nameID=user@example.com&sessionIndex=_session123
```

### 5. Metadata Access

```javascript
// Get SP metadata
GET /metadata/sp

// Get IdP metadata
GET /metadata/idp

// Get federation metadata
GET /metadata/federation
```

## 📡 API Endpoints

### SAML Endpoints

| Endpoint | Method | Description |
|----------|--------|-------------|
| `/saml/login` | GET | SP-initiated SSO |
| `/saml/sso` | GET | IdP-initiated SSO |
| `/saml/acs` | POST | Assertion Consumer Service |
| `/saml/ecp` | POST | Enhanced Client/Proxy |
| `/saml/logout` | GET | SP-initiated logout |
| `/saml/slo` | POST | Single Logout Service |
| `/saml/metadata/sp` | GET | SP metadata |
| `/saml/metadata/idp` | GET | IdP metadata |
| `/saml/attributes` | GET | User attributes |
| `/saml/validate` | POST | SAML validation |
| `/saml/session` | GET | Session information |

### Authentication Endpoints

| Endpoint | Method | Description |
|----------|--------|-------------|
| `/auth/status` | GET | Authentication status |
| `/auth/login` | GET | Login redirect |
| `/auth/logout` | GET | Logout |
| `/auth/protected` | GET | Protected resource |
| `/auth/profile` | GET | User profile |
| `/auth/refresh` | POST | Session refresh |

### Metadata Endpoints

| Endpoint | Method | Description |
|----------|--------|-------------|
| `/metadata/sp` | GET | SP metadata |
| `/metadata/idp` | GET | IdP metadata |
| `/metadata/federation` | GET | Federation metadata |
| `/metadata/discovery` | GET | Discovery service |
| `/metadata/certificates` | GET | Certificate info |
| `/metadata/config` | GET | Configuration info |

## 🔧 Customization

### Adding Custom Attributes

```javascript
// In src/config/saml.js
attributeMapping: {
  'urn:oid:2.5.4.42': 'firstName',
  'urn:oid:2.5.4.4': 'lastName',
  'urn:oid:0.9.2342.19200300.100.1.3': 'email',
  'custom:attribute:1': 'customField'
}
```

### Custom Validation Logic

```javascript
// In src/config/passport.js
validateSignature: (xml, callback) => {
  // Your custom signature validation logic
  const isValid = yourCustomValidation(xml);
  callback(null, isValid);
}
```

### Adding New SAML Profiles

```javascript
// In src/utils/samlUtils.js
generateCustomProfile(options = {}) {
  // Implement custom SAML profile
  const customRequest = {
    // Your custom SAML structure
  };
  
  return {
    xml: this.builder.buildObject(customRequest),
    // Additional metadata
  };
}
```

## 🧪 Testing

### Run Tests

```bash
npm test
```

### Test Coverage

```bash
npm run test:coverage
```

### Manual Testing

1. **Start the application**
   ```bash
   npm run dev
   ```

2. **Test SP-initiated SSO**
   - Visit `http://localhost:3000/saml/login`
   - Should redirect to IdP

3. **Test metadata endpoints**
   - Visit `http://localhost:3000/metadata/sp`
   - Should return XML metadata

4. **Test health checks**
   - Visit `http://localhost:3000/health`
   - Should return system status

## 🚀 Deployment

### Production Considerations

1. **Use proper certificates**
   - Replace self-signed certificates with CA-signed ones
   - Store private keys securely
   - Use environment variables for sensitive data

2. **Security hardening**
   - Enable HTTPS
   - Set secure session cookies
   - Implement rate limiting
   - Use proper logging

3. **Monitoring**
   - Set up health checks
   - Monitor SAML flows
   - Log security events
   - Track performance metrics

### Docker Deployment

```dockerfile
FROM node:16-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
EXPOSE 3000
CMD ["npm", "start"]
```

### Environment-Specific Configs

```bash
# Development
NODE_ENV=development
LOG_LEVEL=debug

# Production
NODE_ENV=production
LOG_LEVEL=warn
SECURITY_REPLAY_PROTECTION=true
```

## 📚 OASIS SAML 2.0 Compliance

This implementation follows the [OASIS SAML 2.0 specifications](https://docs.oasis-open.org/security/saml/Post2.0/sstc-saml-tech-overview-2.0.html) and includes:

- ✅ **Web Browser SSO Profile** - Complete implementation
- ✅ **Enhanced Client/Proxy Profile** - PAOS binding support
- ✅ **Single Logout Profile** - Full logout flow
- ✅ **Identity Federation** - Metadata and discovery
- ✅ **Attribute Management** - Standard and custom attributes
- ✅ **Security Features** - Signing, encryption, validation

## 🤝 Contributing

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests
5. Submit a pull request

## 📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

## 🆘 Support

For support and questions:

- Create an issue in the repository
- Check the documentation
- Review the OASIS SAML 2.0 specifications

## 🔗 Related Resources

- [OASIS SAML 2.0 Specifications](https://docs.oasis-open.org/security/saml/Post2.0/sstc-saml-tech-overview-2.0.html)
- [SAML 2.0 Profiles](https://docs.oasis-open.org/security/saml/Post2.0/saml-profiles-2.0-os.pdf)
- [SAML 2.0 Bindings](https://docs.oasis-open.org/security/saml/Post2.0/saml-bindings-2.0-os.pdf)
- [SAML 2.0 Metadata](https://docs.oasis-open.org/security/saml/Post2.0/saml-metadata-2.0-os.pdf)

---

**Built with ❤️ by subu1979 - Comprehensive SAML 2.0 Solutions**