@remix-run/fetch-proxy 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +51 -0
- package/dist/fetch-proxy.cjs +223 -0
- package/dist/fetch-proxy.cjs.map +7 -0
- package/dist/fetch-proxy.d.ts +2 -0
- package/dist/fetch-proxy.d.ts.map +1 -0
- package/dist/fetch-proxy.js +200 -0
- package/dist/fetch-proxy.js.map +7 -0
- package/dist/lib/fetch-proxy.d.ts +36 -0
- package/dist/lib/fetch-proxy.d.ts.map +1 -0
- package/package.json +53 -0
- package/src/fetch-proxy.ts +1 -0
- package/src/lib/fetch-proxy.ts +123 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 Michael Jackson
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
# fetch-proxy
|
|
2
|
+
|
|
3
|
+
`fetch-proxy` is an HTTP proxy for the [JavaScript Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API).
|
|
4
|
+
|
|
5
|
+
In the context of servers, an HTTP proxy server is a server that forwards all requests it receives to another server and returns the responses it receives. When you think about it this way, a [`fetch` function](https://developer.mozilla.org/en-US/docs/Web/API/Window/fetch) is like a mini proxy server sitting right there in your code. You send it requests, it goes and talks to some other server, and it gives you back the response it received.
|
|
6
|
+
|
|
7
|
+
`fetch-proxy` allows you to easily create `fetch` functions that act as proxies to "target" servers.
|
|
8
|
+
|
|
9
|
+
## Features
|
|
10
|
+
|
|
11
|
+
- Built on the standard [JavaScript Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)
|
|
12
|
+
- Supports rewriting `Set-Cookie` headers received from target server
|
|
13
|
+
- Supports `X-Forwarded-Proto` and `X-Forwarded-Host` headers
|
|
14
|
+
- Supports custom `fetch` implementations
|
|
15
|
+
|
|
16
|
+
## Installation
|
|
17
|
+
|
|
18
|
+
Install from [npm](https://www.npmjs.com/):
|
|
19
|
+
|
|
20
|
+
```sh
|
|
21
|
+
npm i @remix-run/fetch-proxy
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
## Usage
|
|
25
|
+
|
|
26
|
+
```ts
|
|
27
|
+
import { createFetchProxy } from '@remix-run/fetch-proxy';
|
|
28
|
+
|
|
29
|
+
// Create a proxy that sends all requests through to remix.run
|
|
30
|
+
let proxy = createFetchProxy('https://remix.run');
|
|
31
|
+
|
|
32
|
+
// This fetch handler is probably running as part of your server somewhere...
|
|
33
|
+
function handleFetch(request: Request): Promise<Response> {
|
|
34
|
+
return proxy(request);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// Test it out by manually throwing a Request at it
|
|
38
|
+
let response = await handleFetch(new Request('https://shopify.com'));
|
|
39
|
+
|
|
40
|
+
let text = await response.text();
|
|
41
|
+
let title = text.match(/<title>([^<]+)<\/title>/)[1];
|
|
42
|
+
assert(title.includes('Remix'));
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## Related Packages
|
|
46
|
+
|
|
47
|
+
- [`node-fetch-server`](https://github.com/remix-run/remix/tree/v3/packages/node-fetch-server) - Build HTTP servers for Node.js using the web fetch API
|
|
48
|
+
|
|
49
|
+
## License
|
|
50
|
+
|
|
51
|
+
See [LICENSE](https://github.com/remix-run/remix/blob/v3/LICENSE)
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/fetch-proxy.ts
|
|
21
|
+
var fetch_proxy_exports = {};
|
|
22
|
+
__export(fetch_proxy_exports, {
|
|
23
|
+
createFetchProxy: () => createFetchProxy
|
|
24
|
+
});
|
|
25
|
+
module.exports = __toCommonJS(fetch_proxy_exports);
|
|
26
|
+
|
|
27
|
+
// ../headers/src/lib/param-values.ts
|
|
28
|
+
function parseParams(input, delimiter = ";") {
|
|
29
|
+
let parser = delimiter === ";" ? /(?:^|;)\s*([^=;\s]+)(\s*=\s*(?:"((?:[^"\\]|\\.)*)"|((?:[^;]|\\\;)+))?)?/g : /(?:^|,)\s*([^=,\s]+)(\s*=\s*(?:"((?:[^"\\]|\\.)*)"|((?:[^,]|\\\,)+))?)?/g;
|
|
30
|
+
let params = [];
|
|
31
|
+
let match;
|
|
32
|
+
while ((match = parser.exec(input)) !== null) {
|
|
33
|
+
let key = match[1].trim();
|
|
34
|
+
let value;
|
|
35
|
+
if (match[2]) {
|
|
36
|
+
value = (match[3] || match[4] || "").replace(/\\(.)/g, "$1").trim();
|
|
37
|
+
}
|
|
38
|
+
params.push([key, value]);
|
|
39
|
+
}
|
|
40
|
+
return params;
|
|
41
|
+
}
|
|
42
|
+
function quote(value) {
|
|
43
|
+
if (value.includes('"') || value.includes(";") || value.includes(" ")) {
|
|
44
|
+
return `"${value.replace(/"/g, '\\"')}"`;
|
|
45
|
+
}
|
|
46
|
+
return value;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// ../headers/src/lib/utils.ts
|
|
50
|
+
function capitalize(str) {
|
|
51
|
+
return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
|
|
52
|
+
}
|
|
53
|
+
function isValidDate(date) {
|
|
54
|
+
return date instanceof Date && !isNaN(date.getTime());
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// ../headers/src/lib/set-cookie.ts
|
|
58
|
+
var SetCookie = class {
|
|
59
|
+
domain;
|
|
60
|
+
expires;
|
|
61
|
+
httpOnly;
|
|
62
|
+
maxAge;
|
|
63
|
+
name;
|
|
64
|
+
path;
|
|
65
|
+
sameSite;
|
|
66
|
+
secure;
|
|
67
|
+
value;
|
|
68
|
+
constructor(init) {
|
|
69
|
+
if (init) {
|
|
70
|
+
if (typeof init === "string") {
|
|
71
|
+
let params = parseParams(init);
|
|
72
|
+
if (params.length > 0) {
|
|
73
|
+
this.name = params[0][0];
|
|
74
|
+
this.value = params[0][1];
|
|
75
|
+
for (let [key, value] of params.slice(1)) {
|
|
76
|
+
switch (key.toLowerCase()) {
|
|
77
|
+
case "domain":
|
|
78
|
+
this.domain = value;
|
|
79
|
+
break;
|
|
80
|
+
case "expires": {
|
|
81
|
+
if (typeof value === "string") {
|
|
82
|
+
let date = new Date(value);
|
|
83
|
+
if (isValidDate(date)) {
|
|
84
|
+
this.expires = date;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
break;
|
|
88
|
+
}
|
|
89
|
+
case "httponly":
|
|
90
|
+
this.httpOnly = true;
|
|
91
|
+
break;
|
|
92
|
+
case "max-age": {
|
|
93
|
+
if (typeof value === "string") {
|
|
94
|
+
let v = parseInt(value, 10);
|
|
95
|
+
if (!isNaN(v)) this.maxAge = v;
|
|
96
|
+
}
|
|
97
|
+
break;
|
|
98
|
+
}
|
|
99
|
+
case "path":
|
|
100
|
+
this.path = value;
|
|
101
|
+
break;
|
|
102
|
+
case "samesite":
|
|
103
|
+
if (typeof value === "string" && /strict|lax|none/i.test(value)) {
|
|
104
|
+
this.sameSite = capitalize(value);
|
|
105
|
+
}
|
|
106
|
+
break;
|
|
107
|
+
case "secure":
|
|
108
|
+
this.secure = true;
|
|
109
|
+
break;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
} else {
|
|
114
|
+
this.domain = init.domain;
|
|
115
|
+
this.expires = init.expires;
|
|
116
|
+
this.httpOnly = init.httpOnly;
|
|
117
|
+
this.maxAge = init.maxAge;
|
|
118
|
+
this.name = init.name;
|
|
119
|
+
this.path = init.path;
|
|
120
|
+
this.sameSite = init.sameSite;
|
|
121
|
+
this.secure = init.secure;
|
|
122
|
+
this.value = init.value;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
toString() {
|
|
127
|
+
if (!this.name) {
|
|
128
|
+
return "";
|
|
129
|
+
}
|
|
130
|
+
let parts = [`${this.name}=${quote(this.value || "")}`];
|
|
131
|
+
if (this.domain) {
|
|
132
|
+
parts.push(`Domain=${this.domain}`);
|
|
133
|
+
}
|
|
134
|
+
if (this.path) {
|
|
135
|
+
parts.push(`Path=${this.path}`);
|
|
136
|
+
}
|
|
137
|
+
if (this.expires) {
|
|
138
|
+
parts.push(`Expires=${this.expires.toUTCString()}`);
|
|
139
|
+
}
|
|
140
|
+
if (this.maxAge) {
|
|
141
|
+
parts.push(`Max-Age=${this.maxAge}`);
|
|
142
|
+
}
|
|
143
|
+
if (this.secure) {
|
|
144
|
+
parts.push("Secure");
|
|
145
|
+
}
|
|
146
|
+
if (this.httpOnly) {
|
|
147
|
+
parts.push("HttpOnly");
|
|
148
|
+
}
|
|
149
|
+
if (this.sameSite) {
|
|
150
|
+
parts.push(`SameSite=${this.sameSite}`);
|
|
151
|
+
}
|
|
152
|
+
return parts.join("; ");
|
|
153
|
+
}
|
|
154
|
+
};
|
|
155
|
+
|
|
156
|
+
// src/lib/fetch-proxy.ts
|
|
157
|
+
function createFetchProxy(target, options) {
|
|
158
|
+
let localFetch = options?.fetch ?? globalThis.fetch;
|
|
159
|
+
let rewriteCookieDomain = options?.rewriteCookieDomain ?? true;
|
|
160
|
+
let rewriteCookiePath = options?.rewriteCookiePath ?? true;
|
|
161
|
+
let xForwardedHeaders = options?.xForwardedHeaders ?? false;
|
|
162
|
+
let targetUrl = new URL(target);
|
|
163
|
+
if (targetUrl.pathname.endsWith("/")) {
|
|
164
|
+
targetUrl.pathname = targetUrl.pathname.replace(/\/+$/, "");
|
|
165
|
+
}
|
|
166
|
+
return async (input, init) => {
|
|
167
|
+
let request = new Request(input, init);
|
|
168
|
+
let url = new URL(request.url);
|
|
169
|
+
let proxyUrl = new URL(url.search, targetUrl);
|
|
170
|
+
if (url.pathname !== "/") {
|
|
171
|
+
proxyUrl.pathname = proxyUrl.pathname === "/" ? url.pathname : proxyUrl.pathname + url.pathname;
|
|
172
|
+
}
|
|
173
|
+
let proxyHeaders = new Headers(request.headers);
|
|
174
|
+
if (xForwardedHeaders) {
|
|
175
|
+
proxyHeaders.append("X-Forwarded-Proto", url.protocol.replace(/:$/, ""));
|
|
176
|
+
proxyHeaders.append("X-Forwarded-Host", url.host);
|
|
177
|
+
}
|
|
178
|
+
let proxyInit = {
|
|
179
|
+
method: request.method,
|
|
180
|
+
headers: proxyHeaders,
|
|
181
|
+
cache: request.cache,
|
|
182
|
+
credentials: request.credentials,
|
|
183
|
+
integrity: request.integrity,
|
|
184
|
+
keepalive: request.keepalive,
|
|
185
|
+
mode: request.mode,
|
|
186
|
+
redirect: request.redirect,
|
|
187
|
+
referrer: request.referrer,
|
|
188
|
+
referrerPolicy: request.referrerPolicy,
|
|
189
|
+
signal: request.signal,
|
|
190
|
+
...init
|
|
191
|
+
};
|
|
192
|
+
if (request.method !== "GET" && request.method !== "HEAD") {
|
|
193
|
+
proxyInit.body = request.body;
|
|
194
|
+
proxyInit.duplex = "half";
|
|
195
|
+
}
|
|
196
|
+
let response = await localFetch(proxyUrl, proxyInit);
|
|
197
|
+
let responseHeaders = new Headers(response.headers);
|
|
198
|
+
if (responseHeaders.has("Set-Cookie")) {
|
|
199
|
+
let setCookie = responseHeaders.getSetCookie();
|
|
200
|
+
responseHeaders.delete("Set-Cookie");
|
|
201
|
+
for (let cookie of setCookie) {
|
|
202
|
+
let header = new SetCookie(cookie);
|
|
203
|
+
if (rewriteCookieDomain && header.domain) {
|
|
204
|
+
header.domain = url.host;
|
|
205
|
+
}
|
|
206
|
+
if (rewriteCookiePath && header.path) {
|
|
207
|
+
if (header.path.startsWith(targetUrl.pathname + "/")) {
|
|
208
|
+
header.path = header.path.slice(targetUrl.pathname.length);
|
|
209
|
+
} else if (header.path === targetUrl.pathname) {
|
|
210
|
+
header.path = "/";
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
responseHeaders.append("Set-Cookie", header.toString());
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
return new Response(response.body, {
|
|
217
|
+
status: response.status,
|
|
218
|
+
statusText: response.statusText,
|
|
219
|
+
headers: responseHeaders
|
|
220
|
+
});
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
//# sourceMappingURL=fetch-proxy.cjs.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/fetch-proxy.ts", "../../headers/src/lib/param-values.ts", "../../headers/src/lib/utils.ts", "../../headers/src/lib/set-cookie.ts", "../src/lib/fetch-proxy.ts"],
|
|
4
|
+
"sourcesContent": ["export { type FetchProxyOptions, type FetchProxy, createFetchProxy } from './lib/fetch-proxy.ts';\n", "export function parseParams(\n input: string,\n delimiter: ';' | ',' = ';',\n): [string, string | undefined][] {\n // This parser splits on the delimiter and unquotes any quoted values\n // like `filename=\"the\\\\ filename.txt\"`.\n let parser =\n delimiter === ';'\n ? /(?:^|;)\\s*([^=;\\s]+)(\\s*=\\s*(?:\"((?:[^\"\\\\]|\\\\.)*)\"|((?:[^;]|\\\\\\;)+))?)?/g\n : /(?:^|,)\\s*([^=,\\s]+)(\\s*=\\s*(?:\"((?:[^\"\\\\]|\\\\.)*)\"|((?:[^,]|\\\\\\,)+))?)?/g;\n\n let params: [string, string | undefined][] = [];\n\n let match;\n while ((match = parser.exec(input)) !== null) {\n let key = match[1].trim();\n\n let value: string | undefined;\n if (match[2]) {\n value = (match[3] || match[4] || '').replace(/\\\\(.)/g, '$1').trim();\n }\n\n params.push([key, value]);\n }\n\n return params;\n}\n\nexport function quote(value: string): string {\n if (value.includes('\"') || value.includes(';') || value.includes(' ')) {\n return `\"${value.replace(/\"/g, '\\\\\"')}\"`;\n }\n return value;\n}\n", "export function capitalize(str: string): string {\n return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();\n}\n\nexport function isIterable<T>(value: any): value is Iterable<T> {\n return value != null && typeof value[Symbol.iterator] === 'function';\n}\n\nexport function isValidDate(date: unknown): boolean {\n return date instanceof Date && !isNaN(date.getTime());\n}\n\nexport function quoteEtag(tag: string): string {\n return tag === '*' ? tag : /^(W\\/)?\".*\"$/.test(tag) ? tag : `\"${tag}\"`;\n}\n", "import { type HeaderValue } from './header-value.ts';\nimport { parseParams, quote } from './param-values.ts';\nimport { capitalize, isValidDate } from './utils.ts';\n\ntype SameSiteValue = 'Strict' | 'Lax' | 'None';\n\nexport interface SetCookieInit {\n /**\n * The domain of the cookie. For example, `example.com`.\n *\n * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#domaindomain-value)\n */\n domain?: string;\n /**\n * The expiration date of the cookie. If not specified, the cookie is a session cookie.\n *\n * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#expiresdate)\n */\n expires?: Date;\n /**\n * Indicates this cookie should not be accessible via JavaScript.\n *\n * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#httponly)\n */\n httpOnly?: true;\n /**\n * The maximum age of the cookie in seconds.\n *\n * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#max-age)\n */\n maxAge?: number;\n /**\n * The name of the cookie.\n *\n * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#cookie-namecookie-value)\n */\n name?: string;\n /**\n * The path of the cookie. For example, `/` or `/admin`.\n *\n * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#pathpath-value)\n */\n path?: string;\n /**\n * The `SameSite` attribute of the cookie. This attribute lets servers require that a cookie shouldn't be sent with\n * cross-site requests, which provides some protection against cross-site request forgery attacks.\n *\n * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#samesitesamesite-value)\n */\n sameSite?: SameSiteValue;\n /**\n * Indicates the cookie should only be sent over HTTPS.\n *\n * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#secure)\n */\n secure?: true;\n /**\n * The value of the cookie.\n *\n * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#cookie-namecookie-value)\n */\n value?: string;\n}\n\n/**\n * The value of a `Set-Cookie` HTTP header.\n *\n * [MDN `Set-Cookie` Reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie)\n *\n * [HTTP/1.1 Specification](https://datatracker.ietf.org/doc/html/rfc6265#section-4.1)\n */\nexport class SetCookie implements HeaderValue, SetCookieInit {\n domain?: string;\n expires?: Date;\n httpOnly?: true;\n maxAge?: number;\n name?: string;\n path?: string;\n sameSite?: SameSiteValue;\n secure?: true;\n value?: string;\n\n constructor(init?: string | SetCookieInit) {\n if (init) {\n if (typeof init === 'string') {\n let params = parseParams(init);\n if (params.length > 0) {\n this.name = params[0][0];\n this.value = params[0][1];\n\n for (let [key, value] of params.slice(1)) {\n switch (key.toLowerCase()) {\n case 'domain':\n this.domain = value;\n break;\n case 'expires': {\n if (typeof value === 'string') {\n let date = new Date(value);\n if (isValidDate(date)) {\n this.expires = date;\n }\n }\n break;\n }\n case 'httponly':\n this.httpOnly = true;\n break;\n case 'max-age': {\n if (typeof value === 'string') {\n let v = parseInt(value, 10);\n if (!isNaN(v)) this.maxAge = v;\n }\n break;\n }\n case 'path':\n this.path = value;\n break;\n case 'samesite':\n if (typeof value === 'string' && /strict|lax|none/i.test(value)) {\n this.sameSite = capitalize(value) as SameSiteValue;\n }\n break;\n case 'secure':\n this.secure = true;\n break;\n }\n }\n }\n } else {\n this.domain = init.domain;\n this.expires = init.expires;\n this.httpOnly = init.httpOnly;\n this.maxAge = init.maxAge;\n this.name = init.name;\n this.path = init.path;\n this.sameSite = init.sameSite;\n this.secure = init.secure;\n this.value = init.value;\n }\n }\n }\n\n toString(): string {\n if (!this.name) {\n return '';\n }\n\n let parts = [`${this.name}=${quote(this.value || '')}`];\n\n if (this.domain) {\n parts.push(`Domain=${this.domain}`);\n }\n if (this.path) {\n parts.push(`Path=${this.path}`);\n }\n if (this.expires) {\n parts.push(`Expires=${this.expires.toUTCString()}`);\n }\n if (this.maxAge) {\n parts.push(`Max-Age=${this.maxAge}`);\n }\n if (this.secure) {\n parts.push('Secure');\n }\n if (this.httpOnly) {\n parts.push('HttpOnly');\n }\n if (this.sameSite) {\n parts.push(`SameSite=${this.sameSite}`);\n }\n\n return parts.join('; ');\n }\n}\n", "import { SetCookie } from '@remix-run/headers';\n\nexport interface FetchProxyOptions {\n /**\n * The `fetch` function to use for the actual fetch. Defaults to the global `fetch` function.\n */\n fetch?: typeof globalThis.fetch;\n /**\n * Set `false` to prevent the `Domain` attribute of `Set-Cookie` headers from being rewritten. By\n * default the domain will be rewritten to the domain of the incoming request.\n */\n rewriteCookieDomain?: boolean;\n /**\n * Set `false` to prevent the `Path` attribute of `Set-Cookie` headers from being rewritten. By\n * default the portion of the pathname that matches the proxy target's pathname will be removed.\n */\n rewriteCookiePath?: boolean;\n /**\n * Set `true` to add `X-Forwarded-Proto` and `X-Forwarded-Host` headers to the proxied request.\n * Defaults to `false`.\n */\n xForwardedHeaders?: boolean;\n}\n\n/**\n * A [`fetch` function](https://developer.mozilla.org/en-US/docs/Web/API/Window/fetch)\n * that forwards requests to another server.\n */\nexport interface FetchProxy {\n (input: URL | RequestInfo, init?: RequestInit): Promise<Response>;\n}\n\n/**\n * Creates a `fetch` function that forwards requests to another server.\n * @param target The URL of the server to proxy requests to\n * @param options Options to customize the behavior of the proxy\n * @returns A fetch function that forwards requests to the target server\n */\nexport function createFetchProxy(target: string | URL, options?: FetchProxyOptions): FetchProxy {\n let localFetch = options?.fetch ?? globalThis.fetch;\n let rewriteCookieDomain = options?.rewriteCookieDomain ?? true;\n let rewriteCookiePath = options?.rewriteCookiePath ?? true;\n let xForwardedHeaders = options?.xForwardedHeaders ?? false;\n\n let targetUrl = new URL(target);\n if (targetUrl.pathname.endsWith('/')) {\n targetUrl.pathname = targetUrl.pathname.replace(/\\/+$/, '');\n }\n\n return async (input: URL | RequestInfo, init?: RequestInit) => {\n let request = new Request(input, init);\n let url = new URL(request.url);\n\n let proxyUrl = new URL(url.search, targetUrl);\n if (url.pathname !== '/') {\n proxyUrl.pathname =\n proxyUrl.pathname === '/' ? url.pathname : proxyUrl.pathname + url.pathname;\n }\n\n let proxyHeaders = new Headers(request.headers);\n if (xForwardedHeaders) {\n proxyHeaders.append('X-Forwarded-Proto', url.protocol.replace(/:$/, ''));\n proxyHeaders.append('X-Forwarded-Host', url.host);\n }\n\n let proxyInit: RequestInit = {\n method: request.method,\n headers: proxyHeaders,\n cache: request.cache,\n credentials: request.credentials,\n integrity: request.integrity,\n keepalive: request.keepalive,\n mode: request.mode,\n redirect: request.redirect,\n referrer: request.referrer,\n referrerPolicy: request.referrerPolicy,\n signal: request.signal,\n ...init,\n };\n if (request.method !== 'GET' && request.method !== 'HEAD') {\n proxyInit.body = request.body;\n\n // init.duplex = 'half' must be set when body is a ReadableStream, and Node follows the spec.\n // However, this property is not defined in the TypeScript types for RequestInit, so we have\n // to cast it here in order to set it without a type error.\n // See https://fetch.spec.whatwg.org/#dom-requestinit-duplex\n (proxyInit as { duplex: 'half' }).duplex = 'half';\n }\n\n let response = await localFetch(proxyUrl, proxyInit);\n let responseHeaders = new Headers(response.headers);\n\n if (responseHeaders.has('Set-Cookie')) {\n let setCookie = responseHeaders.getSetCookie();\n\n responseHeaders.delete('Set-Cookie');\n\n for (let cookie of setCookie) {\n let header = new SetCookie(cookie);\n\n if (rewriteCookieDomain && header.domain) {\n header.domain = url.host;\n }\n\n if (rewriteCookiePath && header.path) {\n if (header.path.startsWith(targetUrl.pathname + '/')) {\n header.path = header.path.slice(targetUrl.pathname.length);\n } else if (header.path === targetUrl.pathname) {\n header.path = '/';\n }\n }\n\n responseHeaders.append('Set-Cookie', header.toString());\n }\n }\n\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers: responseHeaders,\n });\n };\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAO,SAAS,YACd,OACA,YAAuB,KACS;AAGhC,MAAI,SACF,cAAc,MACV,6EACA;AAEN,MAAI,SAAyC,CAAC;AAE9C,MAAI;AACJ,UAAQ,QAAQ,OAAO,KAAK,KAAK,OAAO,MAAM;AAC5C,QAAI,MAAM,MAAM,CAAC,EAAE,KAAK;AAExB,QAAI;AACJ,QAAI,MAAM,CAAC,GAAG;AACZ,eAAS,MAAM,CAAC,KAAK,MAAM,CAAC,KAAK,IAAI,QAAQ,UAAU,IAAI,EAAE,KAAK;AAAA,IACpE;AAEA,WAAO,KAAK,CAAC,KAAK,KAAK,CAAC;AAAA,EAC1B;AAEA,SAAO;AACT;AAEO,SAAS,MAAM,OAAuB;AAC3C,MAAI,MAAM,SAAS,GAAG,KAAK,MAAM,SAAS,GAAG,KAAK,MAAM,SAAS,GAAG,GAAG;AACrE,WAAO,IAAI,MAAM,QAAQ,MAAM,KAAK,CAAC;AAAA,EACvC;AACA,SAAO;AACT;;;ACjCO,SAAS,WAAW,KAAqB;AAC9C,SAAO,IAAI,OAAO,CAAC,EAAE,YAAY,IAAI,IAAI,MAAM,CAAC,EAAE,YAAY;AAChE;AAMO,SAAS,YAAY,MAAwB;AAClD,SAAO,gBAAgB,QAAQ,CAAC,MAAM,KAAK,QAAQ,CAAC;AACtD;;;AC6DO,IAAM,YAAN,MAAsD;AAAA,EAC3D;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA,YAAY,MAA+B;AACzC,QAAI,MAAM;AACR,UAAI,OAAO,SAAS,UAAU;AAC5B,YAAI,SAAS,YAAY,IAAI;AAC7B,YAAI,OAAO,SAAS,GAAG;AACrB,eAAK,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SAAS,SAAS,MAAM;AAAA,MACjC,QAAQ,SAAS;AAAA,MACjB,YAAY,SAAS;AAAA,MACrB,SAAS;AAAA,IACX,CAAC;AAAA,EACH;AACF;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fetch-proxy.d.ts","sourceRoot":"","sources":["../src/fetch-proxy.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,iBAAiB,EAAE,KAAK,UAAU,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC"}
|
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
// ../headers/src/lib/param-values.ts
|
|
2
|
+
function parseParams(input, delimiter = ";") {
|
|
3
|
+
let parser = delimiter === ";" ? /(?:^|;)\s*([^=;\s]+)(\s*=\s*(?:"((?:[^"\\]|\\.)*)"|((?:[^;]|\\\;)+))?)?/g : /(?:^|,)\s*([^=,\s]+)(\s*=\s*(?:"((?:[^"\\]|\\.)*)"|((?:[^,]|\\\,)+))?)?/g;
|
|
4
|
+
let params = [];
|
|
5
|
+
let match;
|
|
6
|
+
while ((match = parser.exec(input)) !== null) {
|
|
7
|
+
let key = match[1].trim();
|
|
8
|
+
let value;
|
|
9
|
+
if (match[2]) {
|
|
10
|
+
value = (match[3] || match[4] || "").replace(/\\(.)/g, "$1").trim();
|
|
11
|
+
}
|
|
12
|
+
params.push([key, value]);
|
|
13
|
+
}
|
|
14
|
+
return params;
|
|
15
|
+
}
|
|
16
|
+
function quote(value) {
|
|
17
|
+
if (value.includes('"') || value.includes(";") || value.includes(" ")) {
|
|
18
|
+
return `"${value.replace(/"/g, '\\"')}"`;
|
|
19
|
+
}
|
|
20
|
+
return value;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// ../headers/src/lib/utils.ts
|
|
24
|
+
function capitalize(str) {
|
|
25
|
+
return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
|
|
26
|
+
}
|
|
27
|
+
function isValidDate(date) {
|
|
28
|
+
return date instanceof Date && !isNaN(date.getTime());
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// ../headers/src/lib/set-cookie.ts
|
|
32
|
+
var SetCookie = class {
|
|
33
|
+
domain;
|
|
34
|
+
expires;
|
|
35
|
+
httpOnly;
|
|
36
|
+
maxAge;
|
|
37
|
+
name;
|
|
38
|
+
path;
|
|
39
|
+
sameSite;
|
|
40
|
+
secure;
|
|
41
|
+
value;
|
|
42
|
+
constructor(init) {
|
|
43
|
+
if (init) {
|
|
44
|
+
if (typeof init === "string") {
|
|
45
|
+
let params = parseParams(init);
|
|
46
|
+
if (params.length > 0) {
|
|
47
|
+
this.name = params[0][0];
|
|
48
|
+
this.value = params[0][1];
|
|
49
|
+
for (let [key, value] of params.slice(1)) {
|
|
50
|
+
switch (key.toLowerCase()) {
|
|
51
|
+
case "domain":
|
|
52
|
+
this.domain = value;
|
|
53
|
+
break;
|
|
54
|
+
case "expires": {
|
|
55
|
+
if (typeof value === "string") {
|
|
56
|
+
let date = new Date(value);
|
|
57
|
+
if (isValidDate(date)) {
|
|
58
|
+
this.expires = date;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
break;
|
|
62
|
+
}
|
|
63
|
+
case "httponly":
|
|
64
|
+
this.httpOnly = true;
|
|
65
|
+
break;
|
|
66
|
+
case "max-age": {
|
|
67
|
+
if (typeof value === "string") {
|
|
68
|
+
let v = parseInt(value, 10);
|
|
69
|
+
if (!isNaN(v)) this.maxAge = v;
|
|
70
|
+
}
|
|
71
|
+
break;
|
|
72
|
+
}
|
|
73
|
+
case "path":
|
|
74
|
+
this.path = value;
|
|
75
|
+
break;
|
|
76
|
+
case "samesite":
|
|
77
|
+
if (typeof value === "string" && /strict|lax|none/i.test(value)) {
|
|
78
|
+
this.sameSite = capitalize(value);
|
|
79
|
+
}
|
|
80
|
+
break;
|
|
81
|
+
case "secure":
|
|
82
|
+
this.secure = true;
|
|
83
|
+
break;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
} else {
|
|
88
|
+
this.domain = init.domain;
|
|
89
|
+
this.expires = init.expires;
|
|
90
|
+
this.httpOnly = init.httpOnly;
|
|
91
|
+
this.maxAge = init.maxAge;
|
|
92
|
+
this.name = init.name;
|
|
93
|
+
this.path = init.path;
|
|
94
|
+
this.sameSite = init.sameSite;
|
|
95
|
+
this.secure = init.secure;
|
|
96
|
+
this.value = init.value;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
toString() {
|
|
101
|
+
if (!this.name) {
|
|
102
|
+
return "";
|
|
103
|
+
}
|
|
104
|
+
let parts = [`${this.name}=${quote(this.value || "")}`];
|
|
105
|
+
if (this.domain) {
|
|
106
|
+
parts.push(`Domain=${this.domain}`);
|
|
107
|
+
}
|
|
108
|
+
if (this.path) {
|
|
109
|
+
parts.push(`Path=${this.path}`);
|
|
110
|
+
}
|
|
111
|
+
if (this.expires) {
|
|
112
|
+
parts.push(`Expires=${this.expires.toUTCString()}`);
|
|
113
|
+
}
|
|
114
|
+
if (this.maxAge) {
|
|
115
|
+
parts.push(`Max-Age=${this.maxAge}`);
|
|
116
|
+
}
|
|
117
|
+
if (this.secure) {
|
|
118
|
+
parts.push("Secure");
|
|
119
|
+
}
|
|
120
|
+
if (this.httpOnly) {
|
|
121
|
+
parts.push("HttpOnly");
|
|
122
|
+
}
|
|
123
|
+
if (this.sameSite) {
|
|
124
|
+
parts.push(`SameSite=${this.sameSite}`);
|
|
125
|
+
}
|
|
126
|
+
return parts.join("; ");
|
|
127
|
+
}
|
|
128
|
+
};
|
|
129
|
+
|
|
130
|
+
// src/lib/fetch-proxy.ts
|
|
131
|
+
function createFetchProxy(target, options) {
|
|
132
|
+
let localFetch = options?.fetch ?? globalThis.fetch;
|
|
133
|
+
let rewriteCookieDomain = options?.rewriteCookieDomain ?? true;
|
|
134
|
+
let rewriteCookiePath = options?.rewriteCookiePath ?? true;
|
|
135
|
+
let xForwardedHeaders = options?.xForwardedHeaders ?? false;
|
|
136
|
+
let targetUrl = new URL(target);
|
|
137
|
+
if (targetUrl.pathname.endsWith("/")) {
|
|
138
|
+
targetUrl.pathname = targetUrl.pathname.replace(/\/+$/, "");
|
|
139
|
+
}
|
|
140
|
+
return async (input, init) => {
|
|
141
|
+
let request = new Request(input, init);
|
|
142
|
+
let url = new URL(request.url);
|
|
143
|
+
let proxyUrl = new URL(url.search, targetUrl);
|
|
144
|
+
if (url.pathname !== "/") {
|
|
145
|
+
proxyUrl.pathname = proxyUrl.pathname === "/" ? url.pathname : proxyUrl.pathname + url.pathname;
|
|
146
|
+
}
|
|
147
|
+
let proxyHeaders = new Headers(request.headers);
|
|
148
|
+
if (xForwardedHeaders) {
|
|
149
|
+
proxyHeaders.append("X-Forwarded-Proto", url.protocol.replace(/:$/, ""));
|
|
150
|
+
proxyHeaders.append("X-Forwarded-Host", url.host);
|
|
151
|
+
}
|
|
152
|
+
let proxyInit = {
|
|
153
|
+
method: request.method,
|
|
154
|
+
headers: proxyHeaders,
|
|
155
|
+
cache: request.cache,
|
|
156
|
+
credentials: request.credentials,
|
|
157
|
+
integrity: request.integrity,
|
|
158
|
+
keepalive: request.keepalive,
|
|
159
|
+
mode: request.mode,
|
|
160
|
+
redirect: request.redirect,
|
|
161
|
+
referrer: request.referrer,
|
|
162
|
+
referrerPolicy: request.referrerPolicy,
|
|
163
|
+
signal: request.signal,
|
|
164
|
+
...init
|
|
165
|
+
};
|
|
166
|
+
if (request.method !== "GET" && request.method !== "HEAD") {
|
|
167
|
+
proxyInit.body = request.body;
|
|
168
|
+
proxyInit.duplex = "half";
|
|
169
|
+
}
|
|
170
|
+
let response = await localFetch(proxyUrl, proxyInit);
|
|
171
|
+
let responseHeaders = new Headers(response.headers);
|
|
172
|
+
if (responseHeaders.has("Set-Cookie")) {
|
|
173
|
+
let setCookie = responseHeaders.getSetCookie();
|
|
174
|
+
responseHeaders.delete("Set-Cookie");
|
|
175
|
+
for (let cookie of setCookie) {
|
|
176
|
+
let header = new SetCookie(cookie);
|
|
177
|
+
if (rewriteCookieDomain && header.domain) {
|
|
178
|
+
header.domain = url.host;
|
|
179
|
+
}
|
|
180
|
+
if (rewriteCookiePath && header.path) {
|
|
181
|
+
if (header.path.startsWith(targetUrl.pathname + "/")) {
|
|
182
|
+
header.path = header.path.slice(targetUrl.pathname.length);
|
|
183
|
+
} else if (header.path === targetUrl.pathname) {
|
|
184
|
+
header.path = "/";
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
responseHeaders.append("Set-Cookie", header.toString());
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
return new Response(response.body, {
|
|
191
|
+
status: response.status,
|
|
192
|
+
statusText: response.statusText,
|
|
193
|
+
headers: responseHeaders
|
|
194
|
+
});
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
export {
|
|
198
|
+
createFetchProxy
|
|
199
|
+
};
|
|
200
|
+
//# sourceMappingURL=fetch-proxy.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../headers/src/lib/param-values.ts", "../../headers/src/lib/utils.ts", "../../headers/src/lib/set-cookie.ts", "../src/lib/fetch-proxy.ts"],
|
|
4
|
+
"sourcesContent": ["export function parseParams(\n input: string,\n delimiter: ';' | ',' = ';',\n): [string, string | undefined][] {\n // This parser splits on the delimiter and unquotes any quoted values\n // like `filename=\"the\\\\ filename.txt\"`.\n let parser =\n delimiter === ';'\n ? /(?:^|;)\\s*([^=;\\s]+)(\\s*=\\s*(?:\"((?:[^\"\\\\]|\\\\.)*)\"|((?:[^;]|\\\\\\;)+))?)?/g\n : /(?:^|,)\\s*([^=,\\s]+)(\\s*=\\s*(?:\"((?:[^\"\\\\]|\\\\.)*)\"|((?:[^,]|\\\\\\,)+))?)?/g;\n\n let params: [string, string | undefined][] = [];\n\n let match;\n while ((match = parser.exec(input)) !== null) {\n let key = match[1].trim();\n\n let value: string | undefined;\n if (match[2]) {\n value = (match[3] || match[4] || '').replace(/\\\\(.)/g, '$1').trim();\n }\n\n params.push([key, value]);\n }\n\n return params;\n}\n\nexport function quote(value: string): string {\n if (value.includes('\"') || value.includes(';') || value.includes(' ')) {\n return `\"${value.replace(/\"/g, '\\\\\"')}\"`;\n }\n return value;\n}\n", "export function capitalize(str: string): string {\n return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();\n}\n\nexport function isIterable<T>(value: any): value is Iterable<T> {\n return value != null && typeof value[Symbol.iterator] === 'function';\n}\n\nexport function isValidDate(date: unknown): boolean {\n return date instanceof Date && !isNaN(date.getTime());\n}\n\nexport function quoteEtag(tag: string): string {\n return tag === '*' ? tag : /^(W\\/)?\".*\"$/.test(tag) ? tag : `\"${tag}\"`;\n}\n", "import { type HeaderValue } from './header-value.ts';\nimport { parseParams, quote } from './param-values.ts';\nimport { capitalize, isValidDate } from './utils.ts';\n\ntype SameSiteValue = 'Strict' | 'Lax' | 'None';\n\nexport interface SetCookieInit {\n /**\n * The domain of the cookie. For example, `example.com`.\n *\n * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#domaindomain-value)\n */\n domain?: string;\n /**\n * The expiration date of the cookie. If not specified, the cookie is a session cookie.\n *\n * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#expiresdate)\n */\n expires?: Date;\n /**\n * Indicates this cookie should not be accessible via JavaScript.\n *\n * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#httponly)\n */\n httpOnly?: true;\n /**\n * The maximum age of the cookie in seconds.\n *\n * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#max-age)\n */\n maxAge?: number;\n /**\n * The name of the cookie.\n *\n * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#cookie-namecookie-value)\n */\n name?: string;\n /**\n * The path of the cookie. For example, `/` or `/admin`.\n *\n * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#pathpath-value)\n */\n path?: string;\n /**\n * The `SameSite` attribute of the cookie. This attribute lets servers require that a cookie shouldn't be sent with\n * cross-site requests, which provides some protection against cross-site request forgery attacks.\n *\n * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#samesitesamesite-value)\n */\n sameSite?: SameSiteValue;\n /**\n * Indicates the cookie should only be sent over HTTPS.\n *\n * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#secure)\n */\n secure?: true;\n /**\n * The value of the cookie.\n *\n * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#cookie-namecookie-value)\n */\n value?: string;\n}\n\n/**\n * The value of a `Set-Cookie` HTTP header.\n *\n * [MDN `Set-Cookie` Reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie)\n *\n * [HTTP/1.1 Specification](https://datatracker.ietf.org/doc/html/rfc6265#section-4.1)\n */\nexport class SetCookie implements HeaderValue, SetCookieInit {\n domain?: string;\n expires?: Date;\n httpOnly?: true;\n maxAge?: number;\n name?: string;\n path?: string;\n sameSite?: SameSiteValue;\n secure?: true;\n value?: string;\n\n constructor(init?: string | SetCookieInit) {\n if (init) {\n if (typeof init === 'string') {\n let params = parseParams(init);\n if (params.length > 0) {\n this.name = params[0][0];\n this.value = params[0][1];\n\n for (let [key, value] of params.slice(1)) {\n switch (key.toLowerCase()) {\n case 'domain':\n this.domain = value;\n break;\n case 'expires': {\n if (typeof value === 'string') {\n let date = new Date(value);\n if (isValidDate(date)) {\n this.expires = date;\n }\n }\n break;\n }\n case 'httponly':\n this.httpOnly = true;\n break;\n case 'max-age': {\n if (typeof value === 'string') {\n let v = parseInt(value, 10);\n if (!isNaN(v)) this.maxAge = v;\n }\n break;\n }\n case 'path':\n this.path = value;\n break;\n case 'samesite':\n if (typeof value === 'string' && /strict|lax|none/i.test(value)) {\n this.sameSite = capitalize(value) as SameSiteValue;\n }\n break;\n case 'secure':\n this.secure = true;\n break;\n }\n }\n }\n } else {\n this.domain = init.domain;\n this.expires = init.expires;\n this.httpOnly = init.httpOnly;\n this.maxAge = init.maxAge;\n this.name = init.name;\n this.path = init.path;\n this.sameSite = init.sameSite;\n this.secure = init.secure;\n this.value = init.value;\n }\n }\n }\n\n toString(): string {\n if (!this.name) {\n return '';\n }\n\n let parts = [`${this.name}=${quote(this.value || '')}`];\n\n if (this.domain) {\n parts.push(`Domain=${this.domain}`);\n }\n if (this.path) {\n parts.push(`Path=${this.path}`);\n }\n if (this.expires) {\n parts.push(`Expires=${this.expires.toUTCString()}`);\n }\n if (this.maxAge) {\n parts.push(`Max-Age=${this.maxAge}`);\n }\n if (this.secure) {\n parts.push('Secure');\n }\n if (this.httpOnly) {\n parts.push('HttpOnly');\n }\n if (this.sameSite) {\n parts.push(`SameSite=${this.sameSite}`);\n }\n\n return parts.join('; ');\n }\n}\n", "import { SetCookie } from '@remix-run/headers';\n\nexport interface FetchProxyOptions {\n /**\n * The `fetch` function to use for the actual fetch. Defaults to the global `fetch` function.\n */\n fetch?: typeof globalThis.fetch;\n /**\n * Set `false` to prevent the `Domain` attribute of `Set-Cookie` headers from being rewritten. By\n * default the domain will be rewritten to the domain of the incoming request.\n */\n rewriteCookieDomain?: boolean;\n /**\n * Set `false` to prevent the `Path` attribute of `Set-Cookie` headers from being rewritten. By\n * default the portion of the pathname that matches the proxy target's pathname will be removed.\n */\n rewriteCookiePath?: boolean;\n /**\n * Set `true` to add `X-Forwarded-Proto` and `X-Forwarded-Host` headers to the proxied request.\n * Defaults to `false`.\n */\n xForwardedHeaders?: boolean;\n}\n\n/**\n * A [`fetch` function](https://developer.mozilla.org/en-US/docs/Web/API/Window/fetch)\n * that forwards requests to another server.\n */\nexport interface FetchProxy {\n (input: URL | RequestInfo, init?: RequestInit): Promise<Response>;\n}\n\n/**\n * Creates a `fetch` function that forwards requests to another server.\n * @param target The URL of the server to proxy requests to\n * @param options Options to customize the behavior of the proxy\n * @returns A fetch function that forwards requests to the target server\n */\nexport function createFetchProxy(target: string | URL, options?: FetchProxyOptions): FetchProxy {\n let localFetch = options?.fetch ?? globalThis.fetch;\n let rewriteCookieDomain = options?.rewriteCookieDomain ?? true;\n let rewriteCookiePath = options?.rewriteCookiePath ?? true;\n let xForwardedHeaders = options?.xForwardedHeaders ?? false;\n\n let targetUrl = new URL(target);\n if (targetUrl.pathname.endsWith('/')) {\n targetUrl.pathname = targetUrl.pathname.replace(/\\/+$/, '');\n }\n\n return async (input: URL | RequestInfo, init?: RequestInit) => {\n let request = new Request(input, init);\n let url = new URL(request.url);\n\n let proxyUrl = new URL(url.search, targetUrl);\n if (url.pathname !== '/') {\n proxyUrl.pathname =\n proxyUrl.pathname === '/' ? url.pathname : proxyUrl.pathname + url.pathname;\n }\n\n let proxyHeaders = new Headers(request.headers);\n if (xForwardedHeaders) {\n proxyHeaders.append('X-Forwarded-Proto', url.protocol.replace(/:$/, ''));\n proxyHeaders.append('X-Forwarded-Host', url.host);\n }\n\n let proxyInit: RequestInit = {\n method: request.method,\n headers: proxyHeaders,\n cache: request.cache,\n credentials: request.credentials,\n integrity: request.integrity,\n keepalive: request.keepalive,\n mode: request.mode,\n redirect: request.redirect,\n referrer: request.referrer,\n referrerPolicy: request.referrerPolicy,\n signal: request.signal,\n ...init,\n };\n if (request.method !== 'GET' && request.method !== 'HEAD') {\n proxyInit.body = request.body;\n\n // init.duplex = 'half' must be set when body is a ReadableStream, and Node follows the spec.\n // However, this property is not defined in the TypeScript types for RequestInit, so we have\n // to cast it here in order to set it without a type error.\n // See https://fetch.spec.whatwg.org/#dom-requestinit-duplex\n (proxyInit as { duplex: 'half' }).duplex = 'half';\n }\n\n let response = await localFetch(proxyUrl, proxyInit);\n let responseHeaders = new Headers(response.headers);\n\n if (responseHeaders.has('Set-Cookie')) {\n let setCookie = responseHeaders.getSetCookie();\n\n responseHeaders.delete('Set-Cookie');\n\n for (let cookie of setCookie) {\n let header = new SetCookie(cookie);\n\n if (rewriteCookieDomain && header.domain) {\n header.domain = url.host;\n }\n\n if (rewriteCookiePath && header.path) {\n if (header.path.startsWith(targetUrl.pathname + '/')) {\n header.path = header.path.slice(targetUrl.pathname.length);\n } else if (header.path === targetUrl.pathname) {\n header.path = '/';\n }\n }\n\n responseHeaders.append('Set-Cookie', header.toString());\n }\n }\n\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers: responseHeaders,\n });\n };\n}\n"],
|
|
5
|
+
"mappings": ";AAAO,SAAS,YACd,OACA,YAAuB,KACS;AAGhC,MAAI,SACF,cAAc,MACV,6EACA;AAEN,MAAI,SAAyC,CAAC;AAE9C,MAAI;AACJ,UAAQ,QAAQ,OAAO,KAAK,KAAK,OAAO,MAAM;AAC5C,QAAI,MAAM,MAAM,CAAC,EAAE,KAAK;AAExB,QAAI;AACJ,QAAI,MAAM,CAAC,GAAG;AACZ,eAAS,MAAM,CAAC,KAAK,MAAM,CAAC,KAAK,IAAI,QAAQ,UAAU,IAAI,EAAE,KAAK;AAAA,IACpE;AAEA,WAAO,KAAK,CAAC,KAAK,KAAK,CAAC;AAAA,EAC1B;AAEA,SAAO;AACT;AAEO,SAAS,MAAM,OAAuB;AAC3C,MAAI,MAAM,SAAS,GAAG,KAAK,MAAM,SAAS,GAAG,KAAK,MAAM,SAAS,GAAG,GAAG;AACrE,WAAO,IAAI,MAAM,QAAQ,MAAM,KAAK,CAAC;AAAA,EACvC;AACA,SAAO;AACT;;;ACjCO,SAAS,WAAW,KAAqB;AAC9C,SAAO,IAAI,OAAO,CAAC,EAAE,YAAY,IAAI,IAAI,MAAM,CAAC,EAAE,YAAY;AAChE;AAMO,SAAS,YAAY,MAAwB;AAClD,SAAO,gBAAgB,QAAQ,CAAC,MAAM,KAAK,QAAQ,CAAC;AACtD;;;AC6DO,IAAM,YAAN,MAAsD;AAAA,EAC3D;AAAA,E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ACpD,mBAAO,OAAO,OAAO,KAAK,MAAM,UAAU,SAAS,MAAM;AAAA,UAC3D,WAAW,OAAO,SAAS,UAAU,UAAU;AAC7C,mBAAO,OAAO;AAAA,UAChB;AAAA,QACF;AAEA,wBAAgB,OAAO,cAAc,OAAO,SAAS,CAAC;AAAA,MACxD;AAAA,IACF;AAEA,WAAO,IAAI,SAAS,SAAS,MAAM;AAAA,MACjC,QAAQ,SAAS;AAAA,MACjB,YAAY,SAAS;AAAA,MACrB,SAAS;AAAA,IACX,CAAC;AAAA,EACH;AACF;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
export interface FetchProxyOptions {
|
|
2
|
+
/**
|
|
3
|
+
* The `fetch` function to use for the actual fetch. Defaults to the global `fetch` function.
|
|
4
|
+
*/
|
|
5
|
+
fetch?: typeof globalThis.fetch;
|
|
6
|
+
/**
|
|
7
|
+
* Set `false` to prevent the `Domain` attribute of `Set-Cookie` headers from being rewritten. By
|
|
8
|
+
* default the domain will be rewritten to the domain of the incoming request.
|
|
9
|
+
*/
|
|
10
|
+
rewriteCookieDomain?: boolean;
|
|
11
|
+
/**
|
|
12
|
+
* Set `false` to prevent the `Path` attribute of `Set-Cookie` headers from being rewritten. By
|
|
13
|
+
* default the portion of the pathname that matches the proxy target's pathname will be removed.
|
|
14
|
+
*/
|
|
15
|
+
rewriteCookiePath?: boolean;
|
|
16
|
+
/**
|
|
17
|
+
* Set `true` to add `X-Forwarded-Proto` and `X-Forwarded-Host` headers to the proxied request.
|
|
18
|
+
* Defaults to `false`.
|
|
19
|
+
*/
|
|
20
|
+
xForwardedHeaders?: boolean;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* A [`fetch` function](https://developer.mozilla.org/en-US/docs/Web/API/Window/fetch)
|
|
24
|
+
* that forwards requests to another server.
|
|
25
|
+
*/
|
|
26
|
+
export interface FetchProxy {
|
|
27
|
+
(input: URL | RequestInfo, init?: RequestInit): Promise<Response>;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Creates a `fetch` function that forwards requests to another server.
|
|
31
|
+
* @param target The URL of the server to proxy requests to
|
|
32
|
+
* @param options Options to customize the behavior of the proxy
|
|
33
|
+
* @returns A fetch function that forwards requests to the target server
|
|
34
|
+
*/
|
|
35
|
+
export declare function createFetchProxy(target: string | URL, options?: FetchProxyOptions): FetchProxy;
|
|
36
|
+
//# sourceMappingURL=fetch-proxy.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fetch-proxy.d.ts","sourceRoot":"","sources":["../../src/lib/fetch-proxy.ts"],"names":[],"mappings":"AAEA,MAAM,WAAW,iBAAiB;IAChC;;OAEG;IACH,KAAK,CAAC,EAAE,OAAO,UAAU,CAAC,KAAK,CAAC;IAChC;;;OAGG;IACH,mBAAmB,CAAC,EAAE,OAAO,CAAC;IAC9B;;;OAGG;IACH,iBAAiB,CAAC,EAAE,OAAO,CAAC;IAC5B;;;OAGG;IACH,iBAAiB,CAAC,EAAE,OAAO,CAAC;CAC7B;AAED;;;GAGG;AACH,MAAM,WAAW,UAAU;IACzB,CAAC,KAAK,EAAE,GAAG,GAAG,WAAW,EAAE,IAAI,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;CACnE;AAED;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,MAAM,GAAG,GAAG,EAAE,OAAO,CAAC,EAAE,iBAAiB,GAAG,UAAU,CAoF9F"}
|
package/package.json
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@remix-run/fetch-proxy",
|
|
3
|
+
"version": "0.5.0",
|
|
4
|
+
"description": "An HTTP proxy for the web Fetch API",
|
|
5
|
+
"author": "Michael Jackson <mjijackson@gmail.com>",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/remix-run/remix.git",
|
|
10
|
+
"directory": "packages/fetch-proxy"
|
|
11
|
+
},
|
|
12
|
+
"homepage": "https://github.com/remix-run/remix/tree/v3/packages/fetch-proxy#readme",
|
|
13
|
+
"files": [
|
|
14
|
+
"LICENSE",
|
|
15
|
+
"README.md",
|
|
16
|
+
"dist",
|
|
17
|
+
"src",
|
|
18
|
+
"!src/**/*.test.ts"
|
|
19
|
+
],
|
|
20
|
+
"type": "module",
|
|
21
|
+
"types": "dist/fetch-proxy.d.ts",
|
|
22
|
+
"module": "dist/fetch-proxy.js",
|
|
23
|
+
"main": "dist/fetch-proxy.cjs",
|
|
24
|
+
"exports": {
|
|
25
|
+
".": {
|
|
26
|
+
"types": "./dist/fetch-proxy.d.ts",
|
|
27
|
+
"import": "./dist/fetch-proxy.js",
|
|
28
|
+
"require": "./dist/fetch-proxy.cjs",
|
|
29
|
+
"default": "./dist/fetch-proxy.js"
|
|
30
|
+
},
|
|
31
|
+
"./package.json": "./package.json"
|
|
32
|
+
},
|
|
33
|
+
"dependencies": {
|
|
34
|
+
"@remix-run/headers": "^0.12.0"
|
|
35
|
+
},
|
|
36
|
+
"devDependencies": {
|
|
37
|
+
"@types/node": "^20.14.10",
|
|
38
|
+
"esbuild": "^0.25.5"
|
|
39
|
+
},
|
|
40
|
+
"keywords": [
|
|
41
|
+
"fetch",
|
|
42
|
+
"http",
|
|
43
|
+
"proxy"
|
|
44
|
+
],
|
|
45
|
+
"scripts": {
|
|
46
|
+
"build:types": "tsc --project tsconfig.build.json",
|
|
47
|
+
"build:esm": "esbuild src/fetch-proxy.ts --bundle --outfile=dist/fetch-proxy.js --format=esm --platform=neutral --sourcemap",
|
|
48
|
+
"build:cjs": "esbuild src/fetch-proxy.ts --bundle --outfile=dist/fetch-proxy.cjs --format=cjs --platform=neutral --sourcemap",
|
|
49
|
+
"build": "pnpm run clean && pnpm run build:types && pnpm run build:esm && pnpm run build:cjs",
|
|
50
|
+
"clean": "rm -rf dist",
|
|
51
|
+
"test": "node --disable-warning=ExperimentalWarning --test ./src/**/*.test.ts"
|
|
52
|
+
}
|
|
53
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { type FetchProxyOptions, type FetchProxy, createFetchProxy } from './lib/fetch-proxy.ts';
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { SetCookie } from '@remix-run/headers';
|
|
2
|
+
|
|
3
|
+
export interface FetchProxyOptions {
|
|
4
|
+
/**
|
|
5
|
+
* The `fetch` function to use for the actual fetch. Defaults to the global `fetch` function.
|
|
6
|
+
*/
|
|
7
|
+
fetch?: typeof globalThis.fetch;
|
|
8
|
+
/**
|
|
9
|
+
* Set `false` to prevent the `Domain` attribute of `Set-Cookie` headers from being rewritten. By
|
|
10
|
+
* default the domain will be rewritten to the domain of the incoming request.
|
|
11
|
+
*/
|
|
12
|
+
rewriteCookieDomain?: boolean;
|
|
13
|
+
/**
|
|
14
|
+
* Set `false` to prevent the `Path` attribute of `Set-Cookie` headers from being rewritten. By
|
|
15
|
+
* default the portion of the pathname that matches the proxy target's pathname will be removed.
|
|
16
|
+
*/
|
|
17
|
+
rewriteCookiePath?: boolean;
|
|
18
|
+
/**
|
|
19
|
+
* Set `true` to add `X-Forwarded-Proto` and `X-Forwarded-Host` headers to the proxied request.
|
|
20
|
+
* Defaults to `false`.
|
|
21
|
+
*/
|
|
22
|
+
xForwardedHeaders?: boolean;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* A [`fetch` function](https://developer.mozilla.org/en-US/docs/Web/API/Window/fetch)
|
|
27
|
+
* that forwards requests to another server.
|
|
28
|
+
*/
|
|
29
|
+
export interface FetchProxy {
|
|
30
|
+
(input: URL | RequestInfo, init?: RequestInit): Promise<Response>;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Creates a `fetch` function that forwards requests to another server.
|
|
35
|
+
* @param target The URL of the server to proxy requests to
|
|
36
|
+
* @param options Options to customize the behavior of the proxy
|
|
37
|
+
* @returns A fetch function that forwards requests to the target server
|
|
38
|
+
*/
|
|
39
|
+
export function createFetchProxy(target: string | URL, options?: FetchProxyOptions): FetchProxy {
|
|
40
|
+
let localFetch = options?.fetch ?? globalThis.fetch;
|
|
41
|
+
let rewriteCookieDomain = options?.rewriteCookieDomain ?? true;
|
|
42
|
+
let rewriteCookiePath = options?.rewriteCookiePath ?? true;
|
|
43
|
+
let xForwardedHeaders = options?.xForwardedHeaders ?? false;
|
|
44
|
+
|
|
45
|
+
let targetUrl = new URL(target);
|
|
46
|
+
if (targetUrl.pathname.endsWith('/')) {
|
|
47
|
+
targetUrl.pathname = targetUrl.pathname.replace(/\/+$/, '');
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
return async (input: URL | RequestInfo, init?: RequestInit) => {
|
|
51
|
+
let request = new Request(input, init);
|
|
52
|
+
let url = new URL(request.url);
|
|
53
|
+
|
|
54
|
+
let proxyUrl = new URL(url.search, targetUrl);
|
|
55
|
+
if (url.pathname !== '/') {
|
|
56
|
+
proxyUrl.pathname =
|
|
57
|
+
proxyUrl.pathname === '/' ? url.pathname : proxyUrl.pathname + url.pathname;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
let proxyHeaders = new Headers(request.headers);
|
|
61
|
+
if (xForwardedHeaders) {
|
|
62
|
+
proxyHeaders.append('X-Forwarded-Proto', url.protocol.replace(/:$/, ''));
|
|
63
|
+
proxyHeaders.append('X-Forwarded-Host', url.host);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
let proxyInit: RequestInit = {
|
|
67
|
+
method: request.method,
|
|
68
|
+
headers: proxyHeaders,
|
|
69
|
+
cache: request.cache,
|
|
70
|
+
credentials: request.credentials,
|
|
71
|
+
integrity: request.integrity,
|
|
72
|
+
keepalive: request.keepalive,
|
|
73
|
+
mode: request.mode,
|
|
74
|
+
redirect: request.redirect,
|
|
75
|
+
referrer: request.referrer,
|
|
76
|
+
referrerPolicy: request.referrerPolicy,
|
|
77
|
+
signal: request.signal,
|
|
78
|
+
...init,
|
|
79
|
+
};
|
|
80
|
+
if (request.method !== 'GET' && request.method !== 'HEAD') {
|
|
81
|
+
proxyInit.body = request.body;
|
|
82
|
+
|
|
83
|
+
// init.duplex = 'half' must be set when body is a ReadableStream, and Node follows the spec.
|
|
84
|
+
// However, this property is not defined in the TypeScript types for RequestInit, so we have
|
|
85
|
+
// to cast it here in order to set it without a type error.
|
|
86
|
+
// See https://fetch.spec.whatwg.org/#dom-requestinit-duplex
|
|
87
|
+
(proxyInit as { duplex: 'half' }).duplex = 'half';
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
let response = await localFetch(proxyUrl, proxyInit);
|
|
91
|
+
let responseHeaders = new Headers(response.headers);
|
|
92
|
+
|
|
93
|
+
if (responseHeaders.has('Set-Cookie')) {
|
|
94
|
+
let setCookie = responseHeaders.getSetCookie();
|
|
95
|
+
|
|
96
|
+
responseHeaders.delete('Set-Cookie');
|
|
97
|
+
|
|
98
|
+
for (let cookie of setCookie) {
|
|
99
|
+
let header = new SetCookie(cookie);
|
|
100
|
+
|
|
101
|
+
if (rewriteCookieDomain && header.domain) {
|
|
102
|
+
header.domain = url.host;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
if (rewriteCookiePath && header.path) {
|
|
106
|
+
if (header.path.startsWith(targetUrl.pathname + '/')) {
|
|
107
|
+
header.path = header.path.slice(targetUrl.pathname.length);
|
|
108
|
+
} else if (header.path === targetUrl.pathname) {
|
|
109
|
+
header.path = '/';
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
responseHeaders.append('Set-Cookie', header.toString());
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
return new Response(response.body, {
|
|
118
|
+
status: response.status,
|
|
119
|
+
statusText: response.statusText,
|
|
120
|
+
headers: responseHeaders,
|
|
121
|
+
});
|
|
122
|
+
};
|
|
123
|
+
}
|