1.2.2 • Published 4 years ago

@selfkey/node-lib v1.2.2

Weekly downloads
75
License
GPL-3.0
Repository
github
Last release
4 years ago

@selfkey/node-lib

Selfkey sdk for third party integrations written in Node.js

NPM CircleCI

Contents

Install

Requires Node version 10 or above

npm install --save @selfkey/node-lib

Usage

const sk = require('@selfkey/node-lib');

or ES6 syntax

import sk from '@selfkey/node-lib';

API

Modules

auth/generate-access-token


auth/generate-access-token~generateAccessToken(did, algorithm, secret, [expiresIn])Promise.<string>

Generate access token

Kind: inner method of auth/generate-access-token
Returns: Promise.<string> - jwtToken

ParamTypeDefault
didstring
algorithmstring
secretstring
expiresInstring"'1h'"

Example

await sk.auth.generateAccessToken(did, 'rsa', 'secret')

auth/generate-challenge-token


auth/generate-challenge-token~generateChallengeToken(did, algorithm, secret, [expiresIn])Promise.<string>

Generate challenge token

Kind: inner method of auth/generate-challenge-token
Returns: Promise.<string> - jwtToken

ParamTypeDefault
didstring
algorithmstring
secretstring
expiresInstring"'30m'"

Example

await sk.auth.generateChallengeToken(did, 'rsa', 'secret')

auth/generate-nonce


auth/generate-nonce~generateNonce([length])Promise.<string>

Generates base64 encoded random string

Kind: inner method of auth/generate-nonce
Returns: Promise.<string> - nonce

ParamTypeDefault
lengthnumber64

Example

await sk.auth.generateNonce();

auth/validate-access-token


auth/validate-access-token~validateAccessToken(token, algorithm, key)Promise.<object>

Validates access token

Kind: inner method of auth/validate-access-token
Returns: Promise.<object> - decodedToken
Throws:

  • If token is invalid
  • if subject is not did
  • if token type is not access
ParamType
tokenstring
algorithmstring
keystring | Buffer

Example

await sk.auth.validateAccessToken(token, 'hmac', 'secret');

auth/validate-challenge-token


auth/validate-challenge-token~validateChallengeToken(token, algorithm, key)Promise.<object>

Validates challenge token

Kind: inner method of auth/validate-challenge-token
Returns: Promise.<object> - decodedToken
Throws:

  • If token is invalid
  • if subject is not did
  • if token type is not challenge
ParamType
tokenstring
algorithmstring
keystring | Buffer

Example

await sk.auth.validateChallengeToken(token, 'hmac', 'secret');

auth/verify-challenge-signature


auth/verify-challenge-signature~verifyChallengeSignature(nonce, signature, did)Promise.<boolean>

Validates challenge Signature

Kind: inner method of auth/verify-challenge-signature
Returns: Promise.<boolean> - is valid signature
Throws:

  • key not found in resolved did document
  • if no registered verifier for that key type
ParamType
noncestring
signatureobject
didstring

Example

await sk.auth.verifyChallengeSignature(nonce, signature, did);

did/parse


did/parse~parse(did)object

Parses did string to components

Kind: inner method of did/parse
Returns: object - parsedDid
Throws:

  • if invalid did is provided
ParamType
didstring

Example

sk.did.parse('did:selfkey:0xdsdasddasdsa...');

did/resolver


did/resolver~resolvers : object

Kind: inner constant of did/resolver
Properties

NameTypeDescription
ethobjecteth did resolver
sekfkeyobjectselfkey did resolver

did/resolver~isSupported(did)boolean

Checks if a resolver exists for that particular did

Kind: inner method of did/resolver
Returns: boolean - isSuppored

ParamType
didstring

Example

sk.did.isSupported('did:selfkey:0xdsdasddasdsa...'); // true
sk.did.isSupported('did:eth:0xdsdasddasdsa...'); // true
sk.did.isSupported('did:unknown:0xdsdasddasdsa...'); // false

did/resolver~resolve(did)object

Resolves did document

Kind: inner method of did/resolver
Returns: object - didDocument

ParamType
didstring

Example

await sk.did.resolve('did:selfkey:0xdsdasddasdsa...');

did/resolver~registerMethodResolver(method, resolver)

Register custom resolver for a did method

Kind: inner method of did/resolver

ParamType
methodstring
resolverobject

Example

sk.did.register('new-method', resolver);

