npm package: @karthik123456789/unified-oauth
Description: A unified OAuth 2.0 library supporting Google, GitHub, Facebook, LinkedIn, Twitter, Instagram, and Reddit with PKCE support
Author: Unified OAuth Team
Latest version: 1.0.0

# Unified OAuth

A production-ready OAuth 2.0 library supporting Google, GitHub, Facebook, LinkedIn, Twitter, Instagram, and Reddit with PKCE support.

[![npm version](https://badge.fury.io/js/unified-oauth.svg)](https://badge.fury.io/js/unified-oauth)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Node.js Version](https://img.shields.io/node/v/unified-oauth.svg)](https://nodejs.org/)

## 🚀 Features

- **Multiple Providers**: Google, GitHub, Facebook, LinkedIn, Twitter, Instagram, Reddit
- **OAuth 2.0 Standard**: Authorization Code Grant flow
- **PKCE Support**: Built-in PKCE for Twitter OAuth 2.0
- **State Validation**: CSRF protection with state parameter
- **User Profile APIs**: Automatic user profile fetching
- **Error Handling**: Normalized error responses across providers
- **Type Safety**: Consistent response formats
- **Express Integration**: Ready-to-use Express.js example

## 📦 Installation

```bash
npm install @karthik123456789/unified-oauth
```

## 🔧 Quick Start

```javascript
const { getAuthorizationUrl, exchangeCodeForToken, getUserInfo } = require('@karthik123456789/unified-oauth');

// Configuration for any provider
const config = {
  clientId: 'your-client-id',
  clientSecret: 'your-client-secret',
  redirectUri: 'http://localhost:3000/auth/callback'
};

// Get authorization URL
const authData = getAuthorizationUrl('google', config);
console.log('Visit:', authData.url);

// After user authorization, exchange code for token
const tokenData = await exchangeCodeForToken('google', config, 'authorization-code');

// Get user profile
const userInfo = await getUserInfo('google', config, tokenData.access_token);
console.log('User:', userInfo);
```

## 🔐 Supported Providers

### Google
- **Setup**: [Google Cloud Console](https://console.developers.google.com/)
- **Scopes**: `openid`, `email`, `profile`
- **User Info**: `/oauth2/v2/userinfo`

### GitHub
- **Setup**: [GitHub Developer Settings](https://github.com/settings/applications/new)
- **Scopes**: `user:email`
- **User Info**: `/user`

### Facebook
- **Setup**: [Facebook Developers](https://developers.facebook.com/apps/)
- **Scopes**: `email`, `public_profile`
- **User Info**: `/me`

### LinkedIn
- **Setup**: [LinkedIn Developer Portal](https://www.linkedin.com/developers/apps)
- **Scopes**: `openid`, `profile`, `email`
- **User Info**: `/v2/userinfo`

### Twitter
- **Setup**: [Twitter Developer Portal](https://developer.twitter.com/en/portal/dashboard)
- **Scopes**: `tweet.read`, `users.read`
- **User Info**: `/2/users/me`
- **PKCE**: Required (automatically handled)

### Instagram
- **Setup**: [Facebook Developers](https://developers.facebook.com/apps/) (Instagram Basic Display)
- **Scopes**: `user_profile`, `user_media`
- **User Info**: `/me`

### Reddit
- **Setup**: [Reddit App Preferences](https://www.reddit.com/prefs/apps)
- **Scopes**: `identity`
- **User Info**: `/api/v1/me`

## 📚 API Reference

### `getAuthorizationUrl(provider, config, options)`

Generates the OAuth authorization URL for the specified provider.

**Parameters:**
- `provider` (string): Provider name (`google`, `github`, `facebook`, `linkedin`, `twitter`, `instagram`, `reddit`)
- `config` (object): Provider configuration
  - `clientId` (string): OAuth client ID
  - `clientSecret` (string): OAuth client secret
  - `redirectUri` (string): OAuth redirect URI
- `options` (object, optional):
  - `scopes` (array): Custom scopes
  - `state` (string): Custom state parameter (auto-generated if not provided)

**Returns:**
```javascript
{
  url: "https://provider.com/oauth/authorize?...",
  state: "generated-state-string",
  codeVerifier: "pkce-code-verifier", // Only for Twitter
  codeChallenge: "pkce-code-challenge" // Only for Twitter
}
```

### `exchangeCodeForToken(provider, config, code, options)`

Exchanges authorization code for access token.

**Parameters:**
- `provider` (string): Provider name
- `config` (object): Provider configuration
- `code` (string): Authorization code from callback
- `options` (object, optional):
  - `state` (string): State parameter from callback
  - `expectedState` (string): Expected state value
  - `codeVerifier` (string): PKCE code verifier (required for Twitter)

**Returns:**
```javascript
{
  provider: "google",
  access_token: "access-token-string",
  token_type: "Bearer",
  expires_in: 3600,
  refresh_token: "refresh-token-string", // If available
  scope: "openid email profile",
  timestamp: "2024-01-01T00:00:00.000Z"
}
```

### `getUserInfo(provider, config, accessToken)`

Fetches user profile information using access token.

**Parameters:**
- `provider` (string): Provider name
- `config` (object): Provider configuration
- `accessToken` (string): Access token

**Returns:**
```javascript
{
  provider: "google",
  id: "user-id",
  email: "user@example.com",
  name: "User Name",
  picture: "https://avatar-url.com/image.jpg",
  // Provider-specific fields...
  raw: { /* Raw API response */ },
  timestamp: "2024-01-01T00:00:00.000Z"
}
```

### `completeOAuthFlow(provider, config, code, options)`

Complete OAuth flow: exchange code and fetch user info in one call.

**Parameters:**
- `provider` (string): Provider name
- `config` (object): Provider configuration
- `code` (string): Authorization code
- `options` (object, optional): Additional options

**Returns:**
```javascript
{
  provider: "google",
  tokens: { /* Token response */ },
  user: { /* User info response */ },
  timestamp: "2024-01-01T00:00:00.000Z"
}
```

## 🛠️ Express.js Integration

### Basic Setup

```javascript
const express = require('express');
const { getAuthorizationUrl, exchangeCodeForToken, getUserInfo } = require('@karthik123456789/unified-oauth');

const app = express();

// OAuth initiation
app.get('/auth/:provider', (req, res) => {
  const { provider } = req.params;
  const config = {
    clientId: process.env[`${provider.toUpperCase()}_CLIENT_ID`],
    clientSecret: process.env[`${provider.toUpperCase()}_CLIENT_SECRET`],
    redirectUri: `http://localhost:3000/auth/${provider}/callback`
  };

  const authData = getAuthorizationUrl(provider, config);
  res.redirect(authData.url);
});

// OAuth callback
app.get('/auth/:provider/callback', async (req, res) => {
  const { provider } = req.params;
  const { code, state } = req.query;
  
  const config = {
    clientId: process.env[`${provider.toUpperCase()}_CLIENT_ID`],
    clientSecret: process.env[`${provider.toUpperCase()}_CLIENT_SECRET`],
    redirectUri: `http://localhost:3000/auth/${provider}/callback`
  };

  try {
    const tokenData = await exchangeCodeForToken(provider, config, code, { state });
    const userInfo = await getUserInfo(provider, config, tokenData.access_token);
    
    res.json({ user: userInfo, tokens: tokenData });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});
```

### Demo Application

Run the included demo application:

```bash
# Install dependencies
npm install

# Set environment variables
export GOOGLE_CLIENT_ID="your-google-client-id"
export GOOGLE_CLIENT_SECRET="your-google-client-secret"
# ... set other provider credentials

# Start the demo server
npm start
```

Visit `http://localhost:3000` to test OAuth flows with all providers.

## 🔒 Security Best Practices

### State Parameter Validation
Always validate the state parameter to prevent CSRF attacks:

```javascript
const authData = getAuthorizationUrl('google', config);
// Store authData.state securely (session, database, etc.)

// In callback:
const tokenData = await exchangeCodeForToken('google', config, code, {
  state: receivedState,
  expectedState: storedState
});
```

### Environment Variables
Never commit OAuth credentials to version control:

```bash
# .env file
GOOGLE_CLIENT_ID=your-client-id
GOOGLE_CLIENT_SECRET=your-client-secret
GITHUB_CLIENT_ID=your-client-id
GITHUB_CLIENT_SECRET=your-client-secret
# ... other providers
```

### HTTPS in Production
Always use HTTPS in production for OAuth redirect URIs.

## 🧪 Testing

```bash
# Run tests
npm test

# Run tests with coverage
npm run test:coverage

# Run tests in watch mode
npm run test:watch
```

## 📋 Provider Setup Guides

### Google OAuth Setup
1. Go to [Google Cloud Console](https://console.developers.google.com/)
2. Create a new project or select existing
3. Enable Google+ API
4. Create OAuth 2.0 credentials
5. Add authorized redirect URIs
6. Copy Client ID and Client Secret

### GitHub OAuth Setup
1. Go to [GitHub Settings > Developer settings](https://github.com/settings/developers)
2. Click "New OAuth App"
3. Fill in application details
4. Set Authorization callback URL
5. Copy Client ID and Client Secret

### Facebook OAuth Setup
1. Go to [Facebook Developers](https://developers.facebook.com/apps/)
2. Create a new app
3. Add Facebook Login product
4. Configure OAuth redirect URIs
5. Copy App ID and App Secret

### LinkedIn OAuth Setup
1. Go to [LinkedIn Developer Portal](https://www.linkedin.com/developers/apps)
2. Create a new app
3. Add Sign In with LinkedIn product
4. Configure redirect URLs
5. Copy Client ID and Client Secret

### Twitter OAuth Setup
1. Go to [Twitter Developer Portal](https://developer.twitter.com/en/portal/dashboard)
2. Create a new app
3. Enable OAuth 2.0
4. Set callback URLs
5. Copy Client ID and Client Secret

### Instagram OAuth Setup
1. Go to [Facebook Developers](https://developers.facebook.com/apps/)
2. Create a new app
3. Add Instagram Basic Display product
4. Configure OAuth redirect URIs
5. Copy App ID and App Secret

### Reddit OAuth Setup
1. Go to [Reddit App Preferences](https://www.reddit.com/prefs/apps)
2. Create a new app
3. Select "web app" type
4. Set redirect URI
5. Copy Client ID and Client Secret

## 🐛 Troubleshooting

### Common Issues

**"Invalid client" error**
- Verify client ID and secret are correct
- Check redirect URI matches exactly (including trailing slashes)

**"Invalid state parameter" error**
- Ensure state parameter is properly stored and validated
- Check for session/cookie issues

**"PKCE code verifier required" (Twitter)**
- Twitter requires PKCE for OAuth 2.0
- The library handles this automatically, but ensure you're using the returned `codeVerifier`

**"Scope not authorized" error**
- Check that requested scopes are enabled in your OAuth app
- Verify scopes match provider requirements

### Debug Mode

Enable debug logging:

```javascript
process.env.DEBUG = 'unified-oauth:*';
```

## 📄 License

MIT License - see [LICENSE](LICENSE) file for details.

## 🤝 Contributing

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests
5. Submit a pull request

## 📞 Support

- 📧 Email: support@unified-oauth.com
- 🐛 Issues: [GitHub Issues](https://github.com/unified-oauth/unified-oauth/issues)
- 📖 Documentation: [GitHub Wiki](https://github.com/unified-oauth/unified-oauth/wiki)

## 🔄 Changelog

### v1.0.0
- Initial release
- Support for 7 OAuth providers
- PKCE support for Twitter
- Express.js integration
- Comprehensive test suite
- Full documentation

---

Made with ❤️ by the Unified OAuth team