@maidsafe/safe-node-app

0.5.1

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('safe');

// starting initialisation
let prms = safe.initializeApp({
                     id: "net.maidsafe.example",
                     name: 'Example App',
                     vendor: 'MaidSafe Ltd.'
                    });
// we want read-append access to `_pictures` and
// read access to `_videos`:
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 a result url
       ))

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)
connection
networkState
isNetStateInit()
isNetStateConnected()
isNetStateDisconnected()
appInfo
logPath(logFilename)
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()
getOwnContainer()
canAccessContainer(name, permissions)
getContainer(name)
loginFromURI(uri)
loginForTest(access)

CipherOptInterface

src/api/cipher_opt.js

Provide the Cipher Opt API

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

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

Hold the connection to read an existing ImmutableData

new Reader()

Extends helpers.NetworkObject

Instance Members
read(options?)
size()

Holds a immutable Data Writer

new Writer()

Extends helpers.NetworkObject

Example
// write new data to the network
app.immutableData.create().then((writer)=> {
 return writer.write("some string\n")
  .then(() => writer.write("second string"))
  .then(() => writer.close())
  .then((address) => app.immutableData.fetch(address)
    .then((reader) => reader.read()
      .then( (payload) => {
        should(payload).equals("some string\nsecond string");
      })
    ))
})
Instance Members
write(string)
close(cipherOpt, the)
save()

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

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

Emulations are abstraction helpers on top of MData

Emulation

Type: NFS