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-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);

// 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",
});
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.
logLevelINFOLogging 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
});
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 to the checkpoint.
sourceTokenfalseA Dodgeball generated token representing the device making the request.
sessionIdtrueThe current session ID of the request.
userIdfalseThe user ID in your database (after registration). Leave blank if unknown.
useVerificationIdfalseIf 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,
  },
};
PropertyDescription
successWhether the request was successful or failed.
errorsIf success is false, contains an array of error objects with code and message.
versionThe Dodgeball API version used. Default is v1.
verificationObject representing the verification performed at this checkpoint.
verification.idThe ID of the verification created.
verification.statusThe current status. See Verification Statuses.
verification.outcomeThe outcome. See Verification Outcomes.

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 has not been reached yet.
ERRORThe verification encountered an error and was unable to make a determination.

Possible Checkpoint Responses

Approvedstatus: "COMPLETE", outcome: "APPROVED"

Deniedstatus: "COMPLETE", outcome: "DENIED"

Pendingstatus: "PENDING", outcome: "PENDING" (still processing)

Blockedstatus: "BLOCKED", outcome: "PENDING" (awaiting user input, e.g. MFA)

Undecidedstatus: "COMPLETE", outcome: "PENDING" (finished but no determination reached)

Errorsuccess: 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)

Returns true if the request is allowed to proceed.

dodgeball.isDenied(checkpointResponse)

Returns true if the request is denied and should not proceed.

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)

Returns true if the verification has finished with no determination reached.

dodgeball.hasError(checkpointResponse)

Returns true if the response contains an error.

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 });
  }
});