npm package: @kolaylogin/auth-sdk
Description: Enterprise SSO authentication SDK for mobile and web applications
Author: KolayLogin
Latest version: 1.0.1

# @kolaylogin/auth-sdk

Enterprise-grade authentication SDK for mobile and web applications. Powered by modern, secure infrastructure with support for OAuth, SAML SSO, and multi-tenant applications.

## Features

### Authentication
- ✅ **Multiple Auth Methods**: Email/password, OAuth (Google, Apple, Microsoft), Enterprise SSO
- ✅ **Multi-Tenant Ready**: Support for 100+ apps with per-app branding
- ✅ **Cross-Platform**: Web, React, React Native, Node.js
- ✅ **TypeScript First**: Full type safety and IntelliSense
- ✅ **Secure by Default**: Industry-standard security practices
- ✅ **Zero Configuration**: Works out of the box with sensible defaults
- ✅ **White-Label Ready**: Complete branding customization

### Merchant Management (NEW)
- ✅ **Automatic Merchant Creation**: Create merchants with auto-generated merchant IDs
- ✅ **Merchant Profile Management**: Update merchant information and settings
- ✅ **Wallet Address Management**: Store and manage Ethereum wallet addresses
- ✅ **Merchant Status Tracking**: Track merchant status (active, inactive, suspended)

### X402 Payment Integration (NEW)
- ✅ **X402 Facilitator Client**: Complete X402 protocol integration
- ✅ **Payment Verification**: Verify X402 payments before settlement
- ✅ **Payment Settlement**: Settle verified payments
- ✅ **Multi-Network Support**: Support for BSC and Base networks
- ✅ **Supported Payment Kinds**: Query supported payment methods

### Next.js Templates (NEW)
- ✅ **Merchant Dashboard Template**: Ready-to-use merchant management dashboard
- ✅ **Payment Checkout Template**: Pre-built payment checkout page
- ✅ **Webhook Handler Template**: X402 webhook handler implementation

## Installation

```bash
npm install @kolaylogin/auth-sdk

# or

yarn add @kolaylogin/auth-sdk

# or

pnpm add @kolaylogin/auth-sdk
```

## Quick Start

### Web / Node.js

```typescript
import { KolayLoginClient } from '@kolaylogin/auth-sdk';

const client = new KolayLoginClient({
  supabaseUrl: 'YOUR_SUPABASE_URL',
  supabaseKey: 'YOUR_SUPABASE_ANON_KEY',
  redirectUri: 'https://yourapp.com/auth/callback',
});

// Sign in with email/password
const session = await client.signInWithEmail('user@example.com', 'password');

// Sign in with OAuth
const { url } = await client.signInWithOAuth({ provider: 'google' });
window.location.href = url;

// Sign in with enterprise SSO
const { url } = await client.signInWithSSO({ domain: 'company.com' });
window.location.href = url;

// Get current user
const user = await client.getUser();

// Sign out
await client.signOut();
```

### React

```typescript
import { KolayLoginProvider, useKolayLogin } from '@kolaylogin/auth-sdk/react';

function App() {
  return (
    <KolayLoginProvider
      config={{
        supabaseUrl: 'YOUR_SUPABASE_URL',
        supabaseKey: 'YOUR_SUPABASE_ANON_KEY',
        redirectUri: 'https://yourapp.com/auth/callback',
      }}
    >
      <YourApp />
    </KolayLoginProvider>
  );
}

function YourApp() {
  const { user, signIn, signOut, loading } = useKolayLogin();

  if (loading) return <div>Loading...</div>;

  if (!user) {
    return (
      <button onClick={() => signIn('email@example.com', 'password')}>
        Sign In
      </button>
    );
  }

  return (
    <div>
      <p>Welcome, {user.email}!</p>
      <button onClick={signOut}>Sign Out</button>
    </div>
  );
}
```

## Merchant Management

### Create Merchant