identity/attribute-manager


identity/attribute-manager.AttributeManager

Kind: static class of identity/attribute-manager


new exports.AttributeManager()

Creates an instance of AttributeManager.


attributeManager.addRepository(repository)

Adds a new repository

Kind: instance method of AttributeManager

ParamType
repositoryidentity.Repository

attributeManager.removeRepository(repository)

Remove a repository

Kind: instance method of AttributeManager

ParamType
repositoryidentity.Repository

attributeManager.findRepositoryForAttribute(attr)identity.Repository | null

Finds a repository for a given attribute

Kind: instance method of AttributeManager

ParamType
attrobject | string

attributeManager.zipAttributesWithRequirements(attributes, [requirements])Array

Given an array of attributes and requirements, tries to much between them

Kind: instance method of AttributeManager

ParamTypeDefault
attributesArray
requirementsArray[]

attributeManager.validateOneAttribute(attr, requirement)object

Given an attribute and requirement validates the attribute

Kind: instance method of AttributeManager

ParamType
attrobject
requirementobject

attributeManager.validateAttributes(attributes, requirements)object

Given a list of attribute and requirements, validates all attributes

Kind: instance method of AttributeManager

ParamType
attributesArray
requirementsArray

AttributeManager.createWithSelfkeyRepository(options)AttributeManager

Creates an AttributeManager and initializes it with selfkey repository

Kind: static method of AttributeManager

ParamType
optionsobject

identity/attribute-manager~AttributeManager

Attribute Manager, manages multiple repositories of attributes

Kind: inner class of identity/attribute-manager


identity/repository


identity/repository.Repository

Kind: static class of identity/repository


new exports.Repository([config])

Creates an instance of Repository.

ParamTypeDefault
configobject{}

repository.resolveAll()

Resolve all repository data

Kind: instance method of Repository


repository.resolveJsonSchema(schema, [config])object

Resolve one JSON schema

Kind: instance method of Repository

ParamTypeDefault
schemaobject | string
configobject{}

repository.resolveUiSchema(schema, [config])object

Resolve one ui schema

Kind: instance method of Repository

ParamTypeDefault
schemaobject | string
configobject{}

repository.getValidator()

Creates an Ajv validator for the repository data

Kind: instance method of Repository
Returns: Ajv instance


repository.validateData(schemaId, data)object

Given schemaId and data, validates the data based on relevant schema

Kind: instance method of Repository
Returns: object - {valid:boolean, errors: array}

ParamType
schemaIdstring
dataobject

Repository.createSelfkeyRepo([options])Repository

Creates a repository initialized with selfkey data

Kind: static method of Repository

ParamTypeDefault
optionsobject{}

Repository.fromConfig(config, [ui])Repository

Creates and preloads a Repository from a config object

Kind: static method of Repository

ParamTypeDefault
configobject
uibooleanfalse

Repository.fromSchemaId(schemaId, [ui])Repository

Creates and preloads a Repository based on attribute schema id

Kind: static method of Repository

ParamTypeDefault
schemaIdstring
uibooleanfalse

identity/repository~Repository

Repository Class allows to load identity attribute repository and validate schemas

Part of identity namespace

Kind: inner class of identity/repository


identity/utils


identity/utils~attributeMapBySchema(attributes)object

Map list of attributes to schema name

Kind: inner method of identity/utils
Returns: object - an object with attribute name as keys

ParamTypeDescription
attributesArrayarray of identity attributes

identity/utils~resolveAttributeFiles(all, fileProcessor)object

Given a attribute data object and a file processor, process all files in the data object

Kind: inner method of identity/utils
Returns: object - a new attribute data object with processed files

ParamTypeDescription
alldataor part of the attribute data object
fileProcessorfunction

identity/utils~denormalizeDocumentsSchema(typeSchema, value, documents, maxDepth)object

Given a attribute data object and an array of documents, insert the documents into the data object where they are referenced from

Kind: inner method of identity/utils

ParamTypeDescription
typeSchemaobjecta json schema object
valueobjectan attribute data object
documentsarrayan array of documents
maxDepthintegermax search depth in attribute data object

identity/utils~normalizeDocumentsSchema(typeSchema, value, documents, maxDepth)object

Given a attribute data object export all documents from the object to a separate array, leaving documnent references behind

Kind: inner method of identity/utils

ParamTypeDescription
typeSchemaobjecta json schema object
valueobjectan attribute data object
documentsarrayan array of documents
maxDepthintegermax search depth in attribute data object

