Skip to main content

Dodgeball Server Trust SDK for NodeJS

Table of Contents

Purpose

Dodgeball enables developers to decouple security logic from their application code. This has several benefits including:

  • The ability to toggle and compare security services like fraud engines, MFA, KYC, and bot prevention.
  • Faster responses to new attacks. When threats evolve and new vulnerabilities are identified, your application's security logic can be updated without changing a single line of code.
  • The ability to put in placeholders for future security improvements while focussing on product development.
  • A way to visualize all application security logic in one place.

The Dodgeball Server Trust SDK for NodeJS makes integration with the Dodgeball API easy and is maintained by the Dodgeball team.

Prerequisites

You will need to obtain an API key for your application from the Developer Center > API Keys page.

Check out the Dodgeball Trust Client SDK for how to integrate Dodgeball into your frontend applications.

Installation

Use npm to install the Dodgeball module:

npm install @dodgeball/trust-sdk-server

Alternatively, using yarn:

yarn add @dodgeball/trust-sdk-server

Usage

import { Dodgeball } from "@dodgeball/trust-sdk-server";
import express from "express";

const app = express();
// Initialize the SDK with your secret API key.
const dodgeball = new Dodgeball(process.env.DODGEBALL_SECRET_KEY);

// Here's a simple utility method for grabbing the originating IP address from the request.
const getIp = (req) => {
return req.headers["x-forwarded-for"]?.split(",").shift() || req.socket?.remoteAddress;
};

app.post("/api/orders", async (req, res) => {
// In moments of risk, call a checkpoint within Dodgeball to verify the request is allowed to proceed
const checkpointResponse = await dodgeball.checkpoint({
checkpointName: "PLACE_ORDER",
event: {
ip: getIp(req),
data: {
order: req.body.order,
},
},
sourceToken: req.headers["x-dodgeball-source-token"], // (Optional) Obtained from the Dodgeball Client SDK, represents the device making the request
sessionId: req.session.id,
userId: req.session.userId,
useVerificationId: req.headers["x-dodgeball-verification-id"],
});

if (dodgeball.isAllowed(checkpointResponse)) {
// Proceed with placing the order
const placedOrder = await database.createOrder(req.body.order);
return res.status(200).json({
order: placedOrder,
});
} else if (dodgeball.isRunning(checkpointResponse)) {
// If the outcome is pending, send the verification to the frontend to do additional checks (such as MFA, KYC)
return res.status(202).json({
verification: checkpointResponse.verification,
});
} else if (dodgeball.isDenied(checkpointResponse)) {
// If the request is denied, you can return the verification to the frontend to display a reason message
return res.status(403).json({
verification: checkpointResponse.verification,
});
} else {
// If the checkpoint failed, decide how you would like to proceed. You can return the error, choose to proceed, retry, or reject the request.
return res.status(500).json({
message: checkpointResponse.errors,
});
}
});

app.listen(process.env.APP_PORT, () => {
console.log(`Listening on port ${process.env.APP_PORT}`);
});

API

Configuration


The package requires a secret API key as the first argument to the constructor.

const dodgeball = new Dodgeball("secret-api-key...");

Optionally, you can pass in several configuration options to the constructor:

const dodgeball = new Dodgeball("secret-api-key...", {
// Optional configuration
apiVersion: "v1",
apiUrl: "https://api.dodgeballhq.com",
logLevel: "ERROR",
});
OptionDefaultDescription
apiVersionv1The Dodgeball API version to use.
apiUrlhttps://api.dodgeballhq.comThe base URL of the Dodgeball API. Useful for sending requests to different environments such as https://api.sandbox.dodgeballhq.com.
logLevelINFOThe level of logging to use. Possible options are TRACE, INFO, ERROR, or NONE. TRACE and INFO are useful for debugging. ERROR only logs errors. NONE turns off all logging.

Call a Checkpoint


Checkpoints represent key moments of risk in an application and at the core of how Dodgeball works. A checkpoint can represent any activity deemed to be a risk. Some common examples include: login, placing an order, redeeming a coupon, posting a review, changing bank account information, making a donation, transferring funds, creating a listing.

