Skip to content

Commit

Permalink
Merge pull request #833 from supertokens/anomaly-detection
Browse files Browse the repository at this point in the history
Anomaly detection
  • Loading branch information
rishabhpoddar authored Sep 12, 2024
2 parents 5500a2d + 79edabb commit f6d603e
Show file tree
Hide file tree
Showing 24 changed files with 10,929 additions and 23,575 deletions.
1,780 changes: 1,780 additions & 0 deletions v2/botandspamdetection/backend-setup.mdx

Large diffs are not rendered by default.

18 changes: 18 additions & 0 deletions v2/botandspamdetection/enabling.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
---
sidebar_position: 1
title: Enabling the feature
hide_title: true
---

import CustomAdmonition from "/src/components/customAdmonition"

# Enabling the feature

This feature is **currently in beta**. In order to get access to this feature, please reach out to us at [email protected] to get it setup for you.

Once you have access to the feature, you will receive from us:
- **Public API key** - this will be used on your frontend for generating request IDs
- **Secret API key** - this will be used on your backend for making requests to our anomaly detection API
- **Environment ID** - this will be used for identifying the environment you are using both on the backend and the frontend


112 changes: 112 additions & 0 deletions v2/botandspamdetection/frontend-setup.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
---
sidebar_position: 2
title: Frontend Setup
hide_title: true
---

# Setting up the Frontend

Setting up the frontend is relatively simple. You need to generate a request ID for each authentication event attempt.

:::important
This frontend setup is required only for bot detection and anomaly IP based detection such as impossible travel detection. We also recommend checking for bot detection only on the email password login flows.
:::

### Generating a Request ID on the Frontend

In order to generate a request ID, you need to import and initialise the SDK using your public API key. This SDK is used to generate a unique request ID for each authentication event attempt.

Below is an example of how to implement request ID generation on your frontend:


```tsx
const PUBLIC_API_KEY = "<public-api-key>"; // Your public API key that you received from the SuperTokens team
const SDK_URL = "https://supertokens.io/JfNbWqtXUiGYuTqb/PYmK3PIPqdvHw6iz";
const ENVIRONMENT_ID = "<environment-id>"; // Your environment ID that you received from the SuperTokens team

const supertokensAnomalyDetectionSdkPromise = import(SDK_URL + "?apiKey=" + PUBLIC_API_KEY).then((RequestId: any) => RequestId.load({
endpoint: [
SDK_URL,
RequestId.defaultEndpoint
]
}));

async function getRequestId() {
const sdk = await supertokensAnomalyDetectionSdkPromise;
const result = await sdk.get({
tag: {
environmentId: ENVIRONMENT_ID,
}
});
return result.requestId;
}
```

### Passing the Request ID to the Backend

Once you have generated the request ID on the frontend, you need to pass it to the backend. This is done by including the `requestId` property along with the value as part of the preAPIHook body from the initialisation of the recipes.

:::important
If the request ID is not passed to the backend, the anomaly detection will only be able to detect password breaches and brute force attacks.
:::

Below is a full example of how to configure the SDK and pass the request ID to the backend. The request ID is being generated only for the email password sign in, sign up and reset password actions because these are the only actions that require bot detection (the reason the request ID is needed). For all the other recipes (or actions), this is not needed.
```tsx
import EmailPassword from "supertokens-auth-react/recipe/emailpassword";

const PUBLIC_API_KEY = "<public-api-key>"; // Your public API key that you received from the SuperTokens team
const SDK_URL = "https://supertokens.io/JfNbWqtXUiGYuTqb/PYmK3PIPqdvHw6iz";
const ENVIRONMENT_ID = "<environment-id>"; // Your environment ID that you received from the SuperTokens team

const supertokensRequestIdPromise = import(SDK_URL + "?apiKey=" + PUBLIC_API_KEY).then((RequestId: any) => RequestId.load({
endpoint: [
SDK_URL,
RequestId.defaultEndpoint
]
}));

async function getRequestId() {
const requestId = await supertokensRequestIdPromise;
const result = await requestId.get({
tag: {
environmentId: ENVIRONMENT_ID,
}
});
return result.requestId;
}

export const SuperTokensConfig = {
// ... other config options
appInfo: {
appName: "...",
apiDomain: '...',
websiteDomain: '...',
},
// recipeList contains all the modules that you want to
// use from SuperTokens. See the full list here: https://supertokens.com/docs/guides
recipeList: [
EmailPassword.init({
// highlight-start
preAPIHook: async (context) => {
let url = context.url;
let requestInit = context.requestInit;

let action = context.action;
if (action === "EMAIL_PASSWORD_SIGN_IN" || action === "EMAIL_PASSWORD_SIGN_UP" || action === "SEND_RESET_PASSWORD_EMAIL") {
let requestId = await getRequestId();
let body = context.requestInit.body;
if (body !== undefined) {
let bodyJson = JSON.parse(body as string);
bodyJson.requestId = requestId;
requestInit.body = JSON.stringify(bodyJson);
}
}
return {
requestInit, url
};
}
// highlight-end
}),
],
};
```
72 changes: 72 additions & 0 deletions v2/botandspamdetection/introduction.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
---
sidebar_position: 1
title: Introduction
hide_title: true
---

