Navigation

Utility Packages

Overview

For developer convenience, MongoDB Stitch functions have access to utility packages provided through various global variables.

The following global utility packages are available in all functions:

Variable Description
console Provides standard console methods that output to the function editor’s debug console as well as your application logs.
JSON

Provides methods that convert between string and object representations of standard JSON objects. This is a standard built-in object across most Javascript environments.

You can find full documentation for the JSON package on MDN.

EJSON Provides methods that convert between string and object representations of MongoDB Extended JSON objects.
BSON Provides methods that construct and manipulate BSON objects.
utils.crypto Provides methods that encrypt, decrypt, hash, and sign data using cryptographic algorithms such as AES, RSA, HMAC, sha256, and md5. These methods are useful when your Functions need to communicate with external HTTP services.

Utility Packages

console

console.log(arg...)

Logs information to the function editor debug console and your Stitch application’s logs. Accepts multiple arguments which are all included in the log output.

console.warn(arg...)

Logs a warning to the function editor debug console and your Stitch application’s logs. Accepts multiple arguments which are all included in the log output.

console.error(arg...)

Logs an error to the function editor debug console and your Stitch application’s logs. Accepts multiple arguments which are all included in the log output.

JSON

Includes methods that convert between string and object representations of standard JSON objects. This is a standard built-in object across most Javascript environments.

You can find full documentation for the JSON package on MDN.

JSON.parse(<json-string>)

Parses the provided string and attempts to convert it to a JavaScript object.

Parameter Type Description
<json-string> string A serialized string representation of a standard JSON object. Valid inputs include serialized object strings created by JSON.stringify() and EJSON.stringify().
Returns:A standard JSON object based on the provided JSON string.
JSON.stringify(<json-object>)

Serializes the provided JSON object to a string.

Parameter Type Description
<json-object> object A standard JSON object.
Returns:A string representation of the provided JavaScript object. The resulting Javascript object may contain BSON types.

EJSON

Includes methods that convert between string and object representations of MongoDB Extended JSON objects. EJSON is a superset of the JSON package.

EJSON.parse(<ejson-string>)

Parses the provided string and attempts to convert it to an EJSON object.

Parameter Type Description
<ejson-string> string A string representing serialized extended JSON.
Returns:A Javascript object representation of the provided EJSON string. The object may contain BSON types.
EJSON.stringify(<ejson-object>)

Serializes the provided EJSON object to a string.

Parameter Type Description
<ejson-object> document An EJSON object. The object may contain BSON types.
Returns:A string representation of the EJSON object.

BSON

BSON provides functions for constructing and manipulating BSON types.

Note

To avoid ambiguity with the $regex EJSON type, queries with the $regex operator must use a BSON.BSONRegExp.

Creating Explicit BSON types

The BSON global can be used to construct explicit BSON types. The following are the available BSON types in MongoDB Stitch:

Type Description Example
BSON.Binary A string of bytes. BSON.Binary.fromHex("a5f8c1", 0);
BSON.Code Embedded Javascript code. BSON.Code("var x = 123;");
BSON.DBPointer (Deprecated) A reference to another document. BSON.DBPointer("db.coll", BSON.ObjectId("5a14179d01236a9fc1086df6"));
BSON.DBRef A reference to another document. BSON.DBRef("db.coll", BSON.ObjectId("5a14179d01236a9fc1086df6"));
BSON.Decimal128 A 128 bit decimal. BSON.Decimal128.fromString("1.23");
BSON.Double A 64 bit double. BSON.Double(1.23);
BSON.Int32 A 32 bit signed integer. BSON.Int32(123);
BSON.Long A 64 bit signed integer. BSON.Long(0x00000000, 0x40000000);
BSON.MaxKey A value that compares higher than all other BSON values. BSON.MaxKey;
BSON.MinKey A value that compares lower than all other BSON values. BSON.MinKey;
BSON.ObjectId A 12 byte object ID. BSON.ObjectId("5a14179d01236a9fc1086df6");
BSON.BSONRegExp A regular expression. BSON.BSONRegExp("^test*", "i");
BSON.Symbol (Deprecated) A symbol. BSON.Symbol("symbol");
BSON.Timestamp Contains a 32 bit timestamp and 32 bit counter. For working with dates use Date. BSON.Timestamp(1511266261367, 0);