const checkpointResponse = dodgeball.checkpoint({
checkpointName: "CHECKPOINT_NAME",
event: {
ip: "127.0.0.1", // The IP address of the device where the request originated
data: {
// Arbitrary data to send in to the checkpoint...
amount: 100,
currency: "USD",
paymentMethod: {
token: "ghi789",
},
},
},
sourceToken: "abc123...", // (Optional) Obtained from the Dodgeball Client SDK, represents the device making the request
sessionId: "session_def456", // The current session ID of the request
userId: "user_12345", // When you know the ID representing the user making the request in your database (ie after registration), pass it in here. Otherwise leave it blank.
useVerificationId: "def456", // (Optional) If you have a verification ID, you can pass it in here
});
ParameterRequiredDescription
checkpointNametrueThe name of the checkpoint to call.
eventtrueThe event to send to the checkpoint.
event.iptrueThe IP address of the device where the request originated.
event.datafalseObject containing arbitrary data to send in to the checkpoint.
sourceTokenfalseA Dodgeball generated token representing the device making the request. Obtained from the Dodgeball Trust Client SDK.
sessionIdtrueThe current session ID of the request.
userIdfalseWhen you know the ID representing the user making the request in your database (ie after registration), pass it in here. Otherwise leave it blank.
useVerificationIdfalseIf a previous verification was performed on this request, pass it in here. See the useVerification section below for more details.

Interpreting the Checkpoint Response


Calling a checkpoint creates a verification in Dodgeball. The status and outcome of a verification determine how your application should proceed. Continue to possible checkpoint responses for a full explanation of the possible status and outcome combinations and how to interpret them.

const checkpointResponse = {
success: boolean,
errors: [
{
code: number,
message: string,
},
],
version: string,
verification: {
id: string,
status: string,
outcome: string,
},
};
PropertyDescription
successWhether the request encountered any errors was successful or failed.
errorsIf the success flag is false, this will contain an array of error objects each with a code and message.
versionThe version of the Dodgeball API that was used to make the request. Default is v1.
verificationObject representing the verification that was performed when this checkpoint was called.
verification.idThe ID of the verification that was created.
verification.statusThe current status of the verification. See Verification Statuses for possible values and descriptions.
verification.outcomeThe outcome of the verification. See Verification Outcomes for possible values and descriptions.

Verification Statuses

StatusDescription
COMPLETEThe verification was completed successfully.
PENDINGThe verification is currently processing.
BLOCKEDThe verification is waiting for input from the user.
FAILEDThe verification encountered an error and was unable to proceed.

Verification Outcomes

OutcomeDescription
APPROVEDThe request should be allowed to proceed.
DENIEDThe request should be denied.
PENDINGA determination on how to proceed has not been reached yet.
ERRORThe verification encountered an error and was unable to make a determination on how to proceed.

Possible Checkpoint Responses

Approved
const checkpointResponse = {
success: true,
errors: [],
version: "v1",
verification: {
id: "def456",
status: "COMPLETE",
outcome: "APPROVED",
},
};

When a request is allowed to proceed, the verification status will be COMPLETE and outcome will be APPROVED.

Denied
const checkpointResponse = {
success: true,
errors: [],
version: "v1",
verification: {
id: "def456",
status: "COMPLETE",
outcome: "DENIED",
},
};

When a request is denied, verification status will be COMPLETE and outcome will be DENIED.

Pending
const checkpointResponse = {
success: true,
errors: [],
version: "v1",
verification: {
id: "def456",
status: "PENDING",
outcome: "PENDING",
},
};

If the verification is still processing, the status will be PENDING and outcome will be PENDING.

Blocked
const checkpointResponse = {
success: true,
errors: [],
version: "v1",
verification: {
id: "def456",
status: "BLOCKED",
outcome: "PENDING",
},
};

A blocked verification requires additional input from the user before proceeding. When a request is blocked, verification status will be BLOCKED and the outcome will be PENDING.

Undecided
const checkpointResponse = {
success: true,
errors: [],
version: "v1",
verification: {
id: "def456",
status: "COMPLETE",
outcome: "PENDING",
},
};

If the verification has finished, with no determination made on how to proceed, the verification status will be COMPLETE and the outcome will be PENDING.

Error
const checkpointResponse = {
success: false,
errors: [
{
code: 503,
message: "[Service Name]: Service is unavailable",
},
],
version: "v1",
verification: {
id: "def456",
status: "FAILED",
outcome: "ERROR",
},
};

If a verification encounters an error while processing (such as when a 3rd-party service is unavailable), the success flag will be false. The verification status will be FAILED and the outcome will be ERROR. The errors array will contain at least one object with a code and message describing the error(s) that occurred.

