npm package: @pelican-identity/react-native
Description: React Native components for Pelican Identity authentication
Latest version: 1.2.52

# Pelican Identity React Native SDK

React Native SDK for Pelican authentication and identity verification
👉 **Pelican Dashboard:** https://dash.pelicanidentity.com

## Installation

### Using npm

```bash
npm install @pelican-identity/react-native react-native-get-random-values

```

### Using yarn

```bash
yarn add @pelican-identity/react-native react-native-get-random-values
```

### Using pnpm

```bash
pnpm add @pelican-identity/react-native react-native-get-random-values
```

---

## Required Setup

### 1. Set your app’s bundle identifier

You must configure your bundle identifier in your app and pass it explicitly to Pelican.
**Expo (`app.json` or `app.config.js`):**

```json
{
  "expo": {
    "name": "MyApp",
    "ios": {
      "bundleIdentifier": "com.yourcompany.myapp"
    },
    "android": {
      "package": "com.yourcompany.myapp"
    }
  }
}
```

**Bare React Native:**

- **iOS:** Xcode → Target → General → Bundle Identifier
- **Android:** `android/app/build.gradle` → `applicationId`

---

### 2. Import crypto polyfill (Important)

In your app’s entry file (`App.tsx`, `index.js`, or `layout.tsx`), import this **before anything else**:

```ts
import "react-native-get-random-values"; // Must be first
```

---

### 3. Whitelist your app in Pelican Dashboard

Add your app’s bundle identifier (example: `com.yourcompany.myapp`) to your project’s whitelist in the Pelican dashboard.
👉 **Pelican Dashboard:** https://dash.pelicanidentity.com

Pelican validates **explicit app identity** on every authentication attempt.

---

### 4. Callback URL Configuration

The `callBackUrl` defines where the Pelican vault app redirects after authentication, this must be the same page/screen where you have initialized the SDK, if this is not provided, SDK will attempt to authenticate **ONCE** when the app is reopened.

### Expo Go (development)

```ts
callBackUrl = "exp://192.168.1.100:8081";
```

Use your **local IP** and Expo dev server port.

### Expo standalone builds

```ts
callBackUrl = "myapp://auth-callback";
```

In `app.json`:

```json
{
  "expo": {
    "scheme": "myapp"
  }
}
```

### Bare React Native

```ts
callBackUrl = "myapp://auth-callback";
```

## ⚠️ Important: Callback URL Constraints

The Pelican SDK uses a secure handshake mechanism.  
To ensure maximum compatibility across mobile operating systems and to prevent URI manipulation attacks, **do not append query parameters** to your `callBackUrl`.

---

### ✅ Correct Configuration

Your `callBackUrl` must be a clean **Custom Scheme** or **Universal Link path**.  
The SDK and the Pelican App handle all data transmission internally.

| Status       | Format          | Example                               |
| ------------ | --------------- | ------------------------------------- |
| ✅ Correct   | Custom Scheme   | `my-app://auth-callback`              |
| ✅ Correct   | Universal Link  | `https://my-domain.com/auth-callback` |
| ❌ Incorrect | With Parameters | `my-app://auth?user=123`              |

---

### 🔐 Why This Is Required

Appending parameters to the `callBackUrl` can break Pelican’s signature verification process.

The Pelican App expects a **Base Path only**, which it uses to redirect the user back to your application securely.

Once the user returns:

- The SDK automatically retrieves the encrypted payload
- Using the `sessionID` established during `initialize()`
- Without exposing sensitive data in the URL

---

### 📌 Recommended Flow (No-Query Environment)

Since query strings are not supported:

- The Pelican App redirects to the base callback path
- Your SDK listens for the callback event
- Your app then securely polls the backend using the existing `sessionID`

This ensures:

✅ Tamper resistance  
✅ Cross-platform reliability  
✅ Zero sensitive data in URLs

---

> **Never pass authentication data via URL parameters. Always rely on Pelican’s secure session-based retrieval flow.**

Configure deep linking:

- **iOS:** Xcode → Info → URL Types
- **Android:** `AndroidManifest.xml` intent filter

---

## Usage

### Basic Usage

```tsx
import React from "react";
import { View } from "react-native";
import { PelicanAuth } from "@pelican-identity/react-native";

export default function App() {
  return (
    <View style={{ flex: 1 }}>
      <PelicanAuth
        publicKey="your-business-public-key"
        projectId="your-project-id"
        appId="com.yourcompany.myapp"
        authType="signup"
        callBackUrl="myapp://auth-callback"
        onSuccess={(data) => {
          console.log("Authentication successful:", data);
        }}
        onError={(error) => {
          console.error("Authentication failed:", error);
        }}
      />
    </View>
  );
}
```

