@maidsafe/safe-node-app

0.8.0

External API

The externally exposed API

initializeApp

src/index.js

The main entry point to create a new SAFEApp

initializeApp
Parameters
appInfo (AppInfo)
networkStateCallBack (Function = null) callback function to receive network state updates
options (InitOptions?) initialisation options
Returns
Promise<SAFEApp>: promise to a SAFEApp instance
Example
// Usage Example
const safe = require('@maidsafe/safe-node-app');

// starting initialisation
let prms = safe.initializeApp({
                     id: "net.maidsafe.example",
                     name: 'Example SAFE App',
                     vendor: 'MaidSafe.net Ltd'
                    });
// we want read & insert access permissions for `_pictures` and
// read access to `_videos` container:
const containers = { '_videos': ['Read'], '_pictures' : ['Read', 'Insert']}
prms.then(app => app.auth.genAuthUri(containers)
                   .then(uri => app.auth.openUri(uri))
       // now we either quit the programm
       // or wait for an authorisation URI
       )

fromAuthURI

src/index.js

If you have received a response URI (which you are allowed to store securely), you can directly get an authenticated or non-authenticated connection by using this helper function. Just provide said URI as the second value.

fromAuthURI
Parameters
appInfo (AppInfo) the app info
authUri (String) the URI coming back from the Authenticator
networkStateCallBack (Function = null) optional callback function to receive network state updates
options (InitOptions?) initialisation options
Returns
Promise<SAFEApp>: promise to a SAFEApp instance
AppInfo

Type: Object

Parameters
id (String) unique identifier for the app (e.g. 'net.maidsafe.examples.mail-app')
name (String) human readable name of the app (e.g. "Mail App")
vendor (String) human readable name of the vendor (e.g. "MaidSafe Ltd.")
scope (String?) an optional scope of this instance
customExecPath (String?) an optional customised execution path to use when registering the URI with the system.

InitOptions

src/index.js
InitOptions

Type: Object

Parameters
registerScheme (Boolean?) to register auth scheme with the OS. Defaults to true
joinSchemes (Array?) to additionally register custom protocol schemes
log (Boolean?) to enable or disable back end logging. Defaults to true
libPath (String?) path to the folder where the native libs can be found. Defaults to current folder path.
configPath (String?) set additional search path for the config files. E.g. log.toml and crust.config files will be also searched not only in the same folder where the native library is, but also in this additional search path.

CONSTANTS

src/consts.js
CONSTANTS

Type: Object

Parameters
NFS_FILE_MODE_OVERWRITE (Number) NFS File open in overwrite mode. When used as the openMode parameter for nfs.open(<fileName>, <openMode>) the entire content of the file will be replaced when writing data to it.
NFS_FILE_MODE_APPEND (Number) NFS File open in append mode. When used as the openMode param for nfs.open(<fileName>, <openMode>) any new content written to the file will be appended to the end without modifying existing data.
NFS_FILE_MODE_READ (Number) NFS File open in read-only mode. When used as the openMode param for nfs.open(<fileName>, <openMode>) only the read operation is allowed.
NFS_FILE_START (Number) Read the file from the beginning. When used as the position param for the NFS file.read(<position>, <length>) function, the file will be read from the beginning.
NFS_FILE_END (Number) Read until the end of a file. When used as the length param for the NFS file.read(<position>, <length>) function, the file will be read from the position provided until the end of its content. E.g. if NFS_FILE_START and NFS_FILE_END are passed in as the position and length parameters respectively, then the whole content of the file will be read.
USER_ANYONE (Number) Any user. When used as the signkey param in any of the MutableData functions to manipulate user permissions, like getUserPermissions , setUserPermissions , delUserPermissions , etc., this will associate the permissions operation to any user rather than to a particular sign key. E.g. if this constant is used as the signkey param of the setUserPermissions(<signKey>, <permissionSet>, <version>) function, the permissions in the permissionSet provided will be granted to anyone rather to a specific user's/aplication's sign key.
MD_METADATA_KEY (String) MutableData's entry key where its metadata is stored. The MutableData's metadata can be set either when invoking the quickSetup function or by invking the setMetadata function. The metadata is stored as an encoded entry in the MutableData which key is MD_METADATA_KEY , thus this constant can be used to realise which of the entries is not application's data but the MutableData's metadata instead. The metadata is particularly used by the Authenticator when another application has requested mutation permissions on a MutableData, displaying this information to the user, so the user can make a better decision to either allow or deny such a request based on it.
MD_ENTRIES_EMPTY (Number) Represents an empty set of MutableData's entries. This can be used when invoking the put function of the MutableData API to signal that it should be committed to the network with an empty set of entries.
MD_PERMISSION_EMPTY (Number) Represents an empty set of MutableData's permissions. This can be used when invoking the put function of the MutableData API to signal that it should be committed to the network with an empty set of permissions.

