dashmachine-auth-request v0.5.0
dashmachine-auth-request
A Library to Support Auth Requests fos Dash Platform Web Dapps.
Usage
Overview
This is an experimental project to explore methods of achieving a login flow with the Dash Platform.
The current specification can be found here.
This library contains the impementation of the server-side component. The client side component is the Dash Chrome Wallet.
Installation
Install as an npm package
npm i dashmachine-auth-requestSet Options
Sample options module
exports.options = {
connection: {
apps: {
loginContract: {
contractId: '9GHRxvyYDmWz7pBKRjPnxjsJbbgKLngtejWWp3kEY1vB',
},
dpnsContract: {
contractId: '295xRRRMGYyAruG39XdAibaU9jMAzxhknkkAxFE7uVkW',
},
},
network: 'testnet',
seeds: { service: '34.215.175.142:3000' },
},
polling: {
responsePollingTimeout: 30000,
responsePollingFrequency: 5000,
reponsePollingDelay: 3000,
},
};Usage
See the Examples below for possible usage.
Please note this library and documentation is experimental and in the early stages of development so should not be used in a production environment
Development
The following sections are only of interest if you wish to develop this project.
Clone this repo to a suitable location and switch into the project directory
git clone https://github.com/cloudwheels/dapp-auth-demo && cd dapp-auth-demoIt is recommended to install the npm nodemon package globally
npm i -g nodemonThe project can then be started in development mode using the following npm script:
npm run developTests
Tests are configured using Jest and Supertest. The following scripts are available to run different sections of tests, optionally in watch mode:
npm testSingle run of all tests
npm test:watchRuns all tests in watch mode
npm test-unit:watchRuns only unit tests in watch mode
npm test-routes:watchRuns only route tests (using supertest) in watch mode
npm test-services:watchRuns only route services in watch mode
Generated Documentation (experimental)
The following is automatically generated from jsdoc annotaions in the code using the documentaion.js npm package.
You will need to install the documentation package globally:
npm i -g documentationThe run the npm scripts to generate the docs
docs-readme:lib
docs-readme:modelsLibrary
Table of Contents
- AuthRequest
- findEnduser
- findVendor
- create
- submit
- mockReponse
- findResponses
- verify
- vendor
- enduser
- requestDoc
- responseDocType
- userResponses
- temp_timestamp
- entropy
- test_enduserPrivateKey
- test_enduserMnemonic
- DashAccount
- mnemonic
- DashConnection
- connect
- disconnect
- network
- mnemonic
- apps
- options
- client
- DashUser
- id
- name
- identityId
- identity
- publicKey
- privateKey
- find
- DashUser#toJSON
- DPNSDocument
- AuthRequestDocument
- DataDocument
- submit
- dataContractId
- id
- ownerId
- data
- find
- waitFor
- AuthResponseDocument
AuthRequest
AuthRequest class - A request for authorisation
Examples
Note: the libarary has been updated so that the global connection object is no loger automatically connected & disconnected for each method. You must call the (undocumented) connect() and disconnect() methods before (and after) the other calls.
const AuthRequest = require('./lib/auth-request');
const Options = require('./options');
(async () => {
try {
const req = new AuthRequest(
1,
'bob',
'1234',
'alice',
'uniform analyst paper father soldier toe lesson fetch exhaust jazz swim response',
'Web dApp Sample',
Options.options,
'Tweets are greets',
);
req.vendor = {
name: 'alice',
id: 'Aobc5KKaA4ZqzP7unc6WawQXQEK2S3y6EwrmvJLLn1ui',
identityId: 'CheZBPQHztvLNqN67i4KxcTU1XmDz7qG85X1XeJbc7K5',
identity: {
id: 'CheZBPQHztvLNqN67i4KxcTU1XmDz7qG85X1XeJbc7K5',
publicKeys: [
{
id: 0,
type: 0,
data: 'A0/qSE6tis4l6BtQlTXB2PHW+WV+Iy0rpF5hAvX8hDRz',
isEnabled: true,
},
],
balance: 9686447,
},
publicKey: 'A0/qSE6tis4l6BtQlTXB2PHW+WV+Iy0rpF5hAvX8hDRz',
privateKey:
'40148175614f062fb0b4e5c519be7b6f57b872ebb55ea719376322fd12547bff',
};
let createdDoc,
submittedDoc,
mockResponse,
foundResponses,
verifiedRequest;
try {
createdDoc = await req.create();
console.log(`createdDoc:${JSON.stringify(createdDoc)}`);
} catch (e) {
console.log(`createdDoc ERROR:${e}`);
}
if (createdDoc.success) {
try {
submittedDoc = await req.submit();
console.log(`submittedDoc:${JSON.stringify(submittedDoc)}`);
} catch (e) {
console.log(`submittedDoc ERROR:${e}`);
}
}
if (submittedDoc.success) {
try {
req.test_enduserMnemonic =
'liar fee island situate deal exotic flat direct save bag fiscal news';
req.test_enduserPrivateKey =
'219c8a8f9376750cee9f06e0409718f2a1b88df4acc61bf9ed9cf252c8602768';
mockResponse = await req.mockReponse();
console.log(`mockResponse:${JSON.stringify(mockResponse)}`);
} catch (e) {
console.log(`mockResponse ERROR:${e}`);
}
}
if (mockResponse.success) {
try {
foundResponses = await req.findResponses();
console.log(
`foundResponses:${JSON.stringify(foundResponses)}`,
);
} catch (e) {
console.log(`foundResponses ERROR:${e}`);
}
}
if (foundResponses.success) {
try {
verifiedRequest = await req.verify();
console.log(
`verifiedRequest:${JSON.stringify(verifiedRequest)}`,
);
} catch (e) {
console.log(`verifiedRequest ERROR:${e}`);
}
}
} catch (e) {
console.log(`errors: ${e}`); ////
}
})();findEnduser
if this._enduser==null looks up user details from the network using the supplied connection details //
Returns Object this._enduser
findVendor
if this.vendor==null looks up user details from the network using the supplied connection details
Returns Object this._vendor
create
creates a request document of the required type if the username, pin and other options are valid ////
Returns Object the prepared request document
submit
Submits the document set as the value of this._requestDoc returns this._submittedRequestDoc if successful
Returns any Promise<{ success: boolean; data: any; error?: undefined; message?: undefined; } | { error: boolean; message: any; success?: undefined; data?: undefined; }>
mockReponse
Mock Reponse with known user private keys
findResponses
poll for responses matching criteria
Returns Object this._enduser
verify
Verifies all found responses to deternine if loginis successful
vendor
Parameters
newVendorObject
enduser
Parameters
newEndusernewVendorObject
requestDoc
Parameters
newRequestDocObject
responseDocType
Parameters
newResponseDocTypestring
userResponses
Parameters
temp_timestamp
Parameters
newTemp_timestampstring
entropy
Parameters
newEntropystring
test_enduserPrivateKey
Parameters
newTest_enduserPrivateKeystring
test_enduserMnemonic
Parameters
newTest_enduserMnemonicstring
DashAccount
DashAccount class - represents a Dash Platform Account
Properties
mnemonicstring The account mnemonic
mnemonic
Parameters
newMnemonicstring
DashConnection
DashConnection class - represents a connection to Dash Platform
Properties
networkstring Network to connect to i.e. 'testet' (default), mainnetmnemonicstring Account mnemonic to use for the connectionappsObject named app identitiesseedsObject additonal options, overrides other paramatersclientObject the connection instance client
connect
Intialises connection
disconnect
Closes and disconnect the connection
network
Parameters
newNetworknewNamestring
mnemonic
Parameters
newMnemonicstring
apps
Parameters
newAppsObject
options
Parameters
newSeedsObject
client
Parameters
newClientany
DashUser
DashUser class - represents a registered Dash Platform Username
Properties
idstring Unique id fopr the user record - the id of the DPNS document which registered the namenamestring The registered usernameidentityIdstring identityId associated with the usernameidentityObject full identity object of the identityIdpublicKeystring private Key Associated wwith the user identityprivateKeystring private Key Associated wwith the user identity
id
Parameters
newIdstring
name
Parameters
newNamestring
identityId
Parameters
newIdentityIdstring
identity
Parameters
newIdentitynewIdentityIdObject
publicKey
Parameters
newPublicKeystring
privateKey
Parameters
newPrivateKeystring
find
Finds the registered username on the network
Parameters
nameToFindconnection
DashUser#toJSON
Returns the DashUser instance in JSON format
Returns JSON
DPNSDocument
Extends DataDocument
DPNSDocument class - represents a anme registraion documents from Dash Platform Name Service
AuthRequestDocument
Extends DataDocument
AuthRequestDocument class - represents login documents sumitted to or retrieved from Dash Platform
DataDocument
DataDocument class - represents data docuemnts sumitted to or retrieved from Dash Platform
Properties
dataContractIdstring dataContractId the document is validated againstownerIdstring identityId of the owner / submitter of the documentdataJSON actual data of the document represented as JSONsignaturestring the signature on the document
submit
submits the document instance using the passed in connection
Parameters
connectionA DashJS client containing the account and keys for signing the doc
dataContractId
Parameters
newContractIdstring
id
Parameters
newIdObject
ownerId
Parameters
newOwnerIdObject
data
Parameters
newDataObject
find
finds one of more documents based on suplied query params
Parameters
connectionstring A DashJS connection, with options set for the locator of the docs to be retrievedlocatorstring The document namequeryobject Object containing array of query parameters
Returns Array array of found docuemnts
waitFor
Calls find() over specified period at specifed frequency until result tis returned
Parameters
connectionstring A DashJS connection, with options set for the locator of the docs to be retrievedlocatorstring The document namequeryObject Object containing array of query parameterstimeoutnumber Number of millseconds until rejecting as timed outfrequencynumber Frequency of calls to find() in millisenconds
Returns Promise<Object> promise for JSON Object {success:true, data:array of found docuemnts} if resolved {error: true, message:error message} if rejected
AuthResponseDocument
Extends DataDocument
AuthResponseDocument class - represents auth response documents sumitted to or retrieved from Dash Platform
Models
Table of Contents
- DashAccount
- mnemonic
- DashUser
- id
- name
- identityId
- identity
- privateKey
- find
- DashUser#toJSON
- DataDocument
- submit
- dataContractId
- id
- ownerId
- data
- find
- waitFor
- DPNSDocument
- LoginDocument
- LoginResponseDocument
- Tweet
- username
- message
- date
DashAccount
DashAccount class - represents a Dash Platform Account
Properties
mnemonicstring The account mnemonic
mnemonic
Parameters
newMnemonicstring
DashUser
DashUser class - represents a registered Dash Platform Username
Properties
idstring Unique id fopr the user record - the id of the DPNS document which registered the namenamestring The registered usernameidentityIdstring identityId associated with the usernameidentityObject full identity object of the identityIdprivateKeystring private Key Associated wwith the user identity
id
Parameters
newIdstring
name
Parameters
newNamestring
identityId
Parameters
newIdentityIdstring
identity
Parameters
newIdentitynewIdentityIdObject
privateKey
Parameters
newPrivateKeystring
find
Finds the registered username on the network
Parameters
nameToFindconnection
DashUser#toJSON
Returns the DashUser instance in JSON format
Returns JSON
DataDocument
DataDocument class - represents data docuemnts sumitted to or retrieved from Dash Platform
Properties
dataContractIdstring dataContractId the document is validated againstownerIdstring identityId of the owner / submitter of the documentdataJSON actual data of the document represented as JSONsignaturestring the signature on the document
submit
submits the document instance using the passed in connection
Parameters
connectionA DashJS client containing the account and keys for signing the doc
dataContractId
Parameters
newContractIdstring
id
Parameters
newIdObject
ownerId
Parameters
newOwnerIdObject
data
Parameters
newDataObject
find
finds one of more documents based on suplied query params
Parameters
connectionstring A DashJS connection, with options set for the locator of the docs to be retrievedlocatorstring The document namequeryobject Object containing array of query parameters
Returns Array array of found docuemnts
waitFor
Calls find() over specified period at specifed frequency until result tis returned
Parameters
connectionstring A DashJS connection, with options set for the locator of the docs to be retrievedlocatorstring The document namequeryObject Object containing array of query parameterstimeoutnumber Number of millseconds until rejecting as timed outfrequencynumber Frequency of calls to find() in millisenconds
Returns Promise<Object> promise for JSON Object {success:true, data:array of found docuemnts} if resolved {error: true, message:error message} if rejected
DPNSDocument
Extends DataDocument
DPNSDocument class - represents a anme registraion documents from Dash Platform Name Service
LoginDocument
Extends DataDocument
LoginDocument class - represents login documents sumitted to or retrieved from Dash Platform
LoginResponseDocument
Extends DataDocument
LoginResponseDocument class - represents login documents sumitted to or retrieved from Dash Platform
Tweet
Tweet class - represents a user tweet
Properties
username
Parameters
newUsernamestring
message
Parameters
newMessagestring
date
Parameters
newDatestring
Services
Table of Contents
DashConnection
DashConnection class - represents a connection to Dash Platform
Properties
networkstring Network to connect to i.e. 'tesnet' (default), livenetaccountObject An instance of the DashAccount class containing mnemonic etc to use for the connectionappsObject named app identitiesoptionsObject additonal options, overrides other paramatersclientObject the connection instance client
connect
Intialises connection
disconnect
Closes and disconnect the connection
network
Parameters
newNetworknewNamestring
account
Parameters
newAccountObject
apps
Parameters
newAppsObject
options
Parameters
newOptionsObject
client
Parameters
newClientany