npm package: @networkcoin/sdk
Description: Official SDK for NETWORKCOIN.ID - The Identity Provider for Blockchain
Author: NETWORKCOIN.ID
Latest version: 0.1.2

# @networkcoin/sdk

Official SDK for **NETWORKCOIN.ID** — The Web3 Identity Provider.

Add "Sign in with NetworkCoin" to any app in minutes. Supports OAuth 2.0 + PKCE, wallet-based login, and hosted checkout.

## Installation

```bash
npm install @networkcoin/sdk
```

## Quick Start

### Vanilla JavaScript / TypeScript

```typescript
import { NetworkCoinClient } from '@networkcoin/sdk';

const auth = new NetworkCoinClient({
  clientId: 'your-client-id',
  redirectUri: 'https://yourapp.com/callback',
});

// Redirect to login
await auth.login();

// Handle the callback (on your /callback page)
const tokens = await auth.handleCallback();

// Get the authenticated user
const user = await auth.getUser();
console.log(user.name, user.email, user.wallet_address);
```

### React

```tsx
import { NetworkCoinProvider, useNetworkCoin } from '@networkcoin/sdk/react';

function App() {
  return (
    <NetworkCoinProvider
      clientId="your-client-id"
      redirectUri="https://yourapp.com/callback"
    >
      <Profile />
    </NetworkCoinProvider>
  );
}

function Profile() {
  const { user, isAuthenticated, isLoading, login, signup, logout } = useNetworkCoin();

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

  if (!isAuthenticated) {
    return (
      <div>
        <button onClick={login}>Sign in with NetworkCoin</button>
        <button onClick={signup}>Create Account</button>
      </div>
    );
  }

  return (
    <div>
      <p>Welcome, {user?.name}!</p>
      <p>{user?.email}</p>
      <p>{user?.wallet_address}</p>
      <button onClick={() => logout()}>Sign out</button>
    </div>
  );
}
```

## Configuration

| Option | Type | Required | Default | Description |
|---|---|---|---|---|
| `clientId` | `string` | Yes | — | Your OAuth client ID from the [Developer Console](https://id.networkcoin.ai/console) |
| `redirectUri` | `string` | Yes | — | Callback URL (must match your registered redirect URI) |
| `scope` | `string` | No | `"openid profile email wallet"` | OAuth scopes to request |
| `domain` | `string` | No | `"https://id.networkcoin.ai"` | Auth server URL |

## API Reference

### `NetworkCoinClient`

#### `login(): Promise<void>`
Redirects the user to the NetworkCoin login page. Uses OAuth 2.0 with PKCE for security.

#### `signup(): Promise<void>`
Redirects the user to the NetworkCoin signup page to create a new account.

#### `handleCallback(callbackUrl?: string): Promise<TokenResponse | null>`
Processes the OAuth callback after the user returns from authentication. Validates the state parameter, exchanges the authorization code for tokens, and stores them. Returns `null` if no authorization code is present in the URL.

#### `getUser(accessToken?: string): Promise<NetworkCoinUser>`
Fetches the authenticated user's profile. Automatically refreshes the access token if expired.

#### `refreshToken(refreshToken?: string): Promise<TokenResponse>`
Exchanges a refresh token for a new access token.

#### `logout(postLogoutRedirectUri?: string): Promise<void>`
Revokes tokens, clears local storage, and redirects to the logout endpoint.

#### `isAuthenticated(): boolean`
Returns `true` if the user has a valid (non-expired) access token.

#### `getAccessToken(): string | null`
Returns the stored access token for making authenticated API calls.

#### `pay(options: PaymentOptions): Promise<void>`
Redirects the user to the hosted checkout page.

```typescript
await auth.pay({
  amount: 999,           // $9.99 in cents
  currency: 'USD',
  description: 'Pro Plan',
  interval: 'month',     // 'month' or 'year' for subscriptions
  successUrl: 'https://yourapp.com/success',
  cancelUrl: 'https://yourapp.com/cancel',
});
```

### React Provider

#### `<NetworkCoinProvider>`

Wraps your app with authentication context.

| Prop | Type | Default | Description |
|---|---|---|---|
| `clientId` | `string` | — | OAuth client ID |
| `redirectUri` | `string` | — | Callback URL |
| `scope` | `string` | `"openid profile email wallet"` | OAuth scopes |
| `domain` | `string` | `"https://id.networkcoin.ai"` | Auth server URL |
| `autoHandleCallback` | `boolean` | `true` | Automatically process OAuth callback on mount |
| `autoFetchUser` | `boolean` | `true` | Automatically fetch user profile when authenticated |

#### `useNetworkCoin()`

Hook that returns:

| Property | Type | Description |
|---|---|---|
| `client` | `NetworkCoinClient` | Direct access to the client instance |
| `user` | `NetworkCoinUser \| null` | Current authenticated user |
| `isAuthenticated` | `boolean` | Whether the user is logged in |
| `isLoading` | `boolean` | Loading state during initialization |
| `error` | `string \| null` | Error message from auth operations |
| `login()` | `() => Promise<void>` | Redirect to login |
| `signup()` | `() => Promise<void>` | Redirect to signup |
| `logout()` | `(uri?: string) => Promise<void>` | Sign out |
| `getUser()` | `() => Promise<NetworkCoinUser>` | Fetch user profile |
| `getAccessToken()` | `() => string \| null` | Get access token |
| `pay()` | `(options) => Promise<void>` | Start checkout flow |

### Types

```typescript
interface NetworkCoinUser {
  sub: string;
  name?: string;
  email?: string;
  email_verified?: boolean;
  picture?: string;
  wallet_address?: string;
  updated_at?: string;
}

interface TokenResponse {
  access_token: string;
  token_type: string;
  expires_in: number;
  id_token: string;
  refresh_token?: string;
  scope: string;
}

interface PaymentOptions {
  amount: number;          // Amount in cents
  currency?: string;       // Default: 'USD'
  description?: string;
  successUrl?: string;
  cancelUrl?: string;
  interval?: 'month' | 'year';
}
```

## Getting Your Client ID

1. Go to [id.networkcoin.ai/console](https://id.networkcoin.ai/console)
2. Create a new workspace (or select an existing one)
3. Create a new app under **Apps**
4. Copy your **Client ID** and add your **Redirect URI**

## Security

- All auth flows use **PKCE** (Proof Key for Code Exchange) with S256
- State parameter validation protects against CSRF attacks
- Tokens are stored in `localStorage` (access + refresh tokens) and `sessionStorage` (PKCE verifier)

## License

MIT