#
<div align="center">
  <a href="https://nijachat.ng/">
    <img src="https://nijachat.ng/nijachat_logo_full.png" width="300" height="auto" alt="NijaChat"/>
  </a>
</div>

<hr />

<p align="center">
<a href="https://platform.nijachat.ng"><b>check our Documentation 👉 platform.nijachat.ng</b></a><br />
</p>

<hr />

[![npm](https://img.shields.io/npm/v/@nijachat/node)](https://www.npmjs.com/package/@nijachat/node)
[![Bundle Size](https://img.shields.io/bundlephobia/min/@nijachat/node)](https://bundlephobia.com/result?p=@nijachat/node)
[![Bundle Size](https://img.shields.io/bundlephobia/minzip/@nijachat/node)](https://bundlephobia.com/result?p=@nijachat/node)

This SDK provides functionalities to interact with the NijaChat SuperApp from a Node.js environment. The SDK allows you to extract user information, authorization tokens, and device tokens from cookies.

## Installation

```bash
npm i @nijachat/node
```

# Usage

## OAuth

### `buildAuthorization(config: Configuration, redirectUri: string): Promise<{ state, code_challenge, code_verifier, nonce, redirectHref }>`

Initiates the OAuth flow by generating the necessary authorization parameters.

- **Parameters**:
  - `config`: The OAuth configuration object containing client metadata and server endpoints.
  - `redirectUri`: The URI where the user should be redirected after authorization.

- **Returns**: An object containing:
  - `state`: Random string to maintain state between request and callback.
  - `code_challenge`: Challenge derived from the code verifier for PKCE.
  - `code_verifier`: Plaintext code verifier.
  - `nonce`: A unique string to mitigate replay attacks.
  - `redirectHref`: The full URL to redirect the user to initiate login.

---

### `grantAuthorizationCode(config: Configuration, url: string, verifier: string, state: string, nonce: string): Promise<{ access_token, sub }>`

Exchanges the authorization code for an access token and subject identifier.

- **Parameters**:
  - `config`: Nija OAuth configuration.
  - `url`: Full callback URL including the code query parameter.
  - `verifier`: Code verifier originally generated during `buildAuthorization`.
  - `state`: The same `state` string passed to the authorization URL.
  - `nonce`: Nonce to ensure the token is valid and prevent replay attacks.

- **Returns**: An object with:
  - `access_token`: OAuth access token.
  - `sub`: The subject identifier for the user.

---

### `fetchUser(config: Configuration, token: string, sub: string): Promise<User>`

Fetches the authenticated user's profile using the access token.

- **Parameters**:
  - `config`: Nija OAuth configuration.
  - `token`: Access token received via the token exchange.
  - `sub`: Subject identifier (user ID).

- **Returns**: A `User` object containing decoded user information.

---

### `receiveConfig(server: string, clientId: string, metadata: ClientMetadata, secret: string): Promise<Configuration>`

Fetches and constructs the configuration object needed for OAuth calls.

- **Parameters**:
  - `server`: Nija server base URL.
  - `clientId`: The application's client ID.
  - `metadata`: `ClientMetadata` object with endpoint info.
  - `secret`: The application's client secret.

- **Returns**: A `Configuration` object used for all SDK OAuth interactions.

---

### `refreshAccessToken(config: Configuration, refreshToken: string, additionalParameters?: Record<string, string>): Promise<RefreshTokenResponse>`

Refreshes an access token using a refresh token.

- **Parameters**:
  - `config`: Nija OAuth configuration.
  - `refreshToken`: The refresh token to use for obtaining a new access token.
  - `additionalParameters`: Optional additional parameters to send with the refresh request (e.g., scope).

- **Returns**: An object containing:
  - `access_token`: New OAuth access token.
  - `refresh_token`: Optional new refresh token.
  - `expires_in`: Token expiration time in seconds.
  - `token_type`: Token type (usually "Bearer").

---

## Cookie

### `getUser(cookie: object): User`

This function extracts and decodes the user information from a provided cookie.

- **Parameters**:
    - `cookie`: An raw string representing the cookie from which user information is to be extracted.
- **Returns**: An object containing the user information.

**Example**:

```javascript
import { getUser } from '@nijachat/node';

const user = getUser(req.cookies.get("nijachat"));
console.log(user);
```

### `getAuthorization(cookie: object)`

This function generates an authorization token from the provided cookie.

- **Parameters**:
    - `cookie`: An raw string representing the cookie from which the authorization token is to be extracted.
- **Returns**: A base64 encoded string representing the authorization token, or `null` if the token is not available.

**Example**:

```javascript
import { getAuthorization } from '@nijachat/node';

const authToken = getAuthorization(req.cookies.get("nijachat"));
console.log(authToken);
```

### `getDeviceToken(cookie: object)`

This function extracts the device token from the provided cookie.

- **Parameters**:
    - `cookie`: An raw string representing the cookie from which the device token is to be extracted.
- **Returns**: A string representing the device token, or `null` if the token is not available.

**Example**:

```javascript
import { getDeviceToken } from '@nijachat/node';

const deviceToken = getDeviceToken(req.cookies.get("nijachat"));
console.log(deviceToken);
```

### checkSignature( userId: number, authKeyId: string, deviceToken: string, signatureBase64: string, publicKey: string)
This function verifies user.

- **Parameters**:
  - `userId`: id of the nija user,
  - `authKeyId`: key of authorisation, second part of user token, 
  - `deviceToken`: the token describing session on given device, 
  - `signatureBase64`: first part od user token, 
  - `publicKey`: the key that will be obtained in Dev Management
- **Returns**: A boolean that says if session are legit.

**Example**:

```js
import { getUser } from "@nijachat/node";
import { cookies } from "next/headers";

const store = cookies();
const cookie = store.get("nijachat");
const nijachat = getUser(cookie.value);

if (nija.userToken) {
    const [signature, auth_key_id, device_token, device_token_expires_at] =
        nija.userToken.split(":");

    const result = checkSignature(
        nija.userId,
        auth_key_id,
        device_token,
        signature,
        publicKey // obtain in Dev Management,
    );
    console.log(result) // true | false
}

```

## Usage with Different Frameworks

### Express.js

[check out cookie-parser](https://expressjs.com/en/resources/middleware/cookie-parser).

To use the SDK with an Express.js application:

```js
// server.js or index.js
import express from 'express';
import cookieParser from 'cookie-parser';
import { getUser, getAuthorization, getDeviceToken } from '@nijachat/node';

const app = express();
app.use(cookieParser());

app.get('/user', (req, res) => {
  const nijaCookie = req.cookies.nija;
  const user = getUser(nijaCookie);
  res.json(user);
});

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});
```

### Next.js

[check out next js docs](https://nextjs.org/docs/app/api-reference/functions/cookies).
To use the SDK with a Next.js 

#### API route:
```js
import { getUser, getAuthorization, getDeviceToken } from '@nijachat/node';

export default function handler(req, res) {
  const user = getUser(req.cookies.nijachat);
  const authToken = getAuthorization(req.cookies.nijachat);
  const deviceToken = getDeviceToken(req.cookies.nijachat);

  res.status(200).json({ user, authToken, deviceToken });
}
```

#### next/headers:
```js
import { cookies } from "next/headers";

export default async function Page () {
  const store = cookies();

  return(
        <div>
          {JSON.stringify(getUser(store.get("nijachat").value))}
        </div>
    )
}
```

# License

Distributed under the MIT License. See [LICENSE](LICENSE) for more information.
