-
Notifications
You must be signed in to change notification settings - Fork 230
/
proxy.ts
286 lines (270 loc) · 8.28 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
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
// Copyright 2018-2024 the oak authors. All rights reserved. MIT license.
/** Middleware for oak that allows back-to-back proxies of requests to be
* used.
*
* @module
*/
import type { State } from "../application.ts";
import type { Context } from "../context.ts";
import { parse } from "../forwarded.ts";
import type { Middleware } from "../middleware.ts";
import type {
RouteParams,
RouterContext,
RouterMiddleware,
} from "../router.ts";
import { isRouterContext } from "../util.ts";
type Fetch = (
input: Request,
init: { context: Context },
) => Promise<Response>;
type ProxyMatchFunction<
R extends string,
P extends RouteParams<R> = RouteParams<R>,
// deno-lint-ignore no-explicit-any
S extends State = Record<string, any>,
> = (ctx: Context<S> | RouterContext<R, P, S>) => boolean;
type ProxyMapFunction<R extends string, P extends RouteParams<R>> = (
path: R,
params?: P,
) => R;
type ProxyHeadersFunction<S extends State> = (
ctx: Context<S>,
) => HeadersInit | Promise<HeadersInit>;
type ProxyRouterHeadersFunction<
R extends string,
P extends RouteParams<R>,
S extends State,
> = (ctx: RouterContext<R, P, S>) => HeadersInit | Promise<HeadersInit>;
/** Options which can be specified on the {@linkcode proxy} middleware. */
export interface ProxyOptions<
R extends string,
P extends RouteParams<R> = RouteParams<R>,
// deno-lint-ignore no-explicit-any
S extends State = Record<string, any>,
> {
/** A callback hook that is called after the response is received which allows
* the response content type to be adjusted. This is for situations where the
* content type provided by the proxy server might not be suitable for
* responding with. */
contentType?(
url: string,
contentType?: string,
): Promise<string | undefined> | string | undefined;
/** The fetch function to use to proxy the request. This defaults to the
* global {@linkcode fetch} function. It will always be called with a
* second argument which contains an object of `{ context }` which the
* `context` property will be an instance of {@linkcode RouterContext}.
*
* This is designed for mocking purposes or implementing a `fetch()`
* callback that needs access the current context when it is called. */
fetch?: Fetch;
/** Additional headers that should be set in the response. The value can
* be a headers init value or a function that returns or resolves with a
* headers init value. */
headers?:
| HeadersInit
| ProxyHeadersFunction<S>
| ProxyRouterHeadersFunction<R, P, S>;
/** Either a record or a proxy map function that will allow proxied requests
* being handled by the middleware to be remapped to a different remote
* path. */
map?: Record<string, R> | ProxyMapFunction<R, P>;
/** A string, regular expression or proxy match function what determines if
* the proxy middleware should proxy the request.
*
* If the value is a string the match will be true if the requests pathname
* starts with the string. In the case of a regular expression, if the
* pathname
*/
match?:
| string
| RegExp
| ProxyMatchFunction<R, P, S>;
/** A flag that indicates if traditional proxy headers should be set in the
* response. This defaults to `true`.
*/
proxyHeaders?: boolean;
/** A callback hook which will be called before each proxied fetch request
* to allow the native `Request` to be modified or replaced. */
request?(req: Request): Request | Promise<Request>;
/** A callback hook which will be called after each proxied fetch response
* is received to allow the native `Response` to be modified or replaced. */
response?(res: Response): Response | Promise<Response>;
}
function createMatcher<
R extends string,
P extends RouteParams<R>,
S extends State,
>(
{ match }: ProxyOptions<R, P, S>,
) {
return function matches(ctx: RouterContext<R, P, S>): boolean {
if (!match) {
return true;
}
if (typeof match === "string") {
return ctx.request.url.pathname.startsWith(match);
}
if (match instanceof RegExp) {
return match.test(ctx.request.url.pathname);
}
return match(ctx);
};
}
async function createRequest<
R extends string,
P extends RouteParams<R>,
S extends State,
>(
target: string | URL,
ctx: Context<S> | RouterContext<R, P, S>,
{ headers: optHeaders, map, proxyHeaders = true, request: reqFn }:
ProxyOptions<R, P, S>,
): Promise<Request> {
let path = ctx.request.url.pathname as R;
let params: P | undefined;
if (isRouterContext<R, P, S>(ctx)) {
params = ctx.params;
}
if (map && typeof map === "function") {
path = map(path, params);
} else if (map) {
path = map[path] ?? path;
}
const url = new URL(String(target));
if (url.pathname.endsWith("/") && path.startsWith("/")) {
url.pathname = `${url.pathname}${path.slice(1)}`;
} else if (!url.pathname.endsWith("/") && !path.startsWith("/")) {
url.pathname = `${url.pathname}/${path}`;
} else {
url.pathname = `${url.pathname}${path}`;
}
url.search = ctx.request.url.search;
const body = getBodyInit(ctx);
const headers = new Headers(ctx.request.headers);
if (optHeaders) {
if (typeof optHeaders === "function") {
optHeaders = await optHeaders(ctx as RouterContext<R, P, S>);
}
for (const [key, value] of iterableHeaders(optHeaders)) {
headers.set(key, value);
}
}
if (proxyHeaders) {
const maybeForwarded = headers.get("forwarded");
const ip = ctx.request.ip.startsWith("[")
? `"${ctx.request.ip}"`
: ctx.request.ip;
const host = headers.get("host");
if (maybeForwarded && parse(maybeForwarded)) {
let value = `for=${ip}`;
if (host) {
value += `;host=${host}`;
}
headers.append("forwarded", value);
} else {
headers.append("x-forwarded-for", ip);
if (host) {
headers.append("x-forwarded-host", host);
}
}
}
const init: RequestInit = {
body,
headers,
method: ctx.request.method,
redirect: "follow",
};
let request = new Request(url.toString(), init);
if (reqFn) {
request = await reqFn(request);
}
return request;
}
function getBodyInit<
R extends string,
P extends RouteParams<R>,
S extends State,
>(
ctx: Context<S> | RouterContext<R, P, S>,
): BodyInit | null {
if (!ctx.request.hasBody) {
return null;
}
return ctx.request.body.stream;
}
function iterableHeaders(
headers: HeadersInit,
): IterableIterator<[string, string]> {
if (headers instanceof Headers) {
return headers.entries();
} else if (Array.isArray(headers)) {
return headers.values() as IterableIterator<[string, string]>;
} else {
return Object.entries(headers).values() as IterableIterator<
[string, string]
>;
}
}
async function processResponse<
R extends string,
P extends RouteParams<R>,
S extends State,
>(
response: Response,
ctx: Context<S> | RouterContext<R, P, S>,
{ contentType: contentTypeFn, response: resFn }: ProxyOptions<R, P, S>,
) {
if (resFn) {
response = await resFn(response);
}
if (response.body) {
ctx.response.body = response.body;
} else {
ctx.response.body = null;
}
ctx.response.status = response.status;
for (const [key, value] of response.headers) {
ctx.response.headers.append(key, value);
}
if (contentTypeFn) {
const value = await contentTypeFn(
response.url,
ctx.response.headers.get("content-type") ?? undefined,
);
if (value != null) {
ctx.response.headers.set("content-type", value);
}
}
}
/**
* Middleware that provides a back-to-back proxy for requests.
*
* @param target
* @param options
*/
export function proxy<S extends State>(
target: string | URL,
options?: ProxyOptions<string, RouteParams<string>, S>,
): Middleware<S>;
export function proxy<
R extends string,
P extends RouteParams<R>,
S extends State,
>(
target: string | URL,
options: ProxyOptions<R, P, S> = {},
): RouterMiddleware<R, P, S> {
const matches = createMatcher(options);
return async function proxy(context, next) {
if (!matches(context)) {
return next();
}
const request = await createRequest(target, context, options);
const { fetch = globalThis.fetch } = options;
const response = await fetch(request, { context });
await processResponse(response, context, options);
return next();
};
}