-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.ts
More file actions
211 lines (191 loc) · 5 KB
/
proxy.ts
File metadata and controls
211 lines (191 loc) · 5 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
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
import type { H3Event } from "../event";
import type { H3EventContext, RequestHeaders } from "../types";
import { getMethod, getRequestHeaders } from "./request";
import { readRawBody } from "./body";
import { splitCookiesString } from "./cookie";
import { sanitizeStatusMessage, sanitizeStatusCode } from "./sanitize";
export interface ProxyOptions {
headers?: RequestHeaders | HeadersInit;
fetchOptions?: RequestInit;
fetch?: typeof fetch;
sendStream?: 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",
]);
export async function proxyRequest(
event: H3Event,
target: string,
opts: ProxyOptions = {}
) {
// Method
const method = getMethod(event);
// Body
let body;
if (PayloadMethods.has(method)) {
body = await readRawBody(event).catch(() => undefined);
}
// Headers
const headers = getProxyRequestHeaders(event);
if (opts.fetchOptions?.headers) {
Object.assign(headers, opts.fetchOptions.headers);
}
if (opts.headers) {
Object.assign(headers, opts.headers);
}
return sendProxy(event, target, {
...opts,
fetchOptions: {
headers,
method,
body,
...opts.fetchOptions,
},
});
}
export async function sendProxy(
event: H3Event,
target: string,
opts: ProxyOptions = {}
) {
const response = await _getFetch(opts.fetch)(target, {
headers: opts.headers as HeadersInit,
...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();
}
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;
}
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 : "";
}
);
}