identity/utils~schemaContainsFile(schema, maxDepth)boolean

Check if schema contains a file

Kind: inner method of identity/utils

ParamTypeDescription
schemaobjectjson schema object
maxDepthintegermaximum depth to search for in the object tree

identity/utils~fetchJson(url, options)Promise.<object>

Fetch json from remote server. Optionally specify max number of attempts to do on failure (3 by default)

Kind: inner method of identity/utils
Returns: Promise.<object> - json loaded from server

ParamType
urlstring
optionsobject

Example

async sk.identity.utils.fetchJson('http://platform.selfkey.org/schema/attribute/first-name.json', {maxAttempts: 10});

identity/utils~dereferenceSchema(schema, options)Promise.<object>

Given a scheme object, load all references from the schema And combine into one json schema object

Kind: inner method of identity/utils
Returns: Promise.<object> - dereferences json schema object

ParamType
schemaobject
optionsobject

jwt/constants


jwt/issue


jwt/issue~issueJWT(subject, requestedAlgorithm, secret, [expiresIn], additionalClaims)Promise.<string>

Issue a new JWT token

Kind: inner method of jwt/issue
Returns: Promise.<string> - jwt
Throws:

  • if unknown algorithm provided
  • if secret deemed as not secure enough
ParamTypeDefaultDescription
subjectstringsub claim
requestedAlgorithmstringsignature algorithm
secretstring | Buffersecret key for signature
expiresInstring"1h"longevity of the token
additionalClaimsobjectclaims to include in the token

Example

sk.jwt.issueJWT('simple-session', 'hmac', 'test');

jwt/parse


jwt/parse~parseJWT(token)object

Parse a JWT token

Kind: inner method of jwt/parse
Returns: object - decodedJwt

ParamTypeDescription
tokenstringjwt token

Example

sk.jwt.parseJWT(token);

jwt/validate


jwt/validate~validateJWT(token, requestedAlgorithm, key)Promise.<(object|null)>

Validate a JWT token

Kind: inner method of jwt/validate
Returns: Promise.<(object|null)> - decodedJwt
Throws:

  • if unknown algorithm provided
ParamTypeDescription
tokenstringjwt token
requestedAlgorithmstringalgorithm name
keystringthe key to validate the token against

Example

sk.jwt.validateJWT(token, 'hmac', key);

key/hmac


key/hmac~generateHMACKey([length], [encoding])Promise.<(string|Buffer)>

Generate a HMAC Key

Kind: inner method of key/hmac
Returns: Promise.<(string|Buffer)> - key

ParamTypeDefaultDescription
lengthnumber64key length in bytes
encodingstring"base64"the output encoding of the key

Example

sk.key.generateHMACKey();

key/hmac~generateHMACKey(secret, [encoding])

Calculate the bytes length of secret key

Kind: inner method of key/hmac
Returns: number

ParamTypeDefaultDescription
secretstring
encodingstring"base64"the input encoding of the secret

Example

sk.key.getSecretLength(secret);

key/rsa


key/rsa~generateRSAKeyPair([length])Promise.<object>

Generate a RSA Key Pair

Kind: inner method of key/rsa
Returns: Promise.<object> - keypair - contains publicKey adn privateKey

ParamTypeDefaultDescription
lengthnumber4096key length in bytes

Example

sk.key.generateRSAKeyPair();

key/validate-private-key


key/validate-private-key~checkSecretLength(key, algorithm)boolean

Checks if secret length is good enough

Kind: inner method of key/validate-private-key
Returns: boolean - - isKeyLongEnough

ParamType
keystring
algorithmstring

Example

sk.key.checkSecretLength();

kycc/get-user-data-for-token


kycc/get-user-data-for-token~getUserDataForToken(token, options)Promise.<KYCCUserObject>

Fetch user data via token

Kind: inner method of kycc/get-user-data-for-token
Returns: Promise.<KYCCUserObject> - user object
Throws:

  • if no instanceUrl in options
  • if no templateId in options
  • if invalid token
  • if invalid user for token
ParamTypeDescription
tokenstringjwt token
optionsGetUserDataForTokenOptions

Example

async sk.kycc.getUserDataForToken(token, options);

kycc/get-user-data-for-token~FileProcessor

File Processor

Kind: inner typedef of kycc/get-user-data-for-token
Properties

