-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
134 lines (106 loc) · 7.04 KB
/
Copy pathmiddleware.ts
File metadata and controls
134 lines (106 loc) · 7.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
// ─────────────────────────────────────────────────────────────────────────────
// IPGeolocation.io – Next.js Middleware
//
// Usage (Next.js ≥ 13):
// Copy this file to `middleware.ts` at your project root, or import the
// middleware function and call it from your own middleware.ts:
//
// import { middleware, config } from 'ipgeolocation-vercel-middleware/middleware';
// export { middleware, config };
//
// ─────────────────────────────────────────────────────────────────────────────
import type { NextRequest } from 'next/server';
import { NextResponse } from 'next/server';
import {
getClientIp,
lookupIpGeolocation,
parseCsvEnv,
parseRedirectMap,
shouldBlockBySecurity,
envFlag
} from './ipgeolocation-edge.js';
export async function middleware(request: NextRequest): Promise<NextResponse> {
const apiKey = process.env.IPGEOLOCATION_API_KEY;
if (!apiKey) return NextResponse.next();
// ── Config ────────────────────────────────────────────────────────────────
const blockPath = process.env.IPGEO_BLOCK_PATH || '/blocked';
const headerPrefix = process.env.IPGEO_HEADER_PREFIX || 'x-ipgeo';
const failClosed = envFlag(process.env.IPGEO_FAIL_CLOSED);
const trustFirstXff = envFlag(process.env.IPGEO_TRUST_FIRST_XFF);
// ── Guard: never re-run on the block page itself ──────────────────────────
const { pathname } = request.nextUrl;
if (pathname === blockPath || pathname.startsWith(blockPath + '/')) {
return NextResponse.next();
}
// ── Extract client IP ─────────────────────────────────────────────────────
const ip = getClientIp(request.headers, trustFirstXff);
if (!ip) return NextResponse.next();
// ── Geo lookup ────────────────────────────────────────────────────────────
const geo = await lookupIpGeolocation({
apiKey,
ip,
includeSecurity: true,
timeoutMs: Number(process.env.IPGEO_TIMEOUT_MS || '3000')
});
if (!geo) {
if (failClosed) {
const url = new URL(blockPath, request.url);
url.searchParams.set('reason', 'lookup_failed');
return NextResponse.redirect(url);
}
return NextResponse.next();
}
// ── Country controls ──────────────────────────────────────────────────────
const countryCode = geo.location?.country_code2?.toUpperCase() ?? '';
const allowedCountries = parseCsvEnv(process.env.IPGEO_ALLOWED_COUNTRIES);
const blockedCountries = parseCsvEnv(process.env.IPGEO_BLOCKED_COUNTRIES);
if (countryCode && allowedCountries.size > 0 && !allowedCountries.has(countryCode)) {
return NextResponse.redirect(new URL(blockPath, request.url));
}
if (countryCode && blockedCountries.has(countryCode)) {
return NextResponse.redirect(new URL(blockPath, request.url));
}
// ── Security controls ─────────────────────────────────────────────────────
const securityBlockReason = shouldBlockBySecurity(geo.security);
if (securityBlockReason) {
const url = new URL(blockPath, request.url);
url.searchParams.set('reason', securityBlockReason);
return NextResponse.redirect(url);
}
// ── Country-based redirects ───────────────────────────────────────────────
const redirectMap = parseRedirectMap(process.env.IPGEO_COUNTRY_REDIRECTS);
const redirectPath = countryCode ? redirectMap[countryCode] : undefined;
if (redirectPath && !pathname.startsWith(redirectPath)) {
return NextResponse.redirect(new URL(redirectPath, request.url));
}
// ── Forward geo headers to the origin ────────────────────────────────────
const requestHeaders = new Headers(request.headers);
requestHeaders.set(`${headerPrefix}-ip`, geo.ip ?? ip);
requestHeaders.set(`${headerPrefix}-country`, countryCode);
requestHeaders.set(`${headerPrefix}-country-name`, geo.location?.country_name ?? '');
requestHeaders.set(`${headerPrefix}-state`, geo.location?.state_prov ?? '');
requestHeaders.set(`${headerPrefix}-city`, geo.location?.city ?? '');
requestHeaders.set(`${headerPrefix}-latitude`, geo.location?.latitude ?? '');
requestHeaders.set(`${headerPrefix}-longitude`, geo.location?.longitude ?? '');
requestHeaders.set(`${headerPrefix}-timezone`, geo.time_zone?.name ?? '');
requestHeaders.set(`${headerPrefix}-asn`, geo.asn?.as_number ?? '');
requestHeaders.set(`${headerPrefix}-asn-organization`, geo.asn?.organization ?? '');
requestHeaders.set(`${headerPrefix}-threat-score`, String(geo.security?.threat_score ?? ''));
requestHeaders.set(`${headerPrefix}-is-vpn`, String(Boolean(geo.security?.is_vpn)));
requestHeaders.set(`${headerPrefix}-is-proxy`, String(Boolean(geo.security?.is_proxy)));
requestHeaders.set(`${headerPrefix}-is-tor`, String(Boolean(geo.security?.is_tor)));
requestHeaders.set(`${headerPrefix}-is-bot`, String(Boolean(geo.security?.is_bot)));
requestHeaders.set(`${headerPrefix}-is-spam`, String(Boolean(geo.security?.is_spam)));
requestHeaders.set(`${headerPrefix}-is-known-attacker`, String(Boolean(geo.security?.is_known_attacker)));
requestHeaders.set(`${headerPrefix}-is-cloud-provider`, String(Boolean(geo.security?.is_cloud_provider)));
requestHeaders.set(`${headerPrefix}-cloud-provider-name`, geo.security?.cloud_provider_name ?? '');
return NextResponse.next({ request: { headers: requestHeaders } });
}
// ─────────────────────────────────────────────────────────────────────────────
// Matcher — skips static assets, favicons, sitemaps, and the block page
// ─────────────────────────────────────────────────────────────────────────────
export const config = {
matcher: [
'/((?!_next/static|_next/image|favicon.ico|robots.txt|sitemap.xml|blocked).*)'
]
};