## Before you start

Get a valid SDK key from the [Developer Workbench > SDK Keys](https://help.socure.com/riskos/docs/integration-guide-authentication#/) page in RiskOS™.

## Adding the Web SDK code

There are two ways to incorporate the SDK into your application. It can be included via a `<script>` tag directly within the website where capture needs to happen. Alternatively, it can be incorporated within the website via inclusion as an NPM dependency.

### Option 1: Setup via a Script Tag

In the following Web SDK code, replace `<SOCURE-SDK-KEY>` with your SDK key. Add the code to all pages that you use to make RiskOS™ API calls. We recommend that you deploy the Web SDK code across your application or the user funnel. When included via script tag, the SDK automatically initializes. By including the Web SDK across the user funnel, you can observe the device across the session, allowing for more granular monitoring.

HTML

```html
<script defer src="https://sdk.dv.socure.io/latest/device-risk-sdk.js"
            data-public-key="<SOCURE-SDK-KEY>">
</script>
```

Instead of including the `data-public-key` via the script tag, you can start the Device Risk SDK using the `initialize(...)` method, as described in the next section. Note that if the script is included asynchronously, you must ensure that the script is fully loaded and the `SigmaDeviceManager` object is available before calling the `initialize(...)` method.

### Option 2: Setup via NPM

Include the SDK in your application by first installing the dependency:

Shell

```shell
npm install --save @socure-inc/device-risk-sdk
```

Next the SDK needs to be initialized to start collection. The initialization should only happen once within the application. Ideally this should be in a high level component within a web framework like React to ensure it isn't continually re-initialized on state changes. Initialization can be done as follows:

TypeScript

```typescript
SigmaDeviceManager.initialize({
  sdkKey: <SOCURE-SDK-KEY>,
});
```

## Configuration

Configuration of the SDK can be done by passing the options to the initialize method using the object or via attributes on the script tag. The configuration object is as follows:

TypeScript

```typescript
interface SigmaDeviceOptions {
  sdkKey: string;
  configBaseUrl?: string;
  useSocureGov?: boolean;
  customerSessionId?: string;
  disableDeviceCookie?: boolean;
  deviceCookieName?: string;
  disableEventFilter?: boolean;
  enableDetailedMediaCapture?: boolean;
  disableNavigationContextTracking?: boolean;
}
```

The configuration options are as follows with the `[script tag]` equivalent in brackets.

- `sdkKey` \[`data-public-key`\]: The SDK Key that can be found in the **For Developers > SDK Keys** page in RiskOS™
  
- `configBaseUrl` \[`data-base-url`\]: **Optional** The base URL for the SDK to use when making requests. This needs to be configured when the SDK is being accessed through a proxy.
  
- `useSocureGov` \[`data-use-socure-gov`\]: **Optional** A flag to enable the use of the Socure GovCloud environment. This should only be set to true if the SDK key is a SocureGov key. This option is ignored if `configBaseUrl` is set.
  
- `customerSessionId` \[`data-customer-session-id`\]: **Optional** A customer defined identifier to use for the ongoing device session. See Using customer provided identifiers for more details
  
- `disableDeviceCookie` \[`data-disable-device-cookie`\]: **Optional** Disables the creation of a Socure device cookie by the SDK. Disabling this may impact device tracking across subdomains by the SDK.
  
- `deviceCookieName` \[`data-device-cookie-name`\]: **Optional** A method to override the default Socure device cookie name which is `_s_did`. This can be useful if the default value conflicts with an existing cookie name.
  
- `disableEventFilter` \[`data-disable-event-filter`\]: **Optional** A flag to disable the filter applied to behavioral events that restricts reported events to only those that are relevant to forms. This is false by default. Setting this to true will remove the filter and allow all events to be reported. We do not recommend using this now unless the built-in event filter is restricting the reporting of events due to the use of Shadow DOM or other non-standard form elements.
  
- `enableDetailedMediaCapture`: **Optional** A flag to enable the detailed media capture. This is false by default. Setting this to true will enable the detailed media capture.
  
- `disableNavigationContextTracking` \[`data-disable-nav-context-tracking`\]: **Optional** A flag that disables the automatic page navigation tracking and allows the developer to manually control the navigation contexts. When you set this value to `true`, you control navigation entirely by calling the `SigmaDeviceManager.setNavigationContext` method, and the navigation context shows as `unset` until this method sets a new context. Tie the context to portions of the web application, such as `login` or `registration`. These contexts group behavioral data where it occurs and are useful when fetching data captured in a specific portion of the application.

## Using the SDK

Upon inclusion of the above script, the `SigmaDeviceManager` becomes available. This object provides methods of interacting with the Socure SDK. Most notably it provides a way of fetching the current `sessionToken`.

The `getSessionToken` method returns a Promise that resolves to the `sessionToken` for use in a RiskOS™ API call. A sample of getting this `sessionToken` looks as follows:

JavaScript

```javascript
SigmaDeviceManager.getSessionToken().then((sessionToken) => {
  console.log("sessionToken", sessionToken);
  // Logic to store this sessionToken
})
```

Once retrieved, your application should record this `sessionToken` for use in the RiskOS™ API requests associated with this transaction. The `sessionToken` is passed to the RiskOS™ API call in the `di_session_token` field.

### Socure Javascript Device Cookie

Socure uses multiple methods of maintaining the identity of a device. One method is the creation of a first party cookie by the SDK. This cookie aids in tracking the device across all the subdomains the SDK is implemented against. For example, this helps in maintaining device identification across `domain.com` and `payments.domain.com` automatically.

### Controlling Data Collection

By default the SDK will begin collecting data automatically. This includes data about the device and the way the user is interacting with the application. This data will be tracked as long as the web page (or tab) is in the foreground. Data collection is paused automatically when the page is in the background and automatically resumes when in the foreground.

In the event that further control over data collection is needed, two methods are supplied by the SDK:

- `SigmaDeviceManager.pauseDataCollection()` \- Will pause ongoing user behavior and interaction data collection. Data collection will not resume until `SigmaDeviceManager.resumeDataCollection()` is called.
- `SigmaDeviceManager.resumeDataCollection()` \- Will resume data collection if collection was paused.

### Capturing detailed media device information

v2.8.0+ of the SDK has support for the `SigmaDeviceManager.captureDetailedMediaInfo()` method. This method triggers the capture of detailed information about the attached media devices. This method can be used to trigger the capture at a specific point in the application flow as opposed to the automatic capture that happens when the `SigmaDeviceOptions.enableDetailedMediaCapture` config flag is set to `true`.

### Custom Navigation

The Web SDK automatically tracks page navigation by default using the path and hash values of the current page. You can disable this automated navigation tracking by setting `disableNavigationContextTracking: true` in the initialization options.

Update the navigation each time the user moves to a new context within the web application. This allows the SDK to automatically associate all events with the context in which they occur.

To set the navigation context, use the following:

JavaScript

```javascript
SigmaDeviceManager.setNavigationContext('MyNewContext')
  .then(() => {
    console.log('Navigation context set successfully');
  })
  .catch((e) => {
    console.error('Failed to set navigation context', e);
  })
```

### Silent Network Authentication

The Digital Intelligence Web SDK provides the `performSilentNetworkAuth(mobileNumber: string)` method to perform Silent Network Authentication using SIM-based verification. This lets you verify device possession of a specified mobile number without requiring user interaction.

Silent Network Authentication runs asynchronously. The SDK doesn't return the result directly to the caller; instead, the result becomes available for use within RiskOS™ decisioning workflows.

**Requirements:**

- The device must have an active SIM card and cellular data enabled.
- Devices without cellular connectivity or with no SIM do not complete authentication, but this status is still reported for workflow decisioning.
- Your account must have the `SilentNetworkAuth` feature provisioned.

Provide the `mobileNumber` parameter in E.164 format (for example, `+12345678901`):

JavaScript

```javascript
SigmaDeviceManager.performSilentNetworkAuth('+12345678901')
  .then(() => {
    console.log('Silent Network Authentication completed');
  })
  .catch((e) => {
    console.error('Silent Network Authentication failed', e);
  })
```

## Server-side configuration

By default, nothing needs to be done server-side to enable the collection of device data. However, if certain server configurations are in place, there are some updates that will need to be made to use the SDK.

### `Content-Security-Policy`

A `Content-Security-Policy` is a header that is used to control which resources can be used by a given web page. For more details, see the Mozilla Developer Network documentation.

If a `Content-Security-Policy` is in place, the following elements will be needed to make sure the SDK can correctly report to Socure services.

#### `connect-src`

The `connect-src` directive restricts the URLs which can be interacted with by script interfaces. For more details, see the Mozilla Developer Network documentation.

To allow the most flexibility, the following `connect-src` can be set in the Content Security Policy to make sure all Socure services are reachable, including any additional subdomains that may be required in the future.

```undefined
connect-src https://*.socure.io;
```

Should you wish to restrict it more explicitly, the `connect-src` policy will need to be configured as follows:

```undefined
connect-src https://ingestion.dv.socure.io https://analytics.dv.socure.io https://network.dv.socure.io;
```

#### `script-src`

The `script-src` directive restricts which domains can be used for loading JavaScript. For more details, see the Mozilla Developer Network documentation.

All versions of the SDK are fetched through the `sdk.dv.socure.io` domain. To include a `script-src` Content-Security-Policy, include the following:

```undefined
script-src https://sdk.dv.socure.io/;
```

#### Full example

The following is a full example of a `Content-Security-Policy` that is compatible for a site using the Socure Digital Intelligence Web SDK:

Text

```text
Content-Security-Policy: "connect-src 'self' https://*ingestion.dv*.socure.io; script-src 'self' https://sdk.dv.socure.io/"
```