NameType
streamboolean
processfunction

Example

{ stream: false, process: (file, id) => file }

kycc/get-user-data-for-token~GetUserDataForTokenOptions

Options used in getUserDataForToken function

Kind: inner typedef of kycc/get-user-data-for-token
Properties

NameType
instanceUrlstring
templateIdstring
fileProcessorFileProcessor

kycc/get-user-data-for-token~KYCCUserObject

User Object

Kind: inner typedef of kycc/get-user-data-for-token
Properties

NameTypeDescription
idstringid of user in KYCC
attributesobjectmap from attribute id to attribute value

Example

{
	id: '5ddd5b1656fbcef0dd389637',
	attributes: {
		firstName: {
			id: '5d076f0a315423134405cbc4',
			label: 'First Name',
			required: true,
			schema: 'http://platform.selfkey.org/schema/attribute/first-name.json',
			valid: true,
			value: 'first-name'
		},
		lastName: {
			label: 'Last Name',
			id: '5d076f20315423f5db05cbc6',
			required: true,
			schema: 'http://platform.selfkey.org/schema/attribute/last-name.json',
			valid: true,
			value: 'last-name'
		},
		email: {
			id: '5d13577f72089544cb86cda7',
			label: 'Email Address',
			required: true,
			schema: 'http://platform.selfkey.org/schema/attribute/email.json',
			valid: true,
			value: 'test-4952@test.com'
		},
	}

kycc/kycc-integrations-client


kycc/kycc-integrations-client~listUsersFn(filters, fields)Promise.<Array.<KYCCUser>>

Kind: inner method of kycc/kycc-integrations-client
Returns: Promise.<Array.<KYCCUser>> - users

ParamType
filtersobject
fieldsArray.<string>

Example

const users = await kyccClient.users.list();

kycc/kycc-integrations-client~getUserFn(userId, fields)Promise.<KYCCUser>

Kind: inner method of kycc/kycc-integrations-client
Returns: Promise.<KYCCUser> - user

ParamType
userIdstring
fieldsArray.<string>

Example

const user = await kyccClient.users.get("asdasdasdas");

kycc/kycc-integrations-client~listApplicationsFn(filters, fields)Promise.<Array.<KYCCApplication>>

Kind: inner method of kycc/kycc-integrations-client
Returns: Promise.<Array.<KYCCApplication>> - applications

ParamType
filtersobject
fieldsArray.<string>

Example

const applications = await kyccClient.applications.list({templateId: 'sdasdasdsaa'}, ['managers', 'currentStatus']);

kycc/kycc-integrations-client~getApplicationFn(applicationID, fields)Promise.<KYCCApplication>

Kind: inner method of kycc/kycc-integrations-client
Returns: Promise.<KYCCApplication> - application

ParamType
applicationIDstring
fieldsArray.<string>

Example

const application = await kyccClient.applications.get("asdasdasdas");

kycc/kycc-integrations-client~changeApplicationStatusFn(applicationID, statusCode, note)Promise.<KYCCApplication>

Kind: inner method of kycc/kycc-integrations-client
Returns: Promise.<KYCCApplication> - updated application

ParamTypeDescription
applicationIDstring
statusCodeinteger
notestring(optional)

Example

const application = await kyccClient.applications.changeStatus("asdasdasdas", 8, 'testing status change');

kycc/kycc-integrations-client~invalidateApplicationAttributesFn(applicationID, attributes)Promise.<string>

Kind: inner method of kycc/kycc-integrations-client
Returns: Promise.<string> - OK/Error

ParamTypeDescription
applicationIDstring
attributesArray.<string>a list of attribute ids

Example

await kyccClient.applications.attributes.invalidate("asdasdasdas", ["sdasdasdsa", "dsadasdasdasd"]);

kycc/kycc-integrations-client~invalidateApplicationQuestionsFn(applicationID, questions)Promise.<string>

Kind: inner method of kycc/kycc-integrations-client
Returns: Promise.<string> - OK/Error

ParamTypeDescription
applicationIDstring
questionsArray.<string>a list of question ids

Example

await kyccClient.applications.questions.invalidate("asdasdasdas", ["sdasdasdsa", "dsadasdasdasd"]);

kycc/kycc-integrations-client~addApplicationQuestionFn(applicationID, question)Promise.<string>

Kind: inner method of kycc/kycc-integrations-client
Returns: Promise.<string> - Created/Error

ParamType
applicationIDstring
questionKYCCQuestion

Example

await kyccClient.applications.questions.add("asdasdasdas", {
 description: "test question",
 label: 'test',
 question: 'what would you say about test?'
 optional: false
});

kycc/kycc-integrations-client~addApplicationAttributeFn(applicationID, attribute)Promise.<string>

Kind: inner method of kycc/kycc-integrations-client
Returns: Promise.<string> - Created/Error

ParamType
applicationIDstring
attributeKYCCAttribute

Example

await kyccClient.applications.attributes.add("asdasdasdas", {
 description: "test attribute",
 label: 'test',
 schema: 'http://platform.selfkey.org/schema/attribute/fingerprint.json'
 optional: false
});

kycc/kycc-integrations-client~applicationAddAttachment(applicationId, attachmentType, attachment)Promise.<string>

Kind: inner method of kycc/kycc-integrations-client
Returns: Promise.<string> - Created/Error

ParamType
applicationIdstring
attachmentTypestring
attachmentDocument

Example

await kyccClient.applications.attachments.add("sdasdasda", "credential", {
  buffer: Buffer.from('text file value', 'utf8'),
  mimeType: 'text/plain',
  filename: 'credential.txt'
});

kycc/kycc-integrations-client~updateApplicationFn(applicationID, update)Promise.<KYCCApplication>

Kind: inner method of kycc/kycc-integrations-client
Returns: Promise.<KYCCApplication> - updated application

ParamTypeDescription
applicationIDstring
updateobjectapplication update object

Example

await kyccClient.applications.update("asdasdasdas", {
 attributes: {
		"sdasdasdsa": { value: 'updated value' }
	}
});

kycc/kycc-integrations-client~getFileFn(fileId, options)Promise.<KYCCApplicationFile>

Kind: inner method of kycc/kycc-integrations-client
Returns: Promise.<KYCCApplicationFile> - file contents

ParamType
fileIdstring
optionsobject

Example

await kyccClient.files.get("asdasdasdas");

kycc/kycc-integrations-client~createClient(options)KYCCIntegrationsApiClient

Create KYC-Chain integrations api client

Kind: inner method of kycc/kycc-integrations-client

ParamType
optionsKYCCIntegrationsApiOptions

Example

const kyccClient = async sk.kycc.createKYCCIntegrationsClient(options);

kycc/kycc-integrations-client~KYCCQuestion

Kind: inner typedef of kycc/kycc-integrations-client
Properties

NameTypeDescription
descriptionstring
labelstring
questionstring
optionalboolean
optionsArray.<string>for select
typestringone of: input, checkbox, select, date

kycc/kycc-integrations-client~KYCCAttribute

Kind: inner typedef of kycc/kycc-integrations-client
Properties

NameTypeDescription
descriptionstring
labelstring
optionalboolean
schemastringjson schema id, one of https://platform.selfkey.org/repository.json

kycc/kycc-integrations-client~Document

Kind: inner typedef of kycc/kycc-integrations-client
Properties

NameType
bufferbinary
mimeTypestring
filenamestring

kycc/kycc-integrations-client~KYCCApplication

KYC-Chain application object

Kind: inner typedef of kycc/kycc-integrations-client


kycc/kycc-integrations-client~KYCCIntegrationsApiClientArray.<KYCCApplication>

KYC-Chain integrations api client

Kind: inner typedef of kycc/kycc-integrations-client
Properties

NameType
applications.listlistApplicationsFn
applications.getgetApplicationFn
applications.updateupdateApplicationFn
applications.changeStatuschangeApplicationStatusFn
applications.attributes.addaddApplicationAttributeFn
applications.attributes.invalidateinvalidateApplicationAttributesFn
applications.questions.addaddApplicationQuestionFn
applications.questions.invalidateinvalidateApplicationQuestionsFn
files.getgetFileFn

Example

const applicationId = "some application id";
const application = await kyccClient.applications.get(applicationId);
await kyccClient.applications.changeStatus(applicationId, kyccClient.statuses.APPROVED);

kycc/kycc-integrations-client~KYCCIntegrationsApiOptions : Object

Options used in createKYCCIntegrationsClient function

Kind: inner typedef of kycc/kycc-integrations-client
Properties

NameType
instanceUrlstring
apiKeystring

Examples

License

The GPL-3.0 License

Copyright (c) 2018 SelfKey Foundation https://selfkey.org/