App Interface

the App and the API it exposes

SAFEApp

src/app.js

Holds one sessions with the network and is the primary interface to interact with the network. As such it also provides all API-Providers connected through this session.

new SAFEApp(appInfo: any, networkStateCallBack: any, options: any)

Extends EventEmitter

Parameters
appInfo (any)
networkStateCallBack (any)
options (any)
Static Members
fromAuthUri(appInfo, authUri, networkStateCallBack, options, initialisation)
Instance Members
auth
crypto
cipherOpt
immutableData
mutableData
webFetch(url, options)
connection
networkState
isNetStateInit()
isNetStateConnected()
isNetStateDisconnected()
appInfo
logPath(logFilename)
getAccountInfo()
getOwnContainerName()
reconnect()
clearObjectCache()
isMockBuild()

CryptoInterface

src/api/crypto.js

Encryption functionality for the app

Access it through your {SAFEApp} instance under app.crypto

new CryptoInterface(app: any)
Parameters
app (any)
Instance Members
sha3Hash(data)
getAppPubSignKey()
getAppPubEncKey()
generateEncKeyPair()
generateSignKeyPair()
generateEncKeyPairFromRaw(rawPublicKey, rawSecretkey)
generateSignKeyPairFromRaw(rawPublicKey, rawSecretkey)
pubSignKeyFromRaw(raw)
secSignKeyFromRaw(raw)
pubEncKeyFromRaw(raw)
secEncKeyFromRaw(raw)
generateNonce()

AuthInterface

src/api/auth.js

The AuthInterface contains all authentication related functionality with the network. Like creating an authenticated or unauthenticated connection or create messages for the IPC authentitcation protocol.

Access your instance through ypur {SAFEApp} instance under .auth.

new AuthInterface(app: any)
Parameters
app (any)
Instance Members
registered
genAuthUri(permissions, opts?)
genShareMDataUri(permissions)
genConnUri()
openUri(uri)
genContainerAuthUri(containers)
refreshContainersPermissions()
getContainersPermissions()
readGrantedPermissions(uri)
getOwnContainer()
canAccessContainer(name, permissions)
getContainer(name)
loginFromURI(uri)
loginForTest(access, opts)

CipherOptInterface

src/api/cipher_opt.js

Provide the Cipher Opt API

new CipherOptInterface(app: any)
Parameters
app (any)
Instance Members
newPlainText()
newSymmetric()
newAsymmetric(pubEncKey)

ImmutableDataInterface

src/api/immutable.js

Interact with Immutable Data of the Network through this Interface.

Access it through your {SAFEApp} instance under app.immutableData

new ImmutableDataInterface(app: any)
Parameters
app (any)
Instance Members
create()
fetch(address)

MutableDataInterface

src/api/mutable.js

Provide the MutableData API for the session.

Access via mutableData on your app Instance.

new MutableDataInterface(app: any)
Parameters
app (any)
Example
// using mutable Data
app.mutableData.newRandomPublic(15001)
  // set it up with starting data
  .then((mdata) => mdata.quickSetup({keyA: 'input value'})
   .then(() => mdata.getNameAndTag())) // return name and tag

// now read using name and tag
.then((ref) => app.mutableData.newPublic(ref.name, ref.tag)
  .then((mdata) => mdata.get('keyA').then((val) => {
    should(val.buf.toString()).equal('input value');
  })))
Instance Members
newRandomPrivate(typeTag)
newRandomPublic(typeTag)
newPrivate(name, typeTag, secKey, nonce)
newPublic(name, typeTag)
newPermissions()
newMutation()
newEntries()
fromSerial(serial)

Immutable

Holds the connection to read an existing ImmutableData

new Reader()

Extends helpers.NetworkObject

Instance Members
read(options?)
size()

Holds an Immutable Data Writer

new Writer()

Extends helpers.NetworkObject

