npm package: @raytio/core
Description: `@raytio/core` is a collection of low-level functions for using the Raytio API. It works in both the browser and a nodejs environment, although nodejs requires several polyfills (see below).
Latest version: 11.5.0

# @raytio/core

`@raytio/core` is a collection of low-level functions for using the Raytio API. It works in both the browser and a nodejs environment, although nodejs requires several polyfills (see below).

For a high-level and easy-to-use API, consider using [`@raytio/decrypt-helper`](https://npm.im/@raytio/decrypt-helper).

## Usage in nodejs

Nodejs does not support [fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch), [WebCrypto](https://developer.mozilla.org/en-US/docs/Web/API/Web_Crypto_API), or [atob](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/atob)/[btoa](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/atob), so these will need to be polyfilled. Older versions of nodejs (`<14.0.0`) also do not support [TextEncoder](https://developer.mozilla.org/en-US/docs/Web/API/TextEncoder) or [Intl.DateTimeFormat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat).

If you use the high-level [`@raytio/decrypt-helper`](https://npm.im/@raytio/decrypt-helper) module, you don't need to worry about this.

If you wish to use `@raytio/core` directly, an example of configuring polyfills for nodejs is availble [here](https://gitlab.com/raytio/tools/decrypt-helper/-/blob/main/src/configureEnv.ts)

# API

## Table of contents

### Type Aliases

- [SafeHarbourObj](#safeharbourobj)
- [SafeHarbourResult](#safeharbourresult)
- [ServerAA](#serveraa)
- [ServerRelationship](#serverrelationship)
- [VerDetails](#verdetails)

### Variables

- [TAG\_DENYLIST](#tag_denylist)

### Functions

- [calcSafeHarbourScore](#calcsafeharbourscore)
- [calculateScore](#calculatescore)
- [checkJsonSignature](#checkjsonsignature)
- [convertInstanceToRuleInput](#convertinstancetoruleinput)
- [convertServerRelationship](#convertserverrelationship)
- [createAA](#createaa)
- [createHashedNId](#createhashednid)
- [decryptSharedData](#decryptshareddata)
- [evaluateRule](#evaluaterule)
- [expandSchema](#expandschema)
- [findSchemaLabel](#findschemalabel)
- [findSuitableLocale](#findsuitablelocale)
- [fromCognitoAttributes](#fromcognitoattributes)
- [getAADecryptor](#getaadecryptor)
- [getAAPublicKey](#getaapublickey)
- [getMissingDataForInstance](#getmissingdataforinstance)
- [getNidFromUrn](#getnidfromurn)
- [getOwnRealVerifications](#getownrealverifications)
- [getPOVerification](#getpoverification)
- [getSomeoneElsesRealVerifications](#getsomeoneelsesrealverifications)
- [hashPassword](#hashpassword)
- [isConditionMet](#isconditionmet)
- [isEncrypted](#isencrypted)
- [isEncryptedFile](#isencryptedfile)
- [isScoreConfigValid](#isscoreconfigvalid)
- [isScoreResultValid](#isscoreresultvalid)
- [repairDate](#repairdate)
- [someEncrypted](#someencrypted)
- [sortSchemaProperties](#sortschemaproperties)
- [toCognitoAttributes](#tocognitoattributes)

## Type Aliases

### SafeHarbourObj

Ƭ **SafeHarbourObj**: `Partial`<`Record`<`SafeHarbourCode`, `string`[]\>\>

an object listing the `xId`s for each SafeHarbourCode

___

### SafeHarbourResult

Ƭ **SafeHarbourResult**: `Object`

the response from [calcSafeHarbourScore](#calcsafeharbourscore)

#### Type declaration

| Name | Type |
| :------ | :------ |
| `flags` | [`SafeHarbourObj`](#safeharbourobj) |
| `isSafe` | `boolean` |

___

### ServerAA

Ƭ **ServerAA**: `Omit`<`AA`, ``"a_id"``\> & { `id`: `AId`  }

___

### ServerRelationship

Ƭ **ServerRelationship**: `Omit`<`Relationship`, ``"p_id"`` \| ``"start"`` \| ``"end"``\> & { `from_id`: `NId` ; `id`: `PId`  } & { `to_id`: `NId`  } \| { `to_i_id`: `IId`  }

This type represents the relationship format returned by the Postgres API

___

### VerDetails

Ƭ **VerDetails**: `Object`

#### Type declaration

| Name | Type | Description |
| :------ | :------ | :------ |
| `expiryDate?` | `Date` | field only present for expired verifications |
| `sourceNId?` | `NId` | - |
| `verifiers` | `VerificationProvider`[] | - |

## Variables

### TAG\_DENYLIST

• `Const` **TAG\_DENYLIST**: `SchemaTag`[]

## Functions

### calcSafeHarbourScore

▸ **calcSafeHarbourScore**(`data`): `Promise`<[`SafeHarbourResult`](#safeharbourresult)\>

The Safe Harbour Score indidicates whether a person's identity has been verified
to the extent requried for Safe Harbour Compliance. This requires multiple verifications
from different sources. For information, refer to the
[Raytio Documentation](https://dev-docs.rayt.io/docs/features/pep-checks).

#### Parameters

| Name | Type |
| :------ | :------ |
| `data` | `Object` |
| `data.person` | `ProfileObject` |
| `data.profileObjects` | `ProfileObject`[] |
| `data.realVers` | `RealVer`[] |
| `data.getSchema` | (`schemaName`: `SchemaName`) => `Promise`<`Schema`\> |

#### Returns

`Promise`<[`SafeHarbourResult`](#safeharbourresult)\>

___

### calculateScore

▸ **calculateScore**(`ruleConfig`, `ruleInput`): `Promise`<`ScoreResult`\>

the main function to calculate a score and category.
Might throw an error.

#### Parameters

| Name | Type |
| :------ | :------ |
| `ruleConfig` | `ScoreConfig` |
| `ruleInput` | `RuleData` |

#### Returns

`Promise`<`ScoreResult`\>

___

### checkJsonSignature

▸ **checkJsonSignature**(`data`, `signature`, `keyId`): `Promise`<`boolean`\>

checks that a json object was signed by the provided signature. Unless you're
dealing with bundled verifications, you should use `getOwnRealVerifications`
or `getSomeoneElsesRealVerifications` instead.

#### Parameters

| Name | Type |
| :------ | :------ |
| `data` | `unknown` |
| `signature` | `string` |
| `keyId` | `undefined` \| `string` |

#### Returns

`Promise`<`boolean`\>

___

### convertInstanceToRuleInput

▸ **convertInstanceToRuleInput**(`POs`, `realVers`, `getSchema`): `Promise`<`RuleData`\>

#### Parameters

| Name | Type |
| :------ | :------ |
| `POs` | `ProfileObject`[] |
| `realVers` | `RealVer`[] |
| `getSchema` | (`schemaName`: `SchemaName`) => `Promise`<`Schema`\> |

#### Returns

`Promise`<`RuleData`\>

___

### convertServerRelationship

▸ **convertServerRelationship**(`serverRelationship`): `Relationship`

Converts relationship type used by the server into the (Urn format) type used by the client

#### Parameters

| Name | Type | Description |
| :------ | :------ | :------ |
| `serverRelationship` | [`ServerRelationship`](#serverrelationship) | relationship type used in the server |

#### Returns

`Relationship`

a Relationship (client-side type) that is equivalent to the inputted serverRelationship value

___

### createAA

▸ **createAA**(`«destructured»`): `Promise`<`AA`\>

Creates an Access Application and associated public+private keys.

The user must be part of an organization, and you need to include the `orgId`.

You must also supply an apiToken and an instance of the maxcryptor for that user,
as well as the `userDoc` data which is stored in the user's cognito attributes.

#### Parameters

| Name | Type |
| :------ | :------ |
| `«destructured»` | `Object` |
| › `apiToken` | `string` |
| › `apiUrl` | `string` |
| › `application` | `Omit`<`AA`, ``"a_id"``\> |
| › `maxcryptor` | `DataEncryptorI` |
| › `userDoc` | `UserDoc` |

#### Returns

`Promise`<`AA`\>

___

### createHashedNId

▸ **createHashedNId**(`nId`, `aId`): `NId`

the API returns hashed NIds in a separate field,
which breaks the whole app. So, we move the hashed ID into
the normal `n_id` field, and use a different format.

This was first introduced in #1048

#### Parameters

| Name | Type |
| :------ | :------ |
| `nId` | `NId` |
| `aId` | `AId` |

#### Returns

`NId`

___

### decryptSharedData

▸ **decryptSharedData**(`«destructured»`): `Promise`<{ `applicationDecryptor`: `ApplicationDataEncryptorI` ; `instance`: `Instance`  }\>

Decrypts any encrypted properties included in the supplied `instanceData`.
If nothing is encrypted the supplied `instanceData` is returned.

It will reject if there are keys missing for any encrypted properties, or
if the encrypted data is invalid. If you don't want it to reject, you can
supply a `onCorruptedData` function which returns a value to use instead.

#### Parameters

| Name | Type |
| :------ | :------ |
| `«destructured»` | `Object` |
| › `apiToken` | `string` |
| › `apiUrl` | `string` |
| › `instanceData` | `Instance` |
| › `maxcryptor` | `DataEncryptorI` |
| › `onCorruptedData?` | (`fieldName`: `string`, `fieldValue`: `Encrypted`, `error`: `Error`) => `any` |

#### Returns

`Promise`<{ `applicationDecryptor`: `ApplicationDataEncryptorI` ; `instance`: `Instance`  }\>

a copy of `instanceData` with all properties decrypted.

___

### evaluateRule

▸ **evaluateRule**(`rule`, `data`): `Object`

evaluates an individual rule, normally you should use [calculateScore](#calculatescore)

#### Parameters

| Name | Type |
| :------ | :------ |
| `rule` | `ScoreRule` |
| `data` | `RuleData` |

#### Returns

`Object`

| Name | Type |
| :------ | :------ |
| `passed` | `boolean` |
| `score` | `number` |

___

### expandSchema

▸ **expandSchema**(`wrappedSchema`, `allUnexpandedSchemas`, `userLocales`): `Schema`

❣️ This is the main function to transform a schema from
the JSON that the API returns, into a `Schema` object that's useful
to the client.

#### Parameters

| Name | Type |
| :------ | :------ |
| `wrappedSchema` | `WrappedSchema` |
| `allUnexpandedSchemas` | `WrappedSchema`[] |
| `userLocales` | readonly `string`[] |

#### Returns

`Schema`

___

### findSchemaLabel

▸ **findSchemaLabel**(`labels`): `undefined` \| `SchemaName`

Finds the label (on a profile object) which is the schema name

#### Parameters

| Name | Type |
| :------ | :------ |
| `labels` | `undefined` \| `string`[] |

#### Returns

`undefined` \| `SchemaName`

___

### findSuitableLocale

▸ **findSuitableLocale**(`options`, `langs`): `undefined` \| `string`

Selects the most suitable locale to use from a list of options.
Returns undefined if there is no language that the user speaks

#### Parameters

| Name | Type |
| :------ | :------ |
| `options` | `string`[] |
| `langs` | readonly `string`[] |

#### Returns

`undefined` \| `string`

___

### fromCognitoAttributes

▸ **fromCognitoAttributes**(`attributes`): `UserDoc`

This function converts Cognito's userAttributes into a maxcryptor UserDoc.
The userAttributes come from `const attributes = await Auth.userAttributes(user)`

#### Parameters

| Name | Type |
| :------ | :------ |
| `attributes` | `ICognitoUserAttributeData`[] |

#### Returns

`UserDoc`

___

### getAADecryptor

▸ **getAADecryptor**(`«destructured»`): `Promise`<{ `decryptor`: `ApplicationEncryptor` ; `publicKeyId`: `KId`  }\>

Fetchs the public and private keys for an Access Application, then initializes
the [https://npm.im/@raytio/maxcryptor|Maxcryptor](https://npm.im/@raytio/maxcryptor|Maxcryptor)'s `ApplicationEncryptor`.

#### Parameters

| Name | Type |
| :------ | :------ |
| `«destructured»` | `Object` |
| › `aId` | `AId` |
| › `apiToken` | `string` |
| › `apiUrl` | `string` |
| › `maxcryptor` | `DataEncryptorI` |

#### Returns

`Promise`<{ `decryptor`: `ApplicationEncryptor` ; `publicKeyId`: `KId`  }\>

an `ApplicationEncryptor` and the public key of the Access Application

___

### getAAPublicKey

▸ **getAAPublicKey**(`«destructured»`): `Promise`<`PublicKeyNode`\>

Fetches the Public Key Information for an Access Application

#### Parameters

| Name | Type |
| :------ | :------ |
| `«destructured»` | `Object` |
| › `aId` | `AId` |
| › `apiToken` | `string` |
| › `apiUrl` | `string` |

#### Returns

`Promise`<`PublicKeyNode`\>

the id and Key information of the Applications Public Key

___

### getMissingDataForInstance

▸ **getMissingDataForInstance**(`«destructured»`): `Promise`<`Instance`\>

the new API doesn't return the whole instance at once,
so we have to make several additional API requests.

#### Parameters

| Name | Type |
| :------ | :------ |
| `«destructured»` | `Object` |
| › `apiToken` | `string` |
| › `apiUrl` | `string` |
| › `instanceWithoutData` | `InstanceWithoutData` |

#### Returns

`Promise`<`Instance`\>

___

### getNidFromUrn

▸ **getNidFromUrn**<`IDType`\>(`urn`): `IDType`

two overloads - if you provide undefined, you might get undefined back

#### Type parameters

| Name | Type |
| :------ | :------ |
| `IDType` | `NId` |

#### Parameters

| Name | Type |
| :------ | :------ |
| `urn` | `Urn` |

#### Returns

`IDType`

▸ **getNidFromUrn**<`IDType`\>(`urn`): `undefined` \| `IDType`

two overloads - if you provide undefined, you might get undefined back

#### Type parameters

| Name | Type |
| :------ | :------ |
| `IDType` | `NId` |

#### Parameters

| Name | Type |
| :------ | :------ |
| `urn` | `undefined` \| `Urn` |

#### Returns

`undefined` \| `IDType`

___

### getOwnRealVerifications

▸ **getOwnRealVerifications**(`«destructured»`): `Promise`<`RealVer`[]\>

Given a list of verifications and decrypted profile objects, this function
locally verifies the credibility of the signatures in the verifications.

This function does NOT call the API, except to fetch the public key.

#### Parameters

| Name | Type |
| :------ | :------ |
| `«destructured»` | `Object` |
| › `profileObjects` | `ProfileObject`[] |
| › `userId` | `UId` |
| › `verifications` | `Verification`[] |

#### Returns

`Promise`<`RealVer`[]\>

a list of authentic RealVer

___

### getPOVerification

▸ **getPOVerification**(`«destructured»`): `Object`

Determines the verification status of a profile object, and its individual fields.

#### Parameters

| Name | Type |
| :------ | :------ |
| `«destructured»` | `Object` |
| › `PO` | `ProfileObject` \| `ProfileObjectForUpload` |
| › `realVers` | `RealVer`[] |
| › `schema` | `Schema` |

#### Returns

`Object`

| Name | Type |
| :------ | :------ |
| `details` | [`VerDetails`](#verdetails) |
| `fieldVerifications` | `Record`<`string`, `FieldVerification`\> |
| `status` | `POVerification` |

___

### getSomeoneElsesRealVerifications

▸ **getSomeoneElsesRealVerifications**(`«destructured»`): `Promise`<`RealVer`[]\>

Given a list of verifications and decrypted profile objects, this function calls
the Raytio API to verify the credibility of these verifications, returning only valid
verifications.

❗ prefer `getOwnRealVerifications` if the data to be verified belongs to the current user.

#### Parameters

| Name | Type |
| :------ | :------ |
| `«destructured»` | `Props` |

#### Returns

`Promise`<`RealVer`[]\>

a list of fileNames/values that are verified.

___

### hashPassword

▸ **hashPassword**(`password`): `Promise`<`string`\>

**`Deprecated`**

legacy feature, see #1252

AWS Cognito never gets the raw password. We send them
a hashed verison using PBKDF2 with SHA-256 and 10,000
iterations.

#### Parameters

| Name | Type | Description |
| :------ | :------ | :------ |
| `password` | `string` | The raw password |

#### Returns

`Promise`<`string`\>

Promise resolving to the hashed password

___

### isConditionMet

▸ **isConditionMet**(`condition`, `formValues`): `boolean`

Checks all other form values in case any have a
trigger value that makes this field required.

**`Example`**

```json
[
  { "if": { "age": [17, 18], "city": ["Taupō"] } },
  { "if": { "age": [19, 20] } }
]
```

This means `[(age=17 OR age=18) AND (city=Taupō)] OR [(age=19 OR age=20)]`

#### Parameters

| Name | Type |
| :------ | :------ |
| `condition` | `Record`<`string`, `ConditionValue`[]\> |
| `formValues` | `Record`<`string`, `unknown`\> |

#### Returns

`boolean`

___

### isEncrypted

▸ **isEncrypted**(`value`): value is Encrypted

Determines where the input is an encrypted Raytio object

#### Parameters

| Name | Type | Description |
| :------ | :------ | :------ |
| `value` | `unknown` | anything |

#### Returns

value is Encrypted

true or false depending on whether the input is an encrypted Raytio object

___

### isEncryptedFile

▸ **isEncryptedFile**(`value`): value is Encrypted

Determines where the input is an encrypted Raytio file

#### Parameters

| Name | Type | Description |
| :------ | :------ | :------ |
| `value` | `unknown` | anything |

#### Returns

value is Encrypted

true or false depending on whether the input is an encrypted Raytio file

___

### isScoreConfigValid

▸ **isScoreConfigValid**(`x`): x is ScoreConfig

determines whether a `ScoreConfig` object is valid

#### Parameters

| Name | Type |
| :------ | :------ |
| `x` | `unknown` |

#### Returns

x is ScoreConfig

___

### isScoreResultValid

▸ **isScoreResultValid**(`x`): x is ScoreResult

determines whether a `ScoreResult` object is valid

#### Parameters

| Name | Type |
| :------ | :------ |
| `x` | `unknown` |

#### Returns

x is ScoreResult

___

### repairDate

▸ **repairDate**(`date`): `Date`

repairs broken ISO dates into valid JS date objects

#### Parameters

| Name | Type |
| :------ | :------ |
| `date` | `string` \| `Date` |

#### Returns

`Date`

___

### someEncrypted

▸ **someEncrypted**<`T`\>(`...args`): `number`

Given a profile object's properties, returns the number
of properties that are encryted.

#### Type parameters

| Name | Type |
| :------ | :------ |
| `T` | extends `object` |

#### Parameters

| Name | Type |
| :------ | :------ |
| `...args` | [obj: T] |

#### Returns

`number`

___

### sortSchemaProperties

▸ **sortSchemaProperties**(`properties`): `Section`[]

Schema properties are an object, so they need to be converted into an
array, grouped by the group tag, and then sorted based on the `priority`
attribute within their group.

#### Parameters

| Name | Type |
| :------ | :------ |
| `properties` | `Record`<`string`, `SchemaField`\> |

#### Returns

`Section`[]

___

### toCognitoAttributes

▸ **toCognitoAttributes**(`userDoc`): `Object`

Given a `UserDoc` from the maxcryptor, this returns an object
which you can provide to `Auth.updateUserAttributes()`. It is
an object of stringified Json.

#### Parameters

| Name | Type |
| :------ | :------ |
| `userDoc` | `UserDoc` |

#### Returns

`Object`