youverify-liveness-web
Version:
> Software Development Kit for [Youverify](https://youverify.co)'s Liveness Check
369 lines (283 loc) • 14.3 kB
Markdown
# Youverify Livess Web SDK
> Software Development Kit for [Youverify](https://youverify.co)'s Liveness Check
## Installation
To install, run one of the following commands:
```sh
npm install youverify-liveness-web
```
or
```sh
yarn add youverify-liveness-web
```
## Usage
1. Import the package into your web page like so:
```js
import YouverifyLiveness from "youverify-liveness-web";
```
2. Initialize an instance of the package, like so:
```js
const yvLiveness = new YouverifyLiveness(options);
```
> For a list of the valid options, check [this](#options) out
3. Start the process, like so:
```js
yvLiveness.start();
```
This could also be called with an array of tasks. The supplied tasks override those provided during initialization.
```js
const tasks = [{ id: "complete-the-circle" }];
yvLiveness.start(tasks);
```
Full Example:
```js
import YouverifyLiveness from "youverify-liveness-web";
try {
const yvLiveness = new YouverifyLiveness({
tasks: [{ id: "complete-the-circle" }],
});
yvLiveness.start();
} catch (error) {
// Handle Validation Errors
console.log(`Something isn't right, ${error}`);
}
```
## Options
| Option | Type | Required | Description | Default Value | Possible Values |
| --- | --- | --- | --- | --- | --- |
| `presentation` | String | No | Controls how UI is displayed | `modal` | `modal`, `page` |
| `publicKey` | String | No | Your Youverify Public Merchant Key | undefined | Valid Youverify Public Key |
| `entityId` | String | No | Optional entity identifier to include when the liveness result is submitted | undefined | Any valid entity ID |
| `sandboxEnvironment` | Boolean | No | Sets whether session should run in sandbox or live mode | `true` | `true`, `false` |
| `tasks` | Array | No | Sets tasks that need to be performed for liveness to be confirmed | undefined | See [tasks](#tasks) |
| `user` | Object | No | Sets details of user for which liveness check is being performed | undefined | See nested options below |
| `user.firstName` | String | Yes | First name of user | - | Any string |
| `user.lastName` | String | No | Last name of user | undefined | Any string
| `user.email` | String | No | Email of user | undefined | Any string |
| `branding` | Object | No | Customizes UI to fit your brand | undefined | See nested options below
| `branding.name` | String | No | The name of the brand | undefined | Any string |
| `branding.color` | String | No | Sets your branding color | undefined | Valid hex or RGB string |
| `branding.logo` | String | No | Sets your logo | undefined | Valid image link |
| `branding.logoAlt` | String | No | Alternative text for the brand logo | "Youverify" | Any string |
| `branding.hideLogoOnMobile` | Boolean | No | Hides logo in mobile webview | `false` | `true`, `false` |
| `branding.showPoweredBy` | Boolean | No | Displays "Powered by" footer text | `false` | `true`, `false` |
| `branding.poweredByText` | String | No | Customizes the "Powered by" text | "Powered by" | Any string |
| `branding.poweredByLogo` | String | No | Customizes the "Powered by" logo | undefined | Valid image link |
| `allowAudio` | Boolean | No | Sets whether to narrate information to user during tasks | false | `true`, `false` |
| `onClose` | Function | No | Callback function that gets triggered when modal is closed | undefined | Any valid function |
| `onSuccess` | Function | No | Callback function that gets triggered when all tasks have been completed and passed. Called with completion [data](#callback-data) | undefined | Any valid function |
| `onFailure` | Function | No | Callback function that gets triggered when at least one task fails. Called with completion [data](#callback-data) | undefined | Any valid function |
| `sessionId` | String | Yes (required) | ID generated by your backend using your API key. Validated before SDK init and attached to submissions | - | Any valid session ID |
| `sessionToken` | String | Yes (required) | Token generated by your backend for liveness verification | - | Any valid session token |
### Breaking change: session token generation now external
- The SDK no longer generates session tokens internally.
- Partners must call their backend to generate both `sessionId` and `sessionToken` and pass them to the SDK via the respective options.
### Base URL Configuration
All API endpoints use the following base URL:
Sandbox base URL:
```
https://api.sandbox.youverify.co
```
Live base URL:
```
https://api.youverify.co
```
### Session ID Generation
Before initializing the SDK, you must generate a `sessionId` by calling your backend API. Your backend should make the following request:
**Endpoint:** `POST /v2/api/identity/sdk/session/generate`
**Headers:**
```json
{
"Content-Type": "application/json",
"Token": "YOUR_API_KEY"
}
```
**Request Body:**
```json
{
"publicMerchantID": "your_public_merchant_id",
"metadata": {}
}
```
**Response:**
```json
{
"sessionId": "generated_session_id_here"
}
```
**Error Handling:**
- The `sessionId` should be passed to the SDK constructor
### Session Token Generation
Additionally, you need to generate a `sessionToken` for liveness verification:
**Endpoint:** `POST /v2/api/identity/sdk/liveness/token`
**Headers:**
```json
{
"Content-Type": "application/json",
"Token": "YOUR_API_KEY"
}
```
**Request Body:**
```json
{
"publicMerchantID": "your_public_merchant_id",
"deviceCorrelationId": "unique_device_identifier"
}
```
**Response:**
```json
{
"authToken": "generated_auth_token_here"
}
```
**Error Handling:**
- The `authToken` from the response should be passed as `sessionToken` to the SDK constructor
### Complete Integration Flow
1. **Generate Session ID:** Call your backend to generate `sessionId` using the session generation endpoint
2. **Generate Session Token:** Call your backend to generate `sessionToken` using the liveness token endpoint
3. **Initialize SDK:** Pass both `sessionId` and `sessionToken` to the SDK constructor
4. **SDK Validation:** The SDK validates the `sessionId` before initialization
5. **Error Handling:** If validation fails, `onFailure` is called with key `invalid_or_expired_session` and `session_token_error` for both
6. **Success:** Upon successful initialization, the SDK uses the `sessionToken` for liveness verification
### Error Keys
- `invalid_or_expired_session`: Returned when the `sessionId` is invalid or expired
- `session_token_error`: Returned when there's an issue with the `sessionToken` during liveness verification
### Retry Logic
- If session validation fails, generate a new `sessionId` and retry
- If liveness fails, users may retry while the current `sessionId` remains valid
- If the `sessionId` expires, create a new session and restart the entire process
### Complete Example Implementation
Here's a complete example showing how to implement the session generation and SDK initialization:
```javascript
// Backend API calls (these should be made from your backend)
const generateSessionId = async (publicMerchantID, apiToken) => {
const response = await fetch('https://api.sandbox.youverify.co/v2/api/identity/sdk/session/generate', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Token': `${apiToken}`
},
body: JSON.stringify({
publicMerchantID: publicMerchantID,
metadata: {}
})
});
const data = await response.json();
return data.sessionId;
};
const generateSessionToken = async (publicMerchantID, deviceCorrelationId, apiToken) => {
const response = await fetch('https://api.sandbox.youverify.co/v2/api/identity/sdk/liveness/token', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Token': `${apiToken}`
},
body: JSON.stringify({
publicMerchantID: publicMerchantID,
deviceCorrelationId: deviceCorrelationId
})
});
const data = await response.json();
return data.authToken;
};
// Frontend SDK initialization
const initializeLivenessSDK = async () => {
try {
// Generate session ID and token (these calls should be made from your backend)
const sessionId = await generateSessionId('your_public_merchant_id', 'your_api_key');
const sessionToken = await generateSessionToken('your_public_merchant_id', 'unique_device_id', 'your_api_key');
// Initialize the SDK with generated credentials
const yvLiveness = new YouverifyLiveness({
sessionId: sessionId,
sessionToken: sessionToken,
entityId: 'your_optional_entity_id',
sandboxEnvironment: true,
onSuccess: (data) => {
console.log('Liveness check passed:', data);
// Handle successful liveness check
},
onFailure: (data) => {
console.log('Liveness check failed:', data);
// Handle specific error cases
if (data.error && data.error.key === 'invalid_or_expired_session') {
// Session expired, generate new session and retry
console.log('Session expired, retrying...');
initializeLivenessSDK();
} else if (data.error && data.error.key === 'session_token_error') {
// Session token error, generate new token and retry
console.log('Session token error, retrying...');
initializeLivenessSDK();
}
}
});
// Start the liveness check
yvLiveness.start();
} catch (error) {
console.error('Failed to initialize liveness SDK:', error);
// Handle initialization errors
}
};
// Call the initialization function
initializeLivenessSDK();
```
When the SDK submits the liveness payload to `/identity/liveness/`, it now includes:
- `sdkVersion`: the SDK package version, `1.1.1`
- `entityId`: only when you pass it during SDK initialization
### Important Notes
1. **API Token Security:** Never expose your API token in frontend code. All API calls to generate `sessionId` and `sessionToken` should be made from your secure backend.
2. **Device Correlation ID:** The `deviceCorrelationId` should be a unique identifier for the user's device/session. This helps track and prevent abuse.
3. **Error Handling:** Always implement proper error handling for both API calls and SDK initialization to provide a smooth user experience.
4. **Environment:** Use `sandboxEnvironment: true` for testing and `sandboxEnvironment: false` for production.
## Tasks
A task is a series of instructions for users to follow to confirm liveness. Find below a list of tasks.
> PS: We aim to frequently add to this list a variety of fun and yet intuitive ways of confirming liveness, so be on the lookout for more tasks!
### Complete The Circle
User passes task by completing imaginary circle with head movement.
#### Options
| Option | Type | Required | Description | Default Value | Possible Values |
| --- | --- | --- | --- | --- | --- |
`id` | String | Yes | Id of task | - | `complete-the-circle` |
`difficulty` | String | No | Sets difficulty of task | `medium` | `easy`, `medium`, `hard` |
`timeout` | Number | No | Sets time in milliseconds after which task automatically fails | undefined | Any number in milliseconds |
### Yes Or No
User passes task by answering a list of arbitrary questions set by you with the tilting of the head; right for a `yes` and left for a `no`.
#### Options
| Option | Type | Required | Description | Default Value | Possible Values |
| --- | --- | --- | --- | --- | --- |
| `id` | String | Yes | Id of task | - | `yes-or-no` |
| `difficulty` | String | No | Sets difficulty of task | `medium` | `easy`, `medium`, `hard` |
| `timeout` | Number | No | Sets time in milliseconds after which task automatically fails | undefined | Any number in milliseconds |
| `questions` | Array | No | A set of questions to ask user | undefined | See nested options below
| `questions.question` | String | Yes | Question to ask user. Should be a `true` or `false` type question. Eg: "Are you ready" | - | Any string
| `questions.answer` | Boolean | Yes | Answer to the question | - | `true`, `false` |
| `questions.errorMessage` | String | No | Error message to display if user gets question wrong | undefined | Any string |
### Motions
User passes task by performing random motions in random sequences, which include `nodding`, `blinking` and `opening of mouth`.
#### Options
| Option | Type | Required | Description | Default Value | Possible Values |
| --- | --- | --- | --- | --- | --- |
| `id` | String | Yes | Id of task | - | `motions` |
| `difficulty` | String | No | Sets difficulty of task | `medium` | `easy`, `medium`, `hard` |
| `timeout` | Number | No | Sets time in milliseconds after which task automatically fails | undefined | Any number in milliseconds |
| `maxNods` | Number | No | Maximum amount of nods a user is asked to perform | 5 | Any number
| `maxBlinks` | Number | No | Maximum amount of nods a user is asked to perform | 5 | Any number |
### Blink
User passes task by blinking their eyelids based on number of times set.
#### Options
| Option | Type | Required | Description | Default Value | Possible Values |
| --- | --- | --- | --- | --- | --- |
| `id` | String | Yes | Id of task | - | `blink` |
| `difficulty` | String | No | Sets difficulty of task | `medium` | `easy`, `medium`, `hard` |
| `timeout` | Number | No | Sets time in milliseconds after which task automatically fails | undefined | Any number in milliseconds |
| `maxBlinks` | Number | No | Maximum amount of nods a user is asked to perform | 5 | Any number |
## Callback Data
The `onSuccess` and `onFailure` callbacks (if supplied) are passed the following data:
| Option | Type | Description |
| --- | --- | --- |
| `data` | Object | Data passed through callback |
| `data.faceImage` | String | Face Image of user performing liveness check |
| `data.livenessClip` | String | Video of user performing liveness check |
| `data.passed` | Boolean | Indicator on whether liveness check passed or failed |
| `data.metadata` | Any | Metadata passed in during initialization |
| `data.error` | Object | Error object containing error key(`eyes_closed`, `image_capture_failed`, `API_ERROR`) and message (only present in failure cases) |
## Credits
This SDK is developed and maintained solely by [Youverify](https://youverify.co)