More information about BSON types can be found on BSON Types.

BSON.Binary

BSON.Binary has the following methods.

BSON.Binary.fromHex(hexString, subType)

Constructs a BSON.Binary from data represented as a hexadecimal string.

Parameter Type Description
hexString string A string of hexadecimal characters (0-9 and A-F). This must be byte aligned or an exception is thrown.
subType integer An integer in the range of 0-255. The value 0 represents generic binary. Other sub-types are documented on the BSON spec.
Returns:A BSON.Binary.
BSON.Binary.toHex()

Returns the BSON.Binary data represented as a hexadecimal string.

Returns:A string.
BSON.Binary.fromBase64(base64String, subType)

Constructs a BSON.Binary from data represented as a base64 string.

Parameter Type Description
base64String string A string of base64 encoded characters.
subType integer An integer in the range 0-255. The value 0 represents generic binary. Other sub-types are documented on the BSON spec.
Returns:A BSON.Binary.
BSON.Binary.toBase64()

Returns the BSON.Binary data represented as a base64 string.

Returns:A string.
BSON.Binary.text()

Returns a string representation of the data as UTF-8 encoded characters.

Returns:A string.
BSON.Decimal128
BSON.Decimal128.fromString(decimalString)

Constructs a BSON.Decimal128 from a string representation of a decimal number.

Parameter Type Description
decimalString string A string representing a decimal number. E.g. “123.45”.
Returns:A BSON.Decimal128.
BSON.Long

A BSON.Long is a 64 bit signed integer.

BSON.Long(low32, high32)

Constructs a BSON.Long from two 32 bit integers representing the low 32 bits and the high 32 bits.

Parameter Type Description
low32 integer Optional. Represents the low 32 bits of the BSON.Long.
high32 integer Optional. Represents the high 32 bits of the BSON.Long.
Returns:A BSON.Long. If no arguments are supplied the value returned is 0.

Examples

BSON can be used to return explicit BSON types.

exports = function() {
   return {
      a: BSON.Long(10),
      b: BSON.ObjectId("5a14179d01236a9fc1086df6"),
      c: BSON.Code("var x = 1"),
      d: new Date()
   };
};

utils.jwt

The jwt utility provides methods for working with JSON Web Tokens.

utils.jwt.encode(signingMethod, payload, secret)

Generates an encoded JSON Web Token string for the payload based on the specified signingMethod and secret.

Parameter Type Description
signingMethod String

The cryptographic algorithm to use when encoding the JWT. Stitch supports the following JWT signing methods:

Signing Method Description
"HS256" HMAC using SHA-256
"HS384" HMAC using SHA-384
"HS512" HMAC using SHA-512
"RS256" RSASSA-PKCS1-v1_5 using SHA-256
"RS384" RSASSA-PKCS1-v1_5 using SHA-384
"RS512" RSASSA-PKCS1-v1_5 using SHA-512
"ES256" ECDSA using P-256 and SHA-256
"ES384" ECDSA using P-384 and SHA-384
"ES512" ECDSA using P-512 and SHA-512
"PS256" RSASSA-PSS using SHA-256 and MGF1 with SHA-256
"PS384" RSASSA-PSS using SHA-384 and MGF1 with SHA-384
"PS512" RSASSA-PSS using SHA-512 and MGF1 with SHA-512
payload Object A JSON object that specifies the token’s claims and any additional related data.
secret String

A secret string that Stitch uses to sign the token. The value of the string depends on the signing method that you use:

Signing Methods Description
"HS256"
"HS384"
"HS512"
A random string.
"RS256"
"RS384"
"RS512"
An RSA-SHA private key in PKCS#8 format.
"PS256"
"PS384"
"PS512"
An RSA-PSS private key in PKCS#8 format.
"ES256"
"ES384"
"ES512"
An ECDSA private key in PKCS#8 format.
Returns:A JSON Web Token string encoded for the provided payload.

Example

Consider the following JWT claims object:

{
  "sub": "1234567890",
  "name": "Joe Example",
  "iat": 1565721223187
}

We can encode the claims object as a JWT string by calling utils.jwt.encode(). The following function encodes the JWT using the HS512 signing method and the secret "SuperSecret":

exports = function() {
  const signingMethod = "HS512";
  const payload = {
    "sub": "1234567890",
    "name": "Joe Example",
    "iat": 1565721223187
  };
  const secret = "SuperSecret";
  return utils.jwt.encode(signingMethod, payload, secret);
}

The function returns the following JWT string:

eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvZSBTY2htb2UiLCJpYXQiOjE1NjU3MjEyMjMxODd9.-QL15ldu2BYuJokNWT6YRiwZQIiIpvq6Kyv-C6qslNdNiUVxo8zqLJZ1iEkNf2yZKMIrQuMCtIC1tzd2H31AxA
utils.jwt.decode(jwtString, key)

Decodes the payload of the provided JSON Web Token string. The value of key must correspond to the secret value that was used to encode the JWT string.

Parameter Type Description
jwtString String A JSON Web Token string that encodes a set of claims signed with a secret value.
key String

A string that Stitch uses to verify the token signature. The value of the string depends on the signing method that you use:

Signing Methods Description
"HS256"
"HS384"
"HS512"
The random string that was used to sign the token.
"RS256"
"RS384"
"RS512"
The RSA-SHA public key that corresponds to the private key that was used to sign the token.
"PS256"
"PS384"
"PS512"
The RSA-PSS public key that corresponds to the private key that was used to sign the token.
"ES256"
"ES384"
"ES512"
The ECDSA public key that corresponds to the private key that was used to sign the token.
Returns:The decoded EJSON payload of the signed JWT.

Example

Consider the following signed JWT string:

eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvZSBTY2htb2UiLCJpYXQiOjE1NjU3MjEyMjMxODd9.-QL15ldu2BYuJokNWT6YRiwZQIiIpvq6Kyv-C6qslNdNiUVxo8zqLJZ1iEkNf2yZKMIrQuMCtIC1tzd2H31AxA

The JWT was signed using the HS512 signing method with the secret value "SuperSecret". We can decode the JWT’s claims object utils.jwt.decode(). The following function decodes the JWT string:

exports = function(jwtString) {
  const signingMethod = "HS512";
  const key = "SuperSecret";
  return utils.jwt.decode(jwtString, key);
}

The function returns the following EJSON representation of the JWT payload:

{
  "sub": "1234567890",
  "name": "Joe Example",
  "iat": { "$numberDouble": 1565721223187 }
}

utils.crypto

The crypto utility provides methods for working with cryptographic algorithms.

utils.crypto.encrypt(encryptionType, message, key)

Generates an encrypted text string from the provided text using the specified encryption method and key.

Parameter Type Description
encryptionType String

The type of encryption with which to encrypt the message. The following encryption types are supported:

message String The text string that you want to encrypt.
key String

A cryptographic key used to encrypt the text. The key you should use depends on the encryption method:

Encryption Type Encryption Key
AES A 16-byte, 24-byte, or 32-byte random string
Returns:A BSON Binary object that contains the text string encrypted with the specified encryption type and key.

Example

Assume that we have defined a Value named aesEncryptionKey that contains the following 32-byte AES encryption key:

"603082712271C525E087BD999A4E0738"

We can encrypt a message with this key using the following Stitch function:

exports = function(message) {
  const key = context.values.get("aesEncryptionKey");
  const encryptedMessage = utils.crypto.encrypt("aes", message, key);
  return encryptedMessage.toBase64();
}

If we use the function to encrypt the message "MongoDB is great!", it returns the following encrypted base64 string:

"WPBuIvJ6Bity43Uh822dW8QlVYVJaFUiDeUjlTiJXzptUuTYIKPlXekBQAJb"
utils.crypto.decrypt(encryptionType, encryptedMessage, key)

Decrypts the provided text string using the specified encryption type and key. If both the encryption type and key are the same as those used to encrypt, this returns the original, unencrypted text.

Parameter Type Description
encryptionType String

The type of encryption that was used to encrypt the provided text. The following encryption types are supported:

encryptedMessage BSON.Binary A BSON Binary that encodes the encrypted text string that you want to decrypt.
key String

A cryptographic key used to decrypt the text. The key you should use depends on the encryption type:

Encryption Type Encryption Key
AES A 16-byte, 24-byte, or 32-byte random string
Returns:A BSON Binary object that contains the decrypted message.

If the provided encrypted message was encrypted with the specified method and key, then the decrypted message is identical to the original message.

Example

Assume that we have defined a Value named aesEncryptionKey that contains the following 32-byte AES encryption key:

"603082712271C525E087BD999A4E0738"

We can decrypt a message that was encrypted with this key using the following Stitch function:

exports = function(encryptedMessage) {
  // The encrypted message must be a BSON.Binary
  if(typeof encryptedMessage === "string") {
    encryptedMessage = BSON.Binary.fromBase64(encryptedMessage)
  }
  const key = context.values.get("aesEncryptionKey");
  const decryptedMessage = utils.crypto.decrypt("aes", encryptedMessage, key);
  return decryptedMessage.text();
}

If we use the function to decrypt the encrypted message, it returns the original, unencrypted string:

"MongoDB is great!"
utils.crypto.sign(encryptionType, message, privateKey, signatureScheme)

Generates a cryptographically unique signature for a message using a private key. The signature can be verified with the corresponding public key to ensure that the signer has access to the private key and that the message content has not been altered since it was signed.

Parameter Type Description
encryptionType String

The type of encryption that was used to generate the private/public key pair. The following encryption types are supported:

message String The text string that you want to sign.
privateKey String

A private key generated with the specified encryption type.

Key Format

Not all RSA keys use the same format. Stitch can only sign messages with a private key that conforms to the standard PKCS#1 format. Private keys in this format have the header -----BEGIN RSA PRIVATE KEY-----.

You can use the following shell script to generate a valid RSA private/public key pair and save each key to its own text file:

# Generate an RSA SSH key pair
# Save the key to a file called `rsa_key` when prompted
ssh-keygen -t rsa -m PEM -b 2048 -C "2048-bit RSA Key"

# Private Key
cat rsa_key > rsa.private.txt
# Public Key
ssh-keygen -f rsa_key.pub -e -m pem > rsa.public.txt
signatureScheme String

Optional. Default: "pss"

The padding scheme that the signature should use. Stitch supports signing messages with the following schemes:

Returns:A BSON.Binary cryptographic signature for the message signed using the specified private key.

Example

Assume that we have defined a Value named rsaPrivateKey that contains the following RSA private key:

-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQDVsEjse2qO4v3p8RM/q8Rqzloc1lee34yoYuKZ2cemuUu8Jpc7
KFO1+aJpXdbSPZNhGLdANn8f2oMIZ1R9hgEJRn/Qm/YyC4RPTGg55nzHqSlziNZJ
JAyEUyU7kx5+Kb6ktgojhk8ocZRkorM8FEylkrKzgSrfay0PcWHPsKlmeQIDAQAB
AoGAHlVK1L7kLmpMbuP4voYMeLjYE9XdVEEZf2GiFwLSE3mkJY44033y/Bb2lgxr
DScOf675fFUAEK59ATlhxfu6s6rgx+g9qQQ+mL74YZWPqiZHBPjyMRaBalDVC4QF
YJ+DopFcB8hY2ElXnbK70ALmVYNjw3RdmC97h0YfOsQcWW0CQQD18aeuPNicVnse
Ku22vvhvQYlabaQh4xdkEIxz1TthZj48f61wZwEMipYqOAc5XEtDlNnxgeipv0yF
RHstUjwXAkEA3m0Br/U/vC9evuXppWbONana08KLgfELyd3Uw9jG7VKJZTBH5mS8
7CB68aEF8egrJpo8Ss8BkWrvCxYDb4Y77wJAUlbOMZozVtvpKidrIFR9Lho91uWA
Hsw9h4W20AzibXBig7SnJ0uE4WMAdS/+0yhgFkceVCmO8E2YW8Gaj4jJjwJASxtg
AHy+ItuUEL4uIW4Pn8tVW0BMP3qX0niXyfI/ag/+2S5uePv3V3y4RzNqgH83Yved
+FziWKpVQdcTHeuj/QJBAJl1G3WFruk0llIoKKbKljaEiCm1WCTcuEPbdOtkJYvO
9ZYQg/fji70FERkq2KHtY7aLhCHzy0d4n9xgE/pjV+I=
-----END RSA PRIVATE KEY-----

We can sign a message with this key using the following Stitch function:

exports = function(message) {
  const rsaPrivateKey = context.values.get("rsaPrivateKey");
  const signature = utils.crypto.sign("rsa", message, rsaPrivateKey, "pss");
  return signature;
}

If we use the function to sign the message "MongoDB is great!", it returns a BSON.Binary signature that evaluates to the following base64 string:

"SpfXcJwPbypArt+XuYQyuZqU52YCAY/sZj2kiuin2b6/RzyM4Ek3n3spOtqZJqxn1tfQavxIX4V+prbs74/pOaQkCLekl9Hoa1xOzSKcGoRd8U+n1+UBY3d3cyODGMpyr8Tim2HZAeLPE/D3Q36/K+jpgjvrJFXsJoAy5/PV7iEGV1fkzogmZtXWDcUUBBTTNPY4qZTzjNhL4RAFOc7Mfci+ojE/lLsNaumUVU1/Eky4vasmyjqunm+ULCcRmgWtGDMGHaQV4OXC2LMUe9GOqd3Q9ghCe0Vlhn25oTh8cXoGpd1Fr8wolNa//9dUqSM+QYDpZJXGLShX/Oa8mPwJZKDKHtqrS+2vE6S4dDWR7zKDza+DeovOeCih71QyuSYMXSz+WWGgfLzv/syhmUXP/mjqgLmJU6Kwg5htajDoylpzLC0BLGT4zDZEwBrq/AjwRs/EPjYdFgGCt1WCbbVlDyXvvH1ekDrzACzumhiMSZNNa+ZH3JmMJxTCQWDfiTeAfkauaaZHKIj2q2/QE7vuAhNcVPJ2YgpXnvnQHJpEZBc/Y3Q6JLxom6+cGC4P//9d++r2cwzXIkqD+wSGZVSVtpm5CLtWMRSK5FX2dv16bM+LE8ozoRvtMUDTrQ8SSSDGxyuYbvN9b2fYYPcWpCMchqOBXV6eZGoMldaHX3Qy5h8="
utils.crypto.verify(encryptionType, message, publicKey, signature, signatureScheme)

Checks that the provided signature is valid for the specified message and public key.

If the signature is valid, it guarantees that the signer has access to the corresponding private key and that the message content has not been altered since it was signed.

Parameter Type Description
encryptionType String

The type of encryption that was used to generate the private/public key pair. The following encryption types are supported:

message String The text string for which you want to verify the signature. If the signature is valid, this is the exact message that was signed.
publicKey String

The public key for which you want to verify the signature. If the signature is valid, this is the corresponding public key of the private key that was used to sign the message.

Key Format

Not all RSA keys use the same format. Stitch can only verify signatures with RSA keys that conform to the standard PKCS#1 format. Public keys in this format have the header -----BEGIN RSA PUBLIC KEY-----.

You can use the following shell script to generate a valid RSA private/public key pair and save each key to its own text file:

# Generate an RSA SSH key pair
# Save the key to a file called `rsa_key` when prompted
ssh-keygen -t rsa -m PEM -b 2048 -C "2048-bit RSA Key"

# Private Key
cat rsa_key > rsa.private.txt
# Public Key
ssh-keygen -f rsa_key.pub -e -m pem > rsa.public.txt
signature BSON.Binary The signature that you want to verify.
signatureScheme String

Optional. Default: "pss"

The padding scheme that the signature uses. Stitch supports verifying signatures that use the following schemes:

Returns:A boolean that, if true, indicates whether or not the signature is valid for the provided message and public key.

Example

We received a message with a signature in BSON.Binary format and want to verify that the message was signed with the private key that corresponds to the sender’s RSA public key:

-----BEGIN RSA PUBLIC KEY-----
MIGJAoGBANWwSOx7ao7i/enxEz+rxGrOWhzWV57fjKhi4pnZx6a5S7wmlzsoU7X5
omld1tI9k2EYt0A2fx/agwhnVH2GAQlGf9Cb9jILhE9MaDnmfMepKXOI1kkkDIRT
JTuTHn4pvqS2CiOGTyhxlGSiszwUTKWSsrOBKt9rLQ9xYc+wqWZ5AgMBAAE=
-----END RSA PUBLIC KEY-----

We can use the following Stitch function to verify the RSA signature:

exports = function(message, rsaPublicKey, signature) {
  const isValid = utils.crypto.verify("rsa", message, rsaPublicKey, signature, "pss");
  return isValid; // true if the signature matches, else false
}
utils.crypto.hmac(input, secret, hash_function, output_format)

Generates an HMAC signature from the provided input and secret. This is useful when communicating with third-party HTTP services that require signed requests.

Parameter Type Description
input string The input for which you would like to generate a signature.
secret string The secret key to use when generating the signature.
hash_function string The name of the hashing function to use when generating the signature. The following functions are supported: "sha1", "sha256", "sha512".
output_format string The format of the generated signature. Can be either "hex" for a hex string, or "base64" for a Base64 string.
Returns:The signature of the input, in the format specified by output_format.
utils.crypto.hash(hash_function, input)

Generates a hash value for the provided input using the specified hash function.

Parameter Type Description
hash_function string The name of the hashing function. The following functions are supported: "sha1", "sha256", "md5".
input string or BSON.Binary Required. The input for which you would like to generate a hash value.
Returns:A hash value for the provided input generated by the specified hashing function.

Example

The API for Coinbase allows developers to make HTTP requests on behalf of their account by using an API key and by signing the requests with a secret. This page on their documentation gives an overview of the mechanics.

The following example shows a function using utils.crypto.hmac to sign a request to the Coinbase API. The function requests a list of transactions from the primary wallet of the user associated with the API key and secret.

Note

This function assumes the existence of an HTTP service named coinbase with a rule that allows GET requests to api.coinbase.com. It also assumes the existence of values named coinbase_api_key and coinbase_secret that are populated appropriately.

The API key configured in Coinbase must also allow the wallet:transactions:read scope for the request to complete successfully with a 200 OK status.

exports = function() {
  const cur_unix_time = Math.floor(Date.now() / 1000);
  const api_url = "https://api.coinbase.com";
  const request_path = "/v2/accounts/primary/transactions";

  const message = cur_unix_time.toString() + "GET" + request_path;
  const signature = utils.crypto.hmac(message, context.values.get("coinbase_secret"), "sha256", "hex");

  const coinbase = context.services.get("myCoinbaseService")
  const response = await coinbase.get({
    url: api_url + request_path,
    headers: {
      "CB-ACCESS-SIGN": [signature],
      "CB-ACCESS-TIMESTAMP": [cur_unix_time.toString()],
      "CB-ACCESS-KEY": [context.values.get("coinbase_api_key")]
    }
  });

  return EJSON.parse(response.body.text());
};
←   Context Modules Triggers  →