Utility Methods


There are several utility methods available to help interpret the checkpoint response. It is strongly advised to use them rather than directly interpreting the checkpoint response.

dodgeball.isAllowed(checkpointResponse)

The isAllowed method takes in a checkpoint response and returns true if the request is allowed to proceed.

dodgeball.isDenied(checkpointResponse)

The isDenied method takes in a checkpoint response and returns true if the request is denied and should not be allowed to proceed.

dodgeball.isRunning(checkpointResponse)

The isRunning method takes in a checkpoint response and returns true if no determination has been reached on how to proceed. The verification should be returned to the frontend application to gather additional input from the user. See the useVerification section for more details on use and an end-to-end example.

dodgeball.isUndecided(checkpointResponse)

The isUndecided method takes in a checkpoint response and returns true if the verification has finished and no determination has been reached on how to proceed. See undecided for more details.

dodgeball.hasError(checkpointResponse)

The hasError method takes in a checkpoint response and returns true if it contains an error.

dodgeball.isTimeout(checkpointResponse)

The isTimeout method takes in a checkpoint response and returns true if the verification has timed out. At which point it is up to the application to decide how to proceed.

useVerification


Sometimes additional input is required from the user before making a determination about how to proceed. For example, if a user should be required to perform 2FA before being allowed to proceed, the checkpoint response will contain a verification with status of BLOCKED and outcome of PENDING. In this scenario, you will want to return the verification to your frontend application. Inside your frontend application, you can pass the returned verification directly to the dodgeball.handleVerification() method to automatically handle gathering additional input from the user. Continuing with our 2FA example, the user would be prompted to select a phone number and enter a code sent to that number. Once the additional input is received, the frontend application should simply send along the ID of the verification performed to your API. Passing that verification ID to the useVerification option will allow that verification to be used for this checkpoint instead of creating a new one. This prevents duplicate verifications being performed on the user.

Important Note: To prevent replay attacks, each verification ID can only be passed to useVerification once.

End-to-End Example

// In your frontend application...
const placeOrder = async (order, previousVerificationId = null) => {
const sourceToken = await dodgeball.getSourceToken();

const endpointResponse = await axios.post(
"/api/orders",
{ order },
{
headers: {
"x-dodgeball-source-token": sourceToken, // Pass the source token to your API
"x-dodgeball-verification-id": previousVerificationId, // If a previous verification was performed, pass it along to your API
},
}
);

dodgeball.handleVerification(endpointResponse.data.verification, {
onVerified: async (verification) => {
// If an additional check was performed and the request is approved, simply pass the verification ID in to your API
await placeOrder(order, verification.id);
},
onApproved: async () => {
// If no additional check was required, update the view to show that the order was placed
setIsOrderPlaced(true);
},
onDenied: async (verification) => {
// If the action was denied, update the view to show the rejection
setIsOrderDenied(true);
},
onError: async (error) => {
// If there was an error performing the verification, display it
setError(error);
setIsPlacingOrder(false);
},
});
};
// In your API...
app.post("/api/orders", async (req, res) => {
// In moments of risk, call a checkpoint within Dodgeball to verify the request is allowed to proceed
const checkpointResponse = await dodgeball.checkpoint({
checkpointName: "PLACE_ORDER",
event: {
ip: getIp(req),
data: {
order: req.body.order,
},
},
sourceToken: req.headers["x-dodgeball-source-token"], // (Optional) Obtained from the Dodgeball Client SDK, represents the device making the request
sessionId: req.session.id,
userId: req.session.userId,
useVerificationId: req.headers["x-dodgeball-verification-id"],
});

if (dodgeball.isAllowed(checkpointResponse)) {
// Proceed with placing the order...
const placedOrder = await database.createOrder(req.body.order);
return res.status(200).json({
order: placedOrder,
});
} else if (dodgeball.isRunning(checkpointResponse)) {
// If the outcome is pending, send the verification to the frontend to do additional checks (such as MFA, KYC)
return res.status(202).json({
verification: checkpointResponse.verification,
});
} else if (dodgeball.isDenied(checkpointResponse)) {
// If the request is denied, you can return the verification to the frontend to display a reason message
return res.status(403).json({
verification: checkpointResponse.verification,
});
} else {
// If the checkpoint failed, decide how you would like to proceed. You can return the error, choose to proceed, retry, or reject the request.
return res.status(500).json({
message: checkpointResponse.errors,
});
}
});