Example
// write new data to the network
app.immutableData.create()
 .then((writer) => writer.write("some string\n")
   .then(() => writer.write("second string"))
   .then(() => app.cipherOpt.newPlainText())
   .then((cipher) => writer.close(cipher))
 ).then((address) => app.immutableData.fetch(address))
 .then((reader) => reader.read())
 .then((payload) => {
   console.log("Data read from ImmutableData: ", payload.toString());
 })
Instance Members
write(data)
close(cipherOpt)

Mutable

Holds the reference to a MutableData

new MutableData()

Extends h.NetworkObject

Instance Members
quickSetup(data, name, description)
setMetadata(name, description)
encryptKey(key)
encryptValue(value)
decrypt(value)
getNameAndTag()
getVersion()
get(key)
put(permissions, entries)
getEntries()
getKeys()
getValues()
getPermissions()
getUserPermissions(signKey)
delUserPermissions(signKey, version)
setUserPermissions(signKey, permissionSet, version)
applyEntriesMutation(mutations)
serialise()
getSerialisedSize()
emulateAs(eml)

Represent the Entries of a MutableData network object

new Entries()

Extends h.NetworkObject

Instance Members
len()
get(keyName)
forEach(fn)
insert(keyName, value)
mutate()

EntryMutationTransaction

src/api/mutable.js

Holds a mutations to be done to the entries within one transaction on the network.

You need this whenever you want to change the content of the entries.

new EntryMutationTransaction()

Extends h.NetworkObject

Example
// Mutate a range of Entries

app.mutableData.newPublic(somename, tagtype)
 .then((mData) => mData.getEntries()
  .then((entries) => entries.mutate()
    .then((m) => m.insert('key', 'value')
      // this is where all mutations are recorded
      .then(() => mData.applyEntriesMutation(m))
    )))
Instance Members
insert(keyName, value)
remove(keyName, version)
update(keyName, value, version)

Holds the permissions of a MutableData object

new Permissions()

Extends h.NetworkObject

Instance Members
len()
getPermissionSet(signKey)
insertPermissionSet(signKey, permissionSet)
listPermissionSets()

Emulations

Emulations and Abstractions on top of MData

NFS Emulation on top of an MData

new NFS(mData: any)
Parameters
mData (any)
Instance Members
create(content)
fetch(fileName)
insert(fileName, file)
update(fileName, file, version)
delete(fileName, version)
open(file, openMode)

A NFS-style File

Note: As this application layer, the network does not check any of the metadata provided.

new File(ref: any, connection: any, fileCtx: any)
Parameters
ref (any)
connection (any)
fileCtx (any)
Instance Members
dataMapName
created
modified
size()
read(position, len)
write(fileContent, content)
close()
version

Types

AccountInfo

src/app.js
AccountInfo

Type: Object

Parameters
mutations_done (Number) number of mutations performed with this account
mutations_available (Number) number of remaining mutations allowed for this account

Holds an asymmetric encryption keypair

new EncKeyPair(app: any, pub: any, secret: any)
Parameters
app (any)
pub (any)
secret (any)
Instance Members
pubEncKey
secEncKey
decryptSealed(cipher)

Holds the secret part of an encryption key

new SecEncKey()

Extends h.NetworkObject

Instance Members
getRaw()
decrypt(cipher, publicEncKey)
encrypt(data, recipientPubKey)

Holds the public part of an encryption key

new PubEncKey()

Extends h.NetworkObject

Instance Members
getRaw()
encryptSealed(str)
decrypt(cipher, secretEncKey)
encrypt(data, secretEncKey)

Holds a sign key pair

new SignKeyPair(app: any, pub: any, secret: any)
Parameters
app (any)
pub (any)
secret (any)
Instance Members
pubSignKey
secSignKey

Holds the secret part of a sign key

new SecSignKey()

Extends h.NetworkObject

Instance Members
getRaw()
sign(data)

Holds the public part of a sign key

new PubSignKey()

Extends h.NetworkObject

Instance Members
getRaw()
verify(data)

Holds the reference to a Cipher Options, either PlainText, Symmetric or Asymmetric

new CipherOpt()

Extends h.NetworkObject

NameAndTag

Type: Object

Parameters
name (Buffer) the XoR-name/address on the network
type_tag (Number) the type tag
ValueVersion

Type: Object

Parameters
buf (Buffer) the buffer with the value
version (Number) the version Holds the informatation of a value of a MutableData

Errors

ERR_NO_SUCH_DATA

src/error_const.js

Thrown natively when data not found on network.