---

## Complete Example

```tsx
import React, { useState } from "react";
import { View, Text, StyleSheet } from "react-native";
import { PelicanAuth } from "@pelican-identity/react-native";

export default function LoginScreen() {
  const [user, setUser] = useState(null);
  const [error, setError] = useState<string | null>(null);

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Login to MyApp</Text>

      <PelicanAuth
        publicKey="your-business-public-key"
        projectId="your-project-id"
        appId="com.yourcompany.myapp"
        authType="login"
        callBackUrl="myapp://auth-callback"
        onSuccess={(data) => {
          setUser(data);
          // Send user data to your backend
          setError(null);
        }}
        onError={(err) => {
          setError(err.message);
          setUser(null);
        }}
      />

      {user && <Text style={styles.success}>Authenticated successfully</Text>}

      {error && <Text style={styles.error}>{error}</Text>}
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, justifyContent: "center", alignItems: "center" },
  title: { fontSize: 22, fontWeight: "bold", marginBottom: 20 },
  success: { color: "green", marginTop: 20 },
  error: { color: "red", marginTop: 20 },
});
```

---

## API Reference

### `PelicanAuth`

Main authentication component.

#### Props

| Prop                | Type                                       | Required | Description                                                                                                                                                          |
| ------------------- | ------------------------------------------ | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `publicKey`         | `string`                                   | ✅       | Business public key from Pelican dashboard                                                                                                                           |
| `projectId`         | `string`                                   | ✅       | Project ID from Pelican dashboard                                                                                                                                    |
| `appId`             | `string`                                   | ✅       | App bundle identifier                                                                                                                                                |
| `authType`          | `"signup" \| "login" \| "id-verification"` | ✅       | Authentication flow                                                                                                                                                  |
| `onSuccess`         | `(data: IdentityResult) => void`           | ✅       | Success callback containing authenticated user data                                                                                                                  |
| `callBackUrl`       | `string`                                   | ✅       | Deeplink to return to app                                                                                                                                            |
| `onError`           | `(error) => void`                          | Optional | Error callback                                                                                                                                                       |
| `onLoading`         | `(loading: boolean) => void`               | Optional | Loading callback, useful for loading stares                                                                                                                          |
| `buttonComponent`   | `ReactNode`                                | Optional | Custom trigger UI                                                                                                                                                    |
| `onAppNotInstalled` | `(error) => void`                          | Optional | A callback function invoked when the Pelican vault app is not installed on the user's device, if not provided an alert will be shown to the user to download the app |

> If `appId` is missing or does not match the whitelisted value, Pelican will fail immediately.

### Best practice

Fetch your Pelican configuration (public key, project ID) from your backend at runtime instead of hard-coding them into your mobile app.
👉 **Pelican Dashboard:** https://dash.pelicanidentity.com

---

# Authentication Response

When authentication completes successfully, Pelican returns a structured **identity result** to your application via the `onSuccess` callback.

This response contains a **deterministic user identifier** for your business, along with optional verified user data and identity verification (KYC) information depending on the authentication flow used.

---

## Success Callback

```ts
onSuccess: (result: IdentityResult) => void;
```

---

## IdentityResult

```ts
interface IdentityResult {
  /** Deterministic unique user identifier specific to your business */
  user_id: string;

  /** Authentication Assurance level */
  /** AAL1 - Passcode */
  /** AAL2 - Biometric */
  assurance_level: { level: number; type: "passcode" | "biometric" };
  /** Basic user profile and contact information (if available) */
  user_data?: IUserData;

  /** Identity document and liveness verification data */
  id_verification: IKycData;

  /** Download URLs for verified identity documents */
  id_downloadurls?: {
    front_of_card?: string;
    back_of_card?: string;
  };
  /** Location data from the user's device */
  location?: { latitude: number; longitude: number } | null;
}
```

---

## `user_id`

- A **stable, deterministic identifier** generated by Pelican.
- Unique **per business**, not global.
- Safe to store and use as your internal user reference.
- Does **not** expose personally identifiable information (PII).

> This identifier remains the same for the same user across future authentications within your business.

---

## Assurance Level (`assurance_level`)

Pelican will prompt users to authenticate using the required assurance level configured in the project settings when possible. Authentication may still succeed with a lower level, but the achieved assurance level is always returned in the response. Your application is responsible for enforcing access based on this level.

```ts
interface AssuranceLevel {
  level: number;
  type: "passcode" | "biometric";
}
```

## User Data (`user_data`)

