-
Notifications
You must be signed in to change notification settings - Fork 1
/
middleware.ts
193 lines (157 loc) · 5.52 KB
/
middleware.ts
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
import { NextResponse } from 'next/server';
import { NextRequest } from 'next/server';
// import type { DecodedIdToken } from 'firebase-admin/auth';
// import { User } from './types';
import * as jose from 'jose';
import { LRUCache } from 'lru-cache';
import requestIp from 'request-ip';
const API_SKIPS: { [method: string]: string[] } = {
GET: ['api/auth', 'api/cache', 'api/redis'],
POST: ['api/auth', 'api/redis', '/v1/prices', '/v1/trades', '/v1/items', '/v1/items/open'],
};
const userKeyCache = new LRUCache({
max: 100,
});
const PUBLIC_FILE = /\.(.*)$/;
const VALID_LOCALES = ['en', 'pt'];
const skipAPIMiddleware = process.env.SKIP_API_MIDDLEWARE === 'true';
const MAINTENANCE_MODE = process.env.MAINTENANCE_MODE === 'true';
const ITEMDB_URL = process.env.ITEMDB_SERVER;
const SKIP_REDIS_KEY = process.env.SKIP_REDIS_KEY;
export async function middleware(request: NextRequest) {
if (request.nextUrl.pathname.startsWith('/_next') || PUBLIC_FILE.test(request.nextUrl.pathname)) {
return NextResponse.next();
}
if (MAINTENANCE_MODE) {
return NextResponse.rewrite(new URL('/maintenance', request.url), { status: 503 });
}
if (request.nextUrl.pathname.startsWith('/api/')) {
if (skipAPIMiddleware) return NextResponse.next();
return apiMiddleware(request);
}
const cookies = {
name: 'idb_accept-language',
value: request.headers.get('accept-language') ?? '',
expires: Date.now() + 1000000,
};
const response = NextResponse.next();
response.cookies.set(cookies);
const locale = request.cookies.get('NEXT_LOCALE')?.value;
if (!locale || locale === request.nextUrl.locale || !VALID_LOCALES.includes(locale))
return response;
const redirectResponse = NextResponse.redirect(
new URL(`/${locale}${request.nextUrl.pathname}${request.nextUrl.search}`, request.url),
);
redirectResponse.cookies.set(cookies);
return redirectResponse;
}
export const config = {
matcher: ['/api/:path*', '/:path*'],
};
// ---------- API Middleware ---------- //
const apiMiddleware = async (request: NextRequest) => {
if (process.env.NODE_ENV === 'development') return NextResponse.next();
// Skip rate limit if key is provided
if (request.headers.get('x-tarnum-skip') === process.env.TARNUM_KEY) {
return NextResponse.next();
}
if (request.method === 'OPTIONS') {
return NextResponse.next();
}
//check if request pathname has a skip route
const skips = API_SKIPS[request.method] || [];
if (skips.some((skip) => request.nextUrl.pathname.includes(skip))) {
return NextResponse.next();
}
const sessionCookie = request.cookies.get('session');
if (sessionCookie && sessionCookie.value) {
try {
await checkSessionLocal(sessionCookie.value);
const requestHeaders = new Headers(request.headers);
requestHeaders.set('idb-skip-redis', SKIP_REDIS_KEY ?? '');
return NextResponse.next({
request: {
headers: requestHeaders,
},
});
} catch (e) {}
}
// Rate limit
const ip =
requestIp.getClientIp(request as any) ||
request.ip ||
request.headers.get('X-Forwarded-For')?.split(',')[0];
if (!ip) {
return NextResponse.next();
}
const banned = await checkRedis(ip, request.nextUrl.pathname);
if (banned) {
return NextResponse.json({ error: 'Too many requests' }, { status: 429 });
}
return NextResponse.next();
};
// const checkSession = async (session: string, host: string, skipUser: boolean) => {
// const res = await fetch(`http://${host}/api/auth/checkSession`, {
// method: 'POST',
// headers: {
// 'Content-Type': 'application/json',
// },
// body: JSON.stringify({ session: session, skipUser: skipUser }),
// });
// const { authRes } = await res.json();
// return authRes as
// | {
// decodedToken: DecodedIdToken;
// user: null;
// }
// | {
// decodedToken: DecodedIdToken;
// user: User;
// };
// };
const checkSessionLocal = async (jwt: string) => {
const decoded = jose.decodeProtectedHeader(jwt);
const kid = decoded.kid as string;
let cacheKeys = userKeyCache.get('firesbaseKeys') as
| { keys: any; revalidate: number }
| undefined;
if (!cacheKeys || cacheKeys.revalidate < Date.now()) {
const res = await fetch(
'https://www.googleapis.com/identitytoolkit/v3/relyingparty/publicKeys',
);
const JWKS = await res.json();
cacheKeys = { keys: undefined, revalidate: 0 };
cacheKeys.keys = JWKS;
const cacheControl = res.headers.get('Cache-Control')?.split('=')[1];
cacheKeys.revalidate = cacheControl ? Date.now() + parseInt(cacheControl) * 1000 : 0;
userKeyCache.set('firesbaseKeys', cacheKeys);
}
if (!cacheKeys) throw new Error('No keys');
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const publicKey = await jose.importX509(cacheKeys.keys[kid], decoded.alg!);
const jwtDecoded = await jose.jwtVerify(jwt, publicKey, {
issuer: 'https://session.firebase.google.com/itemdb-1db58',
audience: 'itemdb-1db58',
});
return jwtDecoded.payload.user_id as string;
};
const checkRedis = async (ip: string, pathname: string) => {
try {
const res = await fetch(`${ITEMDB_URL}/api/redis/checkapi`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Forwarded-For': ip,
'idb-ip-check': ip,
},
body: JSON.stringify({ pathname }),
});
if (res.status === 429) {
return true;
}
return false;
} catch (e) {
console.error('checkRedis error', e);
return false;
}
};