From f0a87e143924774afd9d72606f49180b446f90df Mon Sep 17 00:00:00 2001 From: Alex Date: Wed, 19 Jun 2024 16:37:24 +0200 Subject: [PATCH] Geoblocking (#176) * feat: initial pass at geoblocking * initial blocked page * fix: build * feat: region support * fix: add matcher to skip redirects to /blocked * chore: better matcher * chore: update copy --- src/middleware.ts | 62 +++++++++++++++++++++++++++++++++++++++++++ src/pages/blocked.tsx | 11 ++++++++ 2 files changed, 73 insertions(+) create mode 100644 src/middleware.ts create mode 100644 src/pages/blocked.tsx diff --git a/src/middleware.ts b/src/middleware.ts new file mode 100644 index 00000000..230380c1 --- /dev/null +++ b/src/middleware.ts @@ -0,0 +1,62 @@ +import { NextRequest, NextResponse } from 'next/server'; + +export const config = { + matcher: ['/((?!blocked/_next/static/backgrounds/fonts/favicon).*)'], +}; + +const BLOCKED_COUNTRIES = [ + 'CU', // Cuba + 'KP', // North Korea + 'RU', // Russia + 'AF', // Afghanistan + 'BY', // Belarus + 'BA', // Bosnia & Herzegovina + 'CF', // Central African Republic + 'CD', // Democratic Republic of the Congo + 'GN', // Guinea + 'GW', // Guinea-Bissau + 'HT', // Haiti + 'IQ', // Iraq + 'LB', // Lebanon + 'LY', // Libya + 'ML', // Mali + 'NI', // Nicaragua + 'SO', // Somalia + 'SS', // South Sudan + 'SD', // Sudan + 'VE', // Venezuela + 'YE', // Yemen + 'ZW', // Zimbabwe + 'MM', // Myanmar + 'SY', // Syria +]; + +const BLOCKED_REGIONS = [ + { + country: 'UA', // Ukraine + regions: [ + '43', // Crimea + '14', // Donetsk + '09', // Luhansk + ], + }, +]; + +export function middleware(req: NextRequest) { + const country = req.geo?.country; + const region = req.geo?.region; + + if (country && BLOCKED_COUNTRIES.includes(country)) { + return NextResponse.redirect('/blocked'); + } + + if ( + country && + region && + BLOCKED_REGIONS.find((x) => x.country === country)?.regions.includes(region) + ) { + return NextResponse.redirect('/blocked'); + } + + return NextResponse.next(); +} diff --git a/src/pages/blocked.tsx b/src/pages/blocked.tsx new file mode 100644 index 00000000..b9f9db38 --- /dev/null +++ b/src/pages/blocked.tsx @@ -0,0 +1,11 @@ +import { ErrorBoundary } from '../components/errors/ErrorBoundary'; + +export default function Page() { + return ( + + {(() => { + throw new Error('Your region has been blocked from accessing this service'); + })()} + + ); +}