```typescript
import { createMerchant } from '@kolaylogin/auth-sdk';

const merchant = await createMerchant(
  {
    userId: user.id,
    name: 'My Shop',
    email: 'merchant@example.com',
    walletAddress: '0x742d35Cc4bF516a687E5b111a7c5f8aAbe4C5827', // Optional
    metadata: {
      businessType: 'e-commerce',
      website: 'https://myshop.com',
    },
  },
  {
    supabaseUrl: 'YOUR_SUPABASE_URL',
    supabaseKey: 'YOUR_SUPABASE_ANON_KEY',
  }
);

console.log('Merchant ID:', merchant.merchantId); // merchant_abc123
```

### Get Merchant

```typescript
import { getMerchant } from '@kolaylogin/auth-sdk';

// By merchant ID
const merchant = await getMerchant(
  { merchantId: 'merchant_abc123' },
  { supabaseUrl: '...', supabaseKey: '...' }
);

// By user ID
const merchant = await getMerchant(
  { userId: user.id },
  { supabaseUrl: '...', supabaseKey: '...' }
);
```

### Using MerchantManager Class

```typescript
import { MerchantManager } from '@kolaylogin/auth-sdk';

const manager = new MerchantManager({
  supabaseUrl: 'YOUR_SUPABASE_URL',
  supabaseKey: 'YOUR_SUPABASE_ANON_KEY',
});

// Create merchant
const merchant = await manager.create({
  userId: user.id,
  name: 'My Shop',
  email: 'merchant@example.com',
});

// Get merchant
const merchantInfo = await manager.get({ merchantId: merchant.merchantId });

// Update merchant
await manager.update(merchant.merchantId, {
  name: 'Updated Shop Name',
  status: 'active',
});
```

## X402 Payment Integration

### X402 Facilitator

```typescript
import { X402Facilitator } from '@kolaylogin/auth-sdk';

const facilitator = new X402Facilitator({
  merchantId: 'merchant_abc123',
  facilitatorAddress: '0x742d35Cc4bF516a687E5b111a7c5f8aAbe4C5827',
  network: 'bsc', // 'bsc' | 'base'
  apiUrl: 'https://api.paykly.com', // Optional
  apiKey: 'YOUR_API_KEY', // Optional
});

// Get supported payment kinds
const supported = await facilitator.getSupported();

// Verify payment
const verification = await facilitator.verify({
  x402Version: 1,
  paymentPayload: {
    transactionHash: '0x...',
  },
  paymentRequirements: {
    scheme: 'exact',
    network: 'bsc',
    maxAmountRequired: '1000000',
    resource: 'https://api.paykly.com/resource',
  },
});

if (verification.isValid) {
  // Settle payment
  const settlement = await facilitator.settle({
    x402Version: 1,
    paymentPayload: {
      transactionHash: '0x...',
    },
    paymentRequirements: {
      scheme: 'exact',
      network: 'bsc',
      maxAmountRequired: '1000000',
      resource: 'https://api.paykly.com/resource',
    },
  });
}
```

### Standalone Functions

```typescript
import { verifyPayment, settlePayment } from '@kolaylogin/auth-sdk';

// Verify payment
const isValid = await verifyPayment(
  {
    x402Version: 1,
    paymentPayload: { transactionHash: '0x...' },
    paymentRequirements: { /* ... */ },
  },
  {
    merchantId: 'merchant_abc123',
    facilitatorAddress: '0x...',
    network: 'bsc',
  }
);

// Settle payment
const success = await settlePayment(
  {
    x402Version: 1,
    paymentPayload: { transactionHash: '0x...' },
    paymentRequirements: { /* ... */ },
  },
  {
    merchantId: 'merchant_abc123',
    facilitatorAddress: '0x...',
    network: 'bsc',
  }
);
```

## React Hooks

### useMerchant Hook

