Skip to content

Commit

Permalink
feat(staking): add vpn detection and blocking
Browse files Browse the repository at this point in the history
  • Loading branch information
cprussin committed Sep 11, 2024
1 parent b4ffa77 commit 0a0770a
Show file tree
Hide file tree
Showing 4 changed files with 59 additions and 353 deletions.
1 change: 1 addition & 0 deletions apps/staking/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
"dnum": "^2.13.1",
"next": "^14.2.5",
"pino": "^9.3.2",
"proxycheck-ts": "^0.0.11",
"react": "^18.3.1",
"react-aria": "^3.34.3",
"react-aria-components": "^1.3.3",
Expand Down
1 change: 1 addition & 0 deletions apps/staking/src/config/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ export const BLOCKED_REGIONS =
: process.env.BLOCKED_REGIONS.split(",").map((region) =>
region.toLowerCase().trim(),
);
export const PROXYCHECK_API_KEY = demandInProduction("PROXYCHECK_API_KEY");

class MissingEnvironmentError extends Error {
constructor(name: string) {
Expand Down
25 changes: 21 additions & 4 deletions apps/staking/src/middleware.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
import { type NextRequest, NextResponse } from "next/server";
import ProxyCheck from "proxycheck-ts";

import { BLOCKED_SEGMENT } from "./config/isomorphic";
import { BLOCKED_REGIONS } from "./config/server";
import { BLOCKED_REGIONS, PROXYCHECK_API_KEY } from "./config/server";

export const middleware = (request: NextRequest) => {
if (blockRequest(request)) {
const proxyCheckClient = PROXYCHECK_API_KEY
? new ProxyCheck({ api_key: PROXYCHECK_API_KEY })
: undefined;

export const middleware = async (request: NextRequest) => {
if (await shouldBlockRequest(request)) {
return NextResponse.rewrite(new URL(`/${BLOCKED_SEGMENT}`, request.url));
} else if (request.nextUrl.pathname.startsWith("/blocked")) {
return NextResponse.rewrite(new URL("/not-found", request.url));
Expand All @@ -13,10 +18,22 @@ export const middleware = (request: NextRequest) => {
}
};

const blockRequest = (request: NextRequest) =>
const shouldBlockRequest = async (request: NextRequest) =>
isRegionBlocked(request) || (await isProxyBlocked(request));

const isRegionBlocked = (request: NextRequest) =>
request.geo?.country !== undefined &&
BLOCKED_REGIONS.includes(request.geo.country.toLowerCase());

const isProxyBlocked = async ({ ip }: NextRequest) => {
if (proxyCheckClient === undefined || ip === undefined) {
return false;
} else {
const result = await proxyCheckClient.checkIP(ip, { vpn: 2 });
return result[ip]?.proxy === "yes";
}
};

export const config = {
matcher: [
"/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
Expand Down
Loading

0 comments on commit 0a0770a

Please sign in to comment.