ERR_NO_SUCH_DATA
Properties
code (number) : -103
msg (string)

ERR_NO_SUCH_ENTRY

src/error_const.js

Thrown natively when entry on found in MutableData.

ERR_NO_SUCH_ENTRY
Properties
code (number) : -106
msg (string)

ERR_FILE_NOT_FOUND

src/error_const.js

Thrown natively when NFS-style file not found.

ERR_FILE_NOT_FOUND
Properties
code (number) : -301
msg (string)

FAILED_TO_LOAD_LIB

src/error_const.js

Thrown when a native library fails to load and which library.

FAILED_TO_LOAD_LIB
Properties
code (number) : 1000
msg (function)

MALFORMED_APP_INFO

src/error_const.js

Informs when app info provided during initialisation is invalid.

MALFORMED_APP_INFO
Properties
code (number) : 1002
msg (string)

MISSING_PERMS_ARRAY

src/error_const.js

Argument should be an array object.

MISSING_PERMS_ARRAY
Properties
code (number) : 1003
msg (string)

INVALID_SHARE_MD_PERMISSION

src/error_const.js

Informs of a specific object in a share MData permissions array that is malformed.

INVALID_SHARE_MD_PERMISSION
Properties
code (number) : 1004
msg (function)

INVALID_PERMS_ARRAY

src/error_const.js

Thrown when share MD permissions is not an array.

INVALID_PERMS_ARRAY
Properties
code (number) : 1005
msg (string)

Please provide URL

MISSING_URL
Properties
code (number) : 1006
msg (string)

Please provide URL in string format.

INVALID_URL
Properties
code (number) : 1007
msg (string)

MISSING_AUTH_URI

src/error_const.js

Thrown when attempting to connect without authorisation URI.

MISSING_AUTH_URI
Properties
code (number) : 1008
msg (string)

MISSING_CONTAINER_STRING

src/error_const.js

Thrown when attempting to get a container without specifying name with a string.

MISSING_CONTAINER_STRING
Properties
code (number) : 1011
msg (string)

Thrown when functions unique to testing environment are attempted to be used.

NON_DEV
Properties
code (number) : 1012
msg (string)

MISSING_PUB_ENC_KEY

src/error_const.js

Thrown when public encryption key is not provided as necessary function argument.

MISSING_PUB_ENC_KEY
Properties
code (number) : 1013
msg (string)

MISSING_SEC_ENC_KEY

src/error_const.js

Thrown when secret encryption key is not provided as necessary function argument.

MISSING_SEC_ENC_KEY
Properties
code (number) : 1014
msg (function)

LOGGER_INIT_ERROR

src/error_const.js

Logger initialisation failed.

LOGGER_INIT_ERROR
Properties
code (number) : 1015
msg (function)

CONFIG_PATH_ERROR

src/error_const.js

Informs you when config search path has failed to set, with specific reason.

CONFIG_PATH_ERROR
Properties
code (number) : 1016
msg (function)

Custom name used to create public or private MutableData must be 32 bytes in length.

XOR_NAME
Properties
code (number) : 1017
msg (function)

Any string or buffer provided to private MutableData that is not 24 bytes in length will throw error.

NONCE
Properties
code (number) : 1018
msg (function)

Tag argument when creating private or public MutableData must be a number.

TYPE_TAG_NAN
Properties
code (number) : 1019
msg (string)

SETUP_INCOMPLETE

src/error_const.js

Informs that app is not yet connected to network.

SETUP_INCOMPLETE
Properties
code (number) : 1001
msg (string)

Thrown when invalid permission is requested on container.

INVALID_PERM
Properties
code (number) : 1010
msg (function)

Emulations are abstraction helpers on top of MData

Emulation

Type: NFS

WebFetchOptions

src/app.js
WebFetchOptions

Type: Object

Parameters
range (Object) range of bytes to be retrieved. The start attribute is expected to be the start offset, while the end attribute of the range object the end position (both inclusive) to be retrieved, e.g. with range: { start: 2, end: 3 } the 3rd and 4th bytes of data will be retrieved. If end is not specified, the bytes retrived will be from the start offset untill the end of the file. The ranges values are also used to populate the Content-Range and Content-Length headers in the response.

NON_AUTH_GRANTED_URI

src/error_const.js

Thrown when attempting extract granted access permissions from a URI which doesn't contain such information.

NON_AUTH_GRANTED_URI
Properties
code (number) : 1009
msg (string)