-
Notifications
You must be signed in to change notification settings - Fork 2
/
middleware.js
349 lines (349 loc) · 13.2 KB
/
middleware.js
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
import { next } from "@vercel/edge";
import { ipAddress } from "@vercel/functions";
import * as redirectionio from "@redirection.io/redirectionio";
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,
};
export const createRedirectionIoMiddleware = (config) => {
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) => {
let response = 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, context, config, fetchResponse) {
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) {
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, ip) {
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, response, body) {
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) {
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)),
]);
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, action, fetchResponse) {
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, writable, 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, backendStatusCode, redirectionioRequest, startTimestamp, action, clientIP) {
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);
}
}