Returned when available and permitted by the authentication flow.

```ts
interface IUserData {
  first_name?: string;
  last_name?: string;
  other_names?: string;
  email?: IEmail;
  phone?: IPhone;
  dob?: string | Date;
  gender?: "male" | "female" | "other";
  country?: string;
  state?: string;
  city?: string;
  address?: string;
  occupation?: string;
  company?: string;
  website?: string;
}
```

### Email

```ts
interface IEmail {
  id: number;
  value: string;
  verifiedAt: string;
  verificationProvider: string;
}
```

### Phone

```ts
interface IPhone {
  id: number;
  country: string;
  callingCode: string;
  number: string;
  verifiedAt: string;
  verificationProvider: string;
}
```

All contact data returned by Pelican is **verified** and includes the service used for verification.

---

## Identity Verification (`id_verification`)

Returned for flows involving identity verification or KYC.

```ts
interface IKycData {
  id: number;
  status?: "Approved" | "Declined" | "In Review";
  document_type?:
    | "national id card"
    | "passport"
    | "driver's license"
    | "residence permit";
  document_number?: string;
  personal_number?: string;
  date_of_birth?: string | Date;
  age?: number;
  expiration_date?: string | Date;
  date_of_issue?: string | Date;
  issuing_state?: string;
  issuing_state_name?: string;
  first_name?: string;
  last_name?: string;
  full_name?: string;
  gender?: string;
  address?: string;
  formatted_address?: string;
  nationality?: string;
  liveness_percentage?: number;
  face_match_percentage?: number;
  verified_at?: string | Date;
}
```

### Verification Scores

- `liveness_percentage`: Confidence score (0–100) from face liveness detection.
- `face_match_percentage`: Confidence score (0–100) matching selfie to document photo.

---

## Document Downloads

If document access is enabled for your project (NB: your business must be verified and KYB completed), Pelican provides secure download URLs valid for 24 hours as Pelican does not store documents and only provides access to them from the Pelican vault for a limited time. You are required to download and store the documents on your backend for compliance and security reasons according to your local data protection regulations:

```ts
id_downloadurls?: {
  front_of_card?: string;
  back_of_card?: string;
};
```

These URLs are:

- Short-lived
- Access-controlled
- Intended for secure backend or compliance workflows

---

## Authentication Flow Differences

| Auth Type         | Returned Data                               |
| ----------------- | ------------------------------------------- |
| `signup`          | `user_id`, basic `user_data`                |
| `login`           | `user_id`, previously generated at signup   |
| `id-verification` | `user_id`, `id_verification`, document URLs |

Returned fields depend on:

- User consent
- Project configuration
- Regulatory requirements

---

## Troubleshooting

### Missing app identifier.

- Ensure you passed the `appId` prop
- Ensure it matches the bundle identifier configured in your app

### No whitelisted app IDs found

- Add the `appId` to your Pelican project whitelist
- Ensure there are no typos or environment mismatches

### “crypto.getRandomValues() not supported”

- Ensure `react-native-get-random-values` is imported **before anything else**

### Redirect doesn’t return to app

- Verify `callBackUrl` scheme matches your app configuration
- Confirm deep linking is correctly set up

### Unsupported authentication type

- Ensure you passed a valid `authType` prop

### Billing issues, please contact this site owner

- Ensure your business wallet has sufficient balance
- Pelican attempts to send a low balance alert to your email, you can configure the threshold in the Pelican dashboard
  👉 **Pelican Dashboard:** https://dash.pelicanidentity.com

### Project not found

- Ensure you passed a valid `projectId` prop
- Ensure it matches the project ID configured in your app
  👉 **Pelican Dashboard:** https://dash.pelicanidentity.com

### Business not found

- Ensure you passed a valid `publicKey` prop
- Ensure it matches the business ID configured in your app
  👉 **Pelican Dashboard:** https://dash.pelicanidentity.com

---

## Error Handling

If authentication fails, the `onError` callback is invoked:

```ts
onError?: (error: Error) => void;
```

Common error scenarios include:

- User cancellation
- Network failure
- Invalid project configuration
- Session expiration
- Invalid authentication type
- Billing issues

---

## Security Notes

- All identity data is transmitted **encrypted**.
- Pelican never exposes raw credentials.
- Identifiers are scoped per business.
- Mobile identifiers (App ID / Bundle ID) are used for **application identification**.

---

### Final note

Pelican deliberately separates:

- **Identity** (who the user is)
- **Authentication** (this session)
- **Verification** (how confident we are)

This keeps your app flexible, compliant, and secure by default.

## License

MIT