```typescript
import { useMerchant } from '@kolaylogin/auth-sdk/react';

function MerchantDashboard() {
  const { user } = useKolayLogin();
  const { merchant, loading, createMerchant, updateMerchant } = useMerchant();

  useEffect(() => {
    if (user && !merchant) {
      createMerchant({
        name: 'My Shop',
        email: 'merchant@example.com',
      });
    }
  }, [user, merchant, createMerchant]);

  if (loading) return <div>Loading...</div>;

  return (
    <div>
      <h1>Merchant: {merchant?.name}</h1>
      <p>Merchant ID: {merchant?.merchantId}</p>
    </div>
  );
}
```

### useX402 Hook

```typescript
import { useX402 } from '@kolaylogin/auth-sdk/react';

function PaymentHandler() {
  const { merchant } = useMerchant();
  const { verifyPayment, settlePayment, loading } = useX402({
    merchantId: merchant?.merchantId || '',
    facilitatorAddress: '0x742d35Cc4bF516a687E5b111a7c5f8aAbe4C5827',
    network: 'bsc',
  });

  const handlePayment = async (paymentData) => {
    const verification = await verifyPayment({
      x402Version: 1,
      paymentPayload: paymentData.payload,
      paymentRequirements: paymentData.requirements,
    });

    if (verification.isValid) {
      await settlePayment({
        x402Version: 1,
        paymentPayload: paymentData.payload,
        paymentRequirements: paymentData.requirements,
      });
    }
  };

  return (
    <button onClick={handlePayment} disabled={loading}>
      Process Payment
    </button>
  );
}
```

## Complete Integration Example

```typescript
import {
  KolayLoginClient,
  createMerchant,
  X402Facilitator,
  initMerchantApp,
} from '@kolaylogin/auth-sdk';

// 1. User authentication
const client = new KolayLoginClient({
  supabaseUrl: 'YOUR_SUPABASE_URL',
  supabaseKey: 'YOUR_SUPABASE_ANON_KEY',
});

const { user } = await client.signUp('user@example.com', 'password');

// 2. Create merchant (automatic merchant ID)
const merchant = await createMerchant(
  {
    userId: user.id,
    name: 'My Shop',
    email: 'shop@example.com',
  },
  {
    supabaseUrl: 'YOUR_SUPABASE_URL',
    supabaseKey: 'YOUR_SUPABASE_ANON_KEY',
  }
);

console.log('Merchant ID:', merchant.merchantId);

// 3. Initialize X402 facilitator
const facilitator = new X402Facilitator({
  merchantId: merchant.merchantId,
  facilitatorAddress: '0x742d35Cc4bF516a687E5b111a7c5f8aAbe4C5827',
  network: 'bsc',
});

// 4. Get supported payment methods
const supported = await facilitator.getSupported();

// 5. Generate merchant dashboard
await initMerchantApp({
  outputDir: './my-shop-dashboard',
  merchantId: merchant.merchantId,
  templates: ['merchant-dashboard', 'payment-checkout'],
  config: {
    facilitatorAddress: '0x742d35Cc4bF516a687E5b111a7c5f8aAbe4C5827',
    network: 'bsc',
  },
});
```

## Database Setup

Before using merchant features, you need to create the merchants table in your Supabase database:

```sql
-- Run the migration file
-- See: lib/database/merchants_schema.sql
```

Or run the SQL directly:

```sql
CREATE TABLE IF NOT EXISTS merchants (
  id TEXT PRIMARY KEY DEFAULT gen_random_uuid()::text,
  user_id UUID REFERENCES auth.users(id) ON DELETE CASCADE,
  merchant_id TEXT UNIQUE NOT NULL DEFAULT 'merchant_' || gen_random_uuid()::text,
  name TEXT NOT NULL,
  email TEXT NOT NULL,
  wallet_address TEXT,
  status TEXT DEFAULT 'active' CHECK (status IN ('active', 'inactive', 'suspended')),
  metadata JSONB DEFAULT '{}',
  created_at TIMESTAMPTZ DEFAULT NOW(),
  updated_at TIMESTAMPTZ DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_merchants_user_id ON merchants(user_id);
CREATE INDEX IF NOT EXISTS idx_merchants_merchant_id ON merchants(merchant_id);
```

