/
proxy.ts
254 lines (232 loc) · 6.1 KB
/
proxy.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
import type { H3Event } from "../event";
import type { H3EventContext, RequestHeaders } from "../types";
import { getRequestHeaders } from "./request";
import { splitCookiesString } from "./cookie";
import { sanitizeStatusMessage, sanitizeStatusCode } from "./sanitize";
import { getRequestWebStream, readRawBody } from "./body";
export type Duplex = "half" | "full";
export interface ProxyOptions {
headers?: RequestHeaders | HeadersInit;
fetchOptions?: RequestInit & { duplex?: Duplex } & {
ignoreResponseError?: boolean;
};
fetch?: typeof fetch;
sendStream?: boolean;
streamRequest?: boolean;
cookieDomainRewrite?: string | Record<string, string>;
cookiePathRewrite?: string | Record<string, string>;
onResponse?: (event: H3Event, response: Response) => void;
}
const PayloadMethods = new Set(["PATCH", "POST", "PUT", "DELETE"]);
const ignoredHeaders = new Set([
"transfer-encoding",
"connection",
"keep-alive",
"upgrade",
"expect",
"host",
"accept",
]);
/**
* Proxy the incoming request to a target URL.
*/
export async function proxyRequest(
event: H3Event,
target: string,
opts: ProxyOptions = {},
) {
// Request Body
let body;
let duplex: Duplex | undefined;
if (PayloadMethods.has(event.method)) {
if (opts.streamRequest) {
body = getRequestWebStream(event);
duplex = "half";
} else {
body = await readRawBody(event, false).catch(() => undefined);
}
}
// Method
const method = opts.fetchOptions?.method || event.method;
// Headers
const fetchHeaders = mergeHeaders(
getProxyRequestHeaders(event),
opts.fetchOptions?.headers,
opts.headers,
);
return sendProxy(event, target, {
...opts,
fetchOptions: {
method,
body,
duplex,
...opts.fetchOptions,
headers: fetchHeaders,
},
});
}
/**
* Make a proxy request to a target URL and send the response back to the client.
*/
export async function sendProxy(
event: H3Event,
target: string,
opts: ProxyOptions = {},
) {
const response = await _getFetch(opts.fetch)(target, {
headers: opts.headers as HeadersInit,
ignoreResponseError: true, // make $ofetch.raw transparent
...opts.fetchOptions,
});
event.node.res.statusCode = sanitizeStatusCode(
response.status,
event.node.res.statusCode,
);
event.node.res.statusMessage = sanitizeStatusMessage(response.statusText);
const cookies: string[] = [];
for (const [key, value] of response.headers.entries()) {
if (key === "content-encoding") {
continue;
}
if (key === "content-length") {
continue;
}
if (key === "set-cookie") {
cookies.push(...splitCookiesString(value));
continue;
}
event.node.res.setHeader(key, value);
}
if (cookies.length > 0) {
event.node.res.setHeader(
"set-cookie",
cookies.map((cookie) => {
if (opts.cookieDomainRewrite) {
cookie = rewriteCookieProperty(
cookie,
opts.cookieDomainRewrite,
"domain",
);
}
if (opts.cookiePathRewrite) {
cookie = rewriteCookieProperty(
cookie,
opts.cookiePathRewrite,
"path",
);
}
return cookie;
}),
);
}
if (opts.onResponse) {
await opts.onResponse(event, response);
}
// Directly send consumed _data
if ((response as any)._data !== undefined) {
return (response as any)._data;
}
// Ensure event is not handled
if (event.handled) {
return;
}
// Send at once
if (opts.sendStream === false) {
const data = new Uint8Array(await response.arrayBuffer());
return event.node.res.end(data);
}
// Send as stream
if (response.body) {
for await (const chunk of response.body as any as AsyncIterable<Uint8Array>) {
event.node.res.write(chunk);
}
}
return event.node.res.end();
}
/**
* Get the request headers object without headers known to cause issues when proxying.
*/
export function getProxyRequestHeaders(event: H3Event) {
const headers = Object.create(null);
const reqHeaders = getRequestHeaders(event);
for (const name in reqHeaders) {
if (!ignoredHeaders.has(name)) {
headers[name] = reqHeaders[name];
}
}
return headers;
}
/**
* Make a fetch request with the event's context and headers.
*/
export function fetchWithEvent<
T = unknown,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
_R = any,
F extends (req: RequestInfo | URL, opts?: any) => any = typeof fetch,
>(
event: H3Event,
req: RequestInfo | URL,
init?: RequestInit & { context?: H3EventContext },
options?: { fetch: F },
): unknown extends T ? ReturnType<F> : T {
return _getFetch(options?.fetch)(req, <RequestInit>{
...init,
context: init?.context || event.context,
headers: {
...getProxyRequestHeaders(event),
...init?.headers,
},
});
}
// -- internal utils --
function _getFetch<T = typeof fetch>(_fetch?: T) {
if (_fetch) {
return _fetch;
}
if (globalThis.fetch) {
return globalThis.fetch;
}
throw new Error(
"fetch is not available. Try importing `node-fetch-native/polyfill` for Node.js.",
);
}
function rewriteCookieProperty(
header: string,
map: string | Record<string, string>,
property: string,
) {
const _map = typeof map === "string" ? { "*": map } : map;
return header.replace(
new RegExp(`(;\\s*${property}=)([^;]+)`, "gi"),
(match, prefix, previousValue) => {
let newValue;
if (previousValue in _map) {
newValue = _map[previousValue];
} else if ("*" in _map) {
newValue = _map["*"];
} else {
return match;
}
return newValue ? prefix + newValue : "";
},
);
}
function mergeHeaders(
defaults: HeadersInit,
...inputs: (HeadersInit | RequestHeaders | undefined)[]
) {
const _inputs = inputs.filter(Boolean) as HeadersInit[];
if (_inputs.length === 0) {
return defaults;
}
const merged = new Headers(defaults);
for (const input of _inputs) {
for (const [key, value] of Object.entries(input!)) {
if (value !== undefined) {
merged.set(key, value);
}
}
}
return merged;
}