import CustomAdmonition from "/src/components/customAdmonition"

# Introduction

SuperTokens Bot / Spam detection is a powerful security feature designed to identify and prevent suspicious activities in authentication and user sessions. It leverages various detection methods to enhance the security of your application.

:::important
This feature is **currently in beta** and not enabled by default. You can find out how to enable this feature [here](/docs/botandspamdetection/enabling).
:::

## Features

### Brute Force Attack Detection
Watches how many times someone tries to do a specific action (such as logging in, resetting password, etc.) within a certain time. If there are too many attempts, it stops them to prevent bad actors from compromising accounts.

### Password Breach Detection
Checks passwords against a database of leaked passwords to see if they've been leaked before. This helps keep accounts safe by avoiding weak passwords.

### Impossible Travel Detection
Identifies potentially fraudulent login attempts by detecting geographically impossible travel between user sessions in a short time.

### Bot Detection
Identifies and prevents automated scripts or bots from performing malicious activities such as credential stuffing, account takeover attempts, or scraping sensitive data. It uses advanced algorithms to analyze user behavior, request patterns, and other indicators to distinguish between human users and automated bots.

### Suspicious IP Detection
Detects suspicious IP addresses that are known for malicious activities. This includes detecting the use of VPNs, TOR, proxy servers, or other network configurations that may be used to hide the user's true location or identity.

### New Device Detection
Recognizes when a user logs in from a new, previously unseen device. This helps find possible unauthorized logins.

### Device Count Tracking
Monitors the number of unique devices associated with a user account. This helps spot unusual account use.

### Requester Detection
Recognize and remember devices and requester details, even when they try to disguise themselves. This helps track and identify the same device or requester across multiple login attempts, improving security and user recognition.


## Flow diagram

The Bot / Spam detection service is typically integrated into your authentication flow. It processes requests and provides risk assessments that you can use to enforce additional security measures, such as requiring two-factor authentication for suspicious logins or blocking high-risk attempts altogether.

By leveraging these advanced detection methods, SuperTokens Bot / Spam detection significantly enhances your application's security posture and helps protect your users from various types of account compromise attempts.

Below is an high level overview of how this works:

<img src="/img/botandspamdetection/sequence-diagram.png" alt="Bot / Spam detection flow"/>

## Recipes integration

Different recipes have different ways of integrating with the Bot / Spam detection feature.

### Passwordless

When using the passwordless recipe, the **only check should be brute force detection**. Other checks are not needed as the passwordless flow by itself prevents bot attacks.

### Email Password Login

When using the email password login recipe, bot detection (and possibly other checks) **should be used** along with brute force detection.

### Phone Password Login

When using the phone password login recipe, bot detection (and possibly other checks) **should be used** along with brute force detection.

### Social/enterprise Login

When using these types of recipes, there **should be no checks used**.
3 changes: 3 additions & 0 deletions v2/botandspamdetection/sidebars.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module.exports = {
sidebar: ["introduction", "enabling", "frontend-setup", "backend-setup"],
};
Loading

0 comments on commit f6d603e

Please sign in to comment.