## Next.js Templates

Coming soon: Ready-to-use Next.js templates for merchant dashboard, payment checkout, and webhook handlers.

```typescript
import { initMerchantApp } from '@kolaylogin/auth-sdk';

await initMerchantApp({
  outputDir: './my-merchant-app',
  merchantId: 'merchant_abc123',
  templates: ['merchant-dashboard', 'payment-checkout', 'webhook-handler'],
  config: {
    facilitatorAddress: '0x742d35Cc4bF516a687E5b111a7c5f8aAbe4C5827',
    network: 'bsc',
  },
});
```

### React Native

```typescript
import { KolayLoginReactNativeClient } from '@kolaylogin/auth-sdk/react-native';

const client = new KolayLoginReactNativeClient({
  supabaseUrl: 'YOUR_SUPABASE_URL',
  supabaseKey: 'YOUR_SUPABASE_ANON_KEY',
  redirectUri: 'yourapp://auth/callback',
});

// Usage same as web client
// Note: Requires expo-secure-store and expo-linking
```

## API Reference

### KolayLoginClient

#### Methods

- `signInWithEmail(email, password)`: Sign in with email and password
- `signInWithOAuth(options)`: Sign in with OAuth provider
- `signInWithSSO(options)`: Sign in with enterprise SSO
- `signUp(email, password, metadata?)`: Create new account
- `signOut()`: Sign out current user
- `getUser()`: Get current user
- `getSession()`: Get current session
- `refreshSession()`: Refresh access token
- `updateUser(updates)`: Update user profile
- `resetPassword(email)`: Send password reset email
- `verifyOTP(params)`: Verify OTP code
- `exchangeCodeForSession(code)`: Exchange OAuth code for session
- `onAuthStateChange(callback)`: Subscribe to auth state changes

### React Hooks

- `useKolayLogin()`: Main hook for authentication
- `useUser()`: Get current user
- `useSession()`: Get current session
- `useAuth()`: Get auth methods
- `useAuthState()`: Check authentication state

### React Components

- `<LoginButton />`: Pre-built login button
- `<UserProfile />`: User profile display
- `<SSOForm />`: SSO login form

## Documentation

- [Getting Started](./docs/getting-started.md)
- [API Reference](./docs/api-reference.md)
- [React Hooks](./docs/react-hooks.md)
- [React Native Guide](./docs/react-native.md)
- [Multi-Tenant Setup](./docs/multi-tenant.md)
- [Migration Guides](./docs/migration-guides.md)

## Error Handling

All errors are thrown as `KolayLoginError` instances:

```typescript
import { KolayLoginError } from '@kolaylogin/auth-sdk';

try {
  await client.signInWithEmail('user@example.com', 'password');
} catch (error) {
  if (error instanceof KolayLoginError) {
    console.error('Error code:', error.code);
    console.error('Error message:', error.message);
  }
}
```

## Multi-Tenant Support

```typescript
import { TenantManager } from '@kolaylogin/auth-sdk';

const tenantManager = new TenantManager();

await tenantManager.registerApp({
  appId: 'my-app',
  appName: 'My App',
  bundleId: 'com.example.app',
  platform: 'ios',
  redirectUri: 'myapp://auth/callback',
  ssoEnabled: true,
});
```

## TypeScript Support

Full TypeScript definitions are included. All types are exported:

```typescript
import type {
  KolayLoginConfig,
  KolayLoginUser,
  AuthSession,
  OAuthOptions,
  SSOOptions,
} from '@kolaylogin/auth-sdk';
```

## License

MIT

## Support

For issues and questions, please visit our [GitHub repository](https://github.com/kolaylogin/auth-sdk).