-
Notifications
You must be signed in to change notification settings - Fork 2
/
middleware.ts
480 lines (379 loc) · 14.3 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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
import { next, RequestContext } from "@vercel/edge";
import { ipAddress } from "@vercel/functions";
import * as redirectionio from "@redirection.io/redirectionio";
import { NextResponse, type NextRequest } from "next/server";
const REDIRECTIONIO_TOKEN = process.env.REDIRECTIONIO_TOKEN || "";
const REDIRECTIONIO_INSTANCE_NAME = process.env.REDIRECTIONIO_INSTANCE_NAME || "redirection-io-vercel-middleware";
const REDIRECTIONIO_VERSION = "redirection-io-vercel-middleware/0.3.12";
const REDIRECTIONIO_ADD_HEADER_RULE_IDS = process.env.REDIRECTIONIO_ADD_HEADER_RULE_IDS
? process.env.REDIRECTIONIO_ADD_HEADER_RULE_IDS === "true"
: false;
const REDIRECTIONIO_TIMEOUT = process.env.REDIRECTIONIO_TIMEOUT ? parseInt(process.env.REDIRECTIONIO_TIMEOUT, 10) : 500;
const DEFAULT_CONFIG = {
matcherRegex: "^/((?!api/|_next/|_static/|_vercel|[\\w-]+\\.\\w+).*)$",
mode: "full",
logged: true,
} as const;
type Middleware = (request: Request | NextRequest, context: RequestContext) => Response | Promise<Response>;
type FetchResponse = (request: Request, useFetch: boolean) => Promise<Response>;
type CreateMiddlewareConfig = {
previousMiddleware?: Middleware;
nextMiddleware?: Middleware;
matcherRegex?: string | null;
mode?: "full" | "light";
logged?: boolean;
};
export const createRedirectionIoMiddleware = (config: CreateMiddlewareConfig): Middleware => {
return async (request, context) => {
const pathname = new URL(request.url).pathname;
config = {
...DEFAULT_CONFIG,
...config,
};
if (config.matcherRegex && !pathname.match(config.matcherRegex)) {
return next();
}
// Avoid infinite loop
if (
request.headers.get("x-redirectionio-middleware") === "true" ||
request.headers.get("User-Agent") === "Vercel Edge Functions"
) {
return next();
}
const body = request.body ? await request.arrayBuffer() : null;
let middlewareRequest = new Request(request.url, {
method: request.method,
headers: request.headers,
body,
});
if (config.previousMiddleware) {
const response = await config.previousMiddleware(middlewareRequest, context);
if (response.status !== 200) {
return response;
}
middlewareRequest = middlewareResponseToRequest(middlewareRequest, response, body);
}
return handler(middlewareRequest, context, config, async (request, useFetch): Promise<Response> => {
let response: Response | null = null;
if (config.nextMiddleware) {
response = await config.nextMiddleware(request, context);
if (response.status !== 200) {
return response;
}
request = middlewareResponseToRequest(request, response, body);
}
if (!useFetch) {
return response ?? next();
}
// Disable for server-actions and components.
if (request.headers.get("Next-Action")?.length || request.headers.get("Accept") === "text/x-component") {
return response ?? next();
}
const fetchResponse = await fetch(request, {
redirect: "manual",
cache: "no-store",
});
const backendResponse = new Response(fetchResponse.body, fetchResponse);
if (response) {
response.headers.forEach((value, key) => {
if (!key.startsWith("x-middleware-")) {
backendResponse.headers.set(key, value);
}
});
}
return backendResponse;
});
};
};
const defaultMiddleware = createRedirectionIoMiddleware({});
export default defaultMiddleware;
async function handler(
request: Request,
context: RequestContext,
config: CreateMiddlewareConfig,
fetchResponse: FetchResponse,
): Promise<Response> {
if (!REDIRECTIONIO_TOKEN) {
console.warn("No REDIRECTIONIO_TOKEN environment variable found. Skipping redirection.io middleware.");
return fetchResponse(request, false);
}
const startTimestamp = Date.now();
await redirectionio.init();
const ip = ipAddress(request);
const redirectionIORequest = createRedirectionIORequest(request, ip);
const action = await fetchRedirectionIOAction(redirectionIORequest);
const [response, backendStatusCode] = await proxy(request, action, (request) => {
request.headers.set("x-redirectionio-middleware", "true");
// skip fetch if we are in light mode
return fetchResponse(request, config.mode === "full");
});
const url = new URL(request.url);
const location = response.headers.get("Location");
// Fix relative location header
if (location && location.startsWith("/")) {
response.headers.set("Location", url.origin + location);
}
if (config.logged) {
context.waitUntil(
(async function () {
await log(response, backendStatusCode, redirectionIORequest, startTimestamp, action, ip);
})(),
);
}
return response;
}
function splitSetCookies(cookiesString: string) {
const cookiesStrings = [];
let pos = 0;
let start;
let ch;
let lastComma;
let nextStart;
let cookiesSeparatorFound;
function skipWhitespace() {
while (pos < cookiesString.length && /\s/.test(cookiesString.charAt(pos))) {
pos += 1;
}
return pos < cookiesString.length;
}
function notSpecialChar() {
ch = cookiesString.charAt(pos);
return ch !== "=" && ch !== ";" && ch !== ",";
}
while (pos < cookiesString.length) {
start = pos;
cookiesSeparatorFound = false;
while (skipWhitespace()) {
ch = cookiesString.charAt(pos);
if (ch === ",") {
// ',' is a cookie separator if we have later first '=', not ';' or ','
lastComma = pos;
pos += 1;
skipWhitespace();
nextStart = pos;
while (pos < cookiesString.length && notSpecialChar()) {
pos += 1;
}
// currently special character
if (pos < cookiesString.length && cookiesString.charAt(pos) === "=") {
// we found cookies separator
cookiesSeparatorFound = true;
// pos is inside the next cookie, so back up and return it.
pos = nextStart;
cookiesStrings.push(cookiesString.substring(start, lastComma));
start = pos;
} else {
// in param ',' or param separator ';',
// we continue from that comma
pos = lastComma + 1;
}
} else {
pos += 1;
}
}
if (!cookiesSeparatorFound || pos >= cookiesString.length) {
cookiesStrings.push(cookiesString.substring(start, cookiesString.length));
}
}
return cookiesStrings;
}
function createRedirectionIORequest(request: Request, ip?: string) {
const urlObject = new URL(request.url);
const redirectionioRequest = new redirectionio.Request(
urlObject.pathname + urlObject.search,
urlObject.host,
urlObject.protocol.replace(":", ""),
request.method,
);
request.headers.forEach((value, key) => {
redirectionioRequest.add_header(key, value);
});
if (ip) {
redirectionioRequest.set_remote_ip(ip);
}
return redirectionioRequest;
}
function middlewareResponseToRequest(originalRequest: Request, response: Response, body: ArrayBuffer | null): Request {
let request = originalRequest;
if (response.headers.has("x-middleware-rewrite")) {
const newUrl = response.headers.get("x-middleware-rewrite");
if (newUrl) {
request = new Request(newUrl, {
method: request.method,
headers: request.headers,
body,
});
}
}
if (response.headers.has("x-middleware-override-headers")) {
const headersToOverride = response.headers.get("x-middleware-override-headers");
if (headersToOverride) {
headersToOverride.split(",").forEach((header) => {
const value = response.headers.get("x-middleware-request-" + header);
if (value) {
request.headers.set(header, value);
}
});
}
}
return request;
}
async function fetchRedirectionIOAction(redirectionIORequest: redirectionio.Request) {
try {
const response = (await Promise.race([
fetch("https://agent.redirection.io/" + REDIRECTIONIO_TOKEN + "/action", {
method: "POST",
body: redirectionIORequest.serialize().toString(),
headers: {
"User-Agent": "vercel-edge-middleware/" + REDIRECTIONIO_VERSION,
"x-redirectionio-instance-name": REDIRECTIONIO_INSTANCE_NAME,
},
cache: "no-store",
}),
new Promise((_, reject) => setTimeout(() => reject(new Error("Timeout")), REDIRECTIONIO_TIMEOUT)),
])) as Response;
const actionStr = await response.text();
if (actionStr === "") {
return redirectionio.Action.empty();
}
return new redirectionio.Action(actionStr);
} catch (e) {
console.error(e);
return redirectionio.Action.empty();
}
}
/* Redirection.io logic */
async function proxy(
request: Request,
action: redirectionio.Action,
fetchResponse: FetchResponse,
): Promise<[Response, number]> {
try {
const statusCodeBeforeResponse = action.get_status_code(0);
let response;
if (statusCodeBeforeResponse === 0) {
response = await fetchResponse(request, true);
} else {
response = new Response("", {
status: Number(statusCodeBeforeResponse),
});
}
const backendStatusCode = response.status;
const statusCodeAfterResponse = action.get_status_code(backendStatusCode);
let status = response.status;
if (statusCodeAfterResponse !== 0) {
status = Number(statusCodeAfterResponse);
}
const headerMap = new redirectionio.HeaderMap();
response.headers.forEach((value, key) => {
if (key === "set-cookie") {
const cookies = splitSetCookies(value);
for (const cookie of cookies) {
headerMap.add_header("set-cookie", cookie);
}
} else {
headerMap.add_header(key, value);
}
});
const newHeaderMap = action.filter_headers(headerMap, backendStatusCode, REDIRECTIONIO_ADD_HEADER_RULE_IDS);
const newHeaders = new Headers();
for (let i = 0; i < newHeaderMap.len(); i++) {
const headerName = newHeaderMap.get_header_name(i);
if (headerName && headerName.length > 0) {
newHeaders.append(headerName, newHeaderMap.get_header_value(i));
}
}
response = new Response(response.body, {
status: status,
statusText: response.statusText,
headers: newHeaders,
});
newHeaderMap.remove_header("content-encoding");
const bodyFilter = action.create_body_filter(backendStatusCode, newHeaderMap);
// Skip body filtering
if (bodyFilter.is_null()) {
return [response, response.status];
}
const { readable, writable } = new TransformStream();
createBodyFilter(response.body, writable, bodyFilter);
return [new Response(readable, response), backendStatusCode];
} catch (err) {
console.error(err);
const response = await fetchResponse(request, true);
return [response, response.status];
}
}
async function createBodyFilter(
readable: ReadableStream<Uint8Array> | null,
writable: WritableStream,
bodyFilter: redirectionio.BodyFilter,
) {
const writer = writable.getWriter();
const reader = readable?.getReader();
if (!reader) {
const filteredData = bodyFilter.filter(new Uint8Array());
if (filteredData) {
await writer.write(filteredData);
}
const lastData = bodyFilter.end();
if (lastData) {
await writer.write(lastData);
}
await writer.close();
return;
}
let data = await reader.read();
while (!data.done) {
const filteredData = bodyFilter.filter(data.value);
if (filteredData) {
await writer.write(filteredData);
}
data = await reader.read();
}
const lastData = bodyFilter.end();
if (lastData) {
await writer.write(lastData);
}
await writer.close();
}
async function log(
response: Response,
backendStatusCode: number,
redirectionioRequest: redirectionio.Request,
startTimestamp: number,
action: redirectionio.Action,
clientIP: string | undefined,
) {
if (response === null) {
return;
}
const responseHeaderMap = new redirectionio.HeaderMap();
response.headers.forEach((value, key) => {
responseHeaderMap.add_header(key, value);
});
if (action && !action.should_log_request(backendStatusCode)) {
return;
}
try {
const logAsJson = redirectionio.create_log_in_json(
redirectionioRequest,
response.status,
responseHeaderMap,
action,
"vercel-edge-middleware/" + REDIRECTIONIO_VERSION,
BigInt(startTimestamp),
clientIP ?? "",
);
return await fetch("https://agent.redirection.io/" + REDIRECTIONIO_TOKEN + "/log", {
method: "POST",
body: logAsJson,
headers: {
"User-Agent": "vercel-edge-middleware/" + REDIRECTIONIO_VERSION,
"x-redirectionio-instance-name": REDIRECTIONIO_INSTANCE_NAME,
},
cache: "no-store",
});
} catch (err) {
console.error(err);
}
}