NodeJS Server SDK
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.
Related
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-serverAlternatively, using yarn:
yarn add @dodgeball/trust-sdk-serverUsage
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);
// 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
sessionId: req.session.id,
userId: req.session.userId,
useVerificationId: req.headers["x-dodgeball-verification-id"],
});
if (dodgeball.isAllowed(checkpointResponse)) {
const placedOrder = await database.createOrder(req.body.order);
return res.status(200).json({ order: placedOrder });
} else if (dodgeball.isRunning(checkpointResponse)) {
return res.status(202).json({ verification: checkpointResponse.verification });
} else if (dodgeball.isDenied(checkpointResponse)) {
return res.status(403).json({ verification: checkpointResponse.verification });
} else {
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 configuration options:
const dodgeball = new Dodgeball("secret-api-key...", {
apiVersion: "v1",
apiUrl: "https://api.dodgeballhq.com",
logLevel: "ERROR",
});| Option | Default | Description |
|---|---|---|
apiVersion | v1 | The Dodgeball API version to use. |
apiUrl | https://api.dodgeballhq.com | The base URL of the Dodgeball API. Useful for sending requests to different environments such as https://api.sandbox.dodgeballhq.com. |
logLevel | INFO | Logging level. Options: TRACE, INFO, ERROR, NONE. |
Call a Checkpoint
Checkpoints represent key moments of risk in an application. A checkpoint can represent any activity deemed to be a risk — 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: {
amount: 100,
currency: "USD",
paymentMethod: {
token: "ghi789",
},
},
},
sourceToken: "abc123...", // (Optional) Obtained from the Dodgeball Client SDK
sessionId: "session_def456", // The current session ID of the request
userId: "user_12345", // The user ID in your database (after registration); leave blank if unknown
useVerificationId: "def456", // (Optional) If you have a verification ID, pass it here
});| Parameter | Required | Description |
|---|---|---|
checkpointName | true | The name of the checkpoint to call. |
event | true | The event to send to the checkpoint. |
event.ip | true | The IP address of the device where the request originated. |
event.data | false | Object containing arbitrary data to send to the checkpoint. |
sourceToken | false | A Dodgeball generated token representing the device making the request. |
sessionId | true | The current session ID of the request. |
userId | false | The user ID in your database (after registration). Leave blank if unknown. |
useVerificationId | false | If a previous verification was performed, pass it here. See useVerification. |
Interpreting the Checkpoint Response
Calling a checkpoint creates a verification in Dodgeball. The status and outcome determine how your application should proceed.
const checkpointResponse = {
success: boolean,
errors: [
{
code: number,
message: string,
},
],
version: string,
verification: {
id: string,
status: string,
outcome: string,
},
};| Property | Description |
|---|---|
success | Whether the request was successful or failed. |
errors | If success is false, contains an array of error objects with code and message. |
version | The Dodgeball API version used. Default is v1. |
verification | Object representing the verification performed at this checkpoint. |
verification.id | The ID of the verification created. |
verification.status | The current status. See Verification Statuses. |
verification.outcome | The outcome. See Verification Outcomes. |
Verification Statuses
| Status | Description |
|---|---|
COMPLETE | The verification was completed successfully. |
PENDING | The verification is currently processing. |
BLOCKED | The verification is waiting for input from the user. |
FAILED | The verification encountered an error and was unable to proceed. |
Verification Outcomes
| Outcome | Description |
|---|---|
APPROVED | The request should be allowed to proceed. |
DENIED | The request should be denied. |
PENDING | A determination has not been reached yet. |
ERROR | The verification encountered an error and was unable to make a determination. |
Possible Checkpoint Responses
Approved — status: "COMPLETE", outcome: "APPROVED"
Denied — status: "COMPLETE", outcome: "DENIED"
Pending — status: "PENDING", outcome: "PENDING" (still processing)
Blocked — status: "BLOCKED", outcome: "PENDING" (awaiting user input, e.g. MFA)
Undecided — status: "COMPLETE", outcome: "PENDING" (finished but no determination reached)
Error — success: false, status: "FAILED", outcome: "ERROR"
Utility Methods
It is strongly advised to use these methods rather than directly interpreting the checkpoint response.
dodgeball.isAllowed(checkpointResponse)
dodgeball.isAllowed(checkpointResponse)Returns true if the request is allowed to proceed.
dodgeball.isDenied(checkpointResponse)
dodgeball.isDenied(checkpointResponse)Returns true if the request is denied and should not proceed.
dodgeball.isRunning(checkpointResponse)
dodgeball.isRunning(checkpointResponse)Returns true if no determination has been reached. Return the verification to the frontend to gather additional user input. See useVerification.
dodgeball.isUndecided(checkpointResponse)
dodgeball.isUndecided(checkpointResponse)Returns true if the verification has finished with no determination reached.
dodgeball.hasError(checkpointResponse)
dodgeball.hasError(checkpointResponse)Returns true if the response contains an error.
dodgeball.isTimeout(checkpointResponse)
dodgeball.isTimeout(checkpointResponse)Returns true if the verification has timed out. The application decides how to proceed.
useVerification
Sometimes additional input is required from the user before making a determination. For example, if 2FA is required, the checkpoint response will have status: "BLOCKED" and outcome: "PENDING". Return the verification to your frontend and pass it to dodgeball.handleVerification() to prompt the user. Once the user completes the step, pass the resulting verification ID back to your API via useVerification.
Important: 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,
"x-dodgeball-verification-id": previousVerificationId,
},
}
);
dodgeball.handleVerification(endpointResponse.data.verification, {
onVerified: async (verification) => {
await placeOrder(order, verification.id);
},
onApproved: async () => {
setIsOrderPlaced(true);
},
onDenied: async (verification) => {
setIsOrderDenied(true);
},
onError: async (error) => {
setError(error);
setIsPlacingOrder(false);
},
});
};// In your API...
app.post("/api/orders", async (req, res) => {
const checkpointResponse = await dodgeball.checkpoint({
checkpointName: "PLACE_ORDER",
event: {
ip: getIp(req),
data: {
order: req.body.order,
},
},
sourceToken: req.headers["x-dodgeball-source-token"],
sessionId: req.session.id,
userId: req.session.userId,
useVerificationId: req.headers["x-dodgeball-verification-id"],
});
if (dodgeball.isAllowed(checkpointResponse)) {
const placedOrder = await database.createOrder(req.body.order);
return res.status(200).json({ order: placedOrder });
} else if (dodgeball.isRunning(checkpointResponse)) {
return res.status(202).json({ verification: checkpointResponse.verification });
} else if (dodgeball.isDenied(checkpointResponse)) {
return res.status(403).json({ verification: checkpointResponse.verification });
} else {
return res.status(500).json({ message: checkpointResponse.errors });
}
});Updated about 2 hours ago
