@webframe/use-cors-headers 0.0.0-stage → 0.1.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 +30 -2
- package/dist/index.d.ts +33 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +71 -0
- package/dist/index.js.map +1 -0
- package/package.json +30 -4
- package/src/index.ts +92 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 tw050x
|
|
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
CHANGED
|
@@ -1,3 +1,31 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @webframe/use-cors-headers
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Sets the [CORS](https://developer.mozilla.org/docs/Web/HTTP/CORS) headers that let pages on other sites call your service.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
npm install @webframe/use-cors-headers
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import { defineMiddleware } from '@webframe/core'
|
|
11
|
+
import { useCorsHeaders } from '@webframe/use-cors-headers'
|
|
12
|
+
|
|
13
|
+
const cors = useCorsHeaders({
|
|
14
|
+
allowedOrigins: ['app.example.com', 'localhost:5173'],
|
|
15
|
+
allowedMethods: ['GET', 'POST'],
|
|
16
|
+
allowedHeaders: ['Content-Type', 'Authorization'],
|
|
17
|
+
})
|
|
18
|
+
|
|
19
|
+
const routes = {
|
|
20
|
+
'GET /orders': defineMiddleware([cors, listOrders]),
|
|
21
|
+
'POST /orders': defineMiddleware([cors, createOrder]),
|
|
22
|
+
// the browser's preflight
|
|
23
|
+
'OPTIONS /orders': defineMiddleware([cors, async ({ serverResponse }) => serverResponse.sendNoContentResponse()]),
|
|
24
|
+
}
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
It only sets headers. It doesn't answer preflight requests itself, so give each path an `OPTIONS` route that sends `204` after it, as above.
|
|
28
|
+
|
|
29
|
+
The full documentation is at [webframe.tw050x.net/packages/use-cors-headers](https://webframe.tw050x.net/packages/use-cors-headers).
|
|
30
|
+
|
|
31
|
+
Part of [webframe](https://webframe.tw050x.net), MIT licensed.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { type HttpMethod, type Middleware } from "@webframe/core";
|
|
2
|
+
/** The allowed origins: their hosts (`app.example.com`, `localhost:3000`), or `'*'` for any. */
|
|
3
|
+
export type AllowedOrigins = readonly string[] | '*';
|
|
4
|
+
export type UseCorsHeadersOptions = {
|
|
5
|
+
/**
|
|
6
|
+
* Origins allowed, by host. A function is called for each request, for origins read from
|
|
7
|
+
* config (`() => configs.read('cors.allowed-origins').split(',')`).
|
|
8
|
+
*/
|
|
9
|
+
allowedOrigins: AllowedOrigins | (() => AllowedOrigins | string);
|
|
10
|
+
allowedMethods: readonly HttpMethod[] | '*';
|
|
11
|
+
/** Headers a preflight may ask for: an array, a comma-separated list, or `'*'` (the default). */
|
|
12
|
+
allowedHeaders?: readonly string[] | string;
|
|
13
|
+
};
|
|
14
|
+
/**
|
|
15
|
+
* Whether an `Origin` header's host is one of those allowed. A missing or malformed origin isn't.
|
|
16
|
+
*/
|
|
17
|
+
export declare const isAllowedOrigin: (origin: string | undefined, allowedOrigins: readonly string[]) => origin is string;
|
|
18
|
+
/**
|
|
19
|
+
* Whether every header in an `Access-Control-Request-Headers` list is allowed, ignoring case.
|
|
20
|
+
*/
|
|
21
|
+
export declare const isAllowedHeaders: (headers: string | undefined, allowedHeaders: readonly string[]) => headers is string;
|
|
22
|
+
/**
|
|
23
|
+
* Sets the CORS headers for the request's origin. It doesn't answer preflight requests itself:
|
|
24
|
+
* give the route an `OPTIONS` pattern that sends 204 after it.
|
|
25
|
+
*
|
|
26
|
+
* @example
|
|
27
|
+
* defineMiddleware([
|
|
28
|
+
* useCorsHeaders({ allowedOrigins: ['app.example.com'], allowedMethods: ['GET', 'POST'] }),
|
|
29
|
+
* async ({ serverResponse }) => serverResponse.sendNoContentResponse(),
|
|
30
|
+
* ]);
|
|
31
|
+
*/
|
|
32
|
+
export declare const useCorsHeaders: (options: UseCorsHeadersOptions) => Middleware;
|
|
33
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAsC,KAAK,UAAU,EAAE,KAAK,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAEtG,gGAAgG;AAChG,MAAM,MAAM,cAAc,GAAG,SAAS,MAAM,EAAE,GAAG,GAAG,CAAC;AAErD,MAAM,MAAM,qBAAqB,GAAG;IAClC;;;OAGG;IACH,cAAc,EAAE,cAAc,GAAG,CAAC,MAAM,cAAc,GAAG,MAAM,CAAC,CAAC;IACjE,cAAc,EAAE,SAAS,UAAU,EAAE,GAAG,GAAG,CAAC;IAC5C,iGAAiG;IACjG,cAAc,CAAC,EAAE,SAAS,MAAM,EAAE,GAAG,MAAM,CAAC;CAC7C,CAAA;AAED;;GAEG;AACH,eAAO,MAAM,eAAe,GAAI,QAAQ,MAAM,GAAG,SAAS,EAAE,gBAAgB,SAAS,MAAM,EAAE,KAAG,MAAM,IAAI,MAQzG,CAAA;AAED;;GAEG;AACH,eAAO,MAAM,gBAAgB,GAAI,SAAS,MAAM,GAAG,SAAS,EAAE,gBAAgB,SAAS,MAAM,EAAE,KAAG,OAAO,IAAI,MAI5G,CAAA;AAKD;;;;;;;;;GASG;AACH,eAAO,MAAM,cAAc,GAAI,SAAS,qBAAqB,KAAG,UAwC/D,CAAA"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { isArrayOfHttpMethods, isHttpMethod } from "@webframe/core";
|
|
2
|
+
/**
|
|
3
|
+
* Whether an `Origin` header's host is one of those allowed. A missing or malformed origin isn't.
|
|
4
|
+
*/
|
|
5
|
+
export const isAllowedOrigin = (origin, allowedOrigins) => {
|
|
6
|
+
if (origin === undefined)
|
|
7
|
+
return false;
|
|
8
|
+
try {
|
|
9
|
+
return allowedOrigins.includes(new URL(origin).host);
|
|
10
|
+
}
|
|
11
|
+
catch {
|
|
12
|
+
return false;
|
|
13
|
+
}
|
|
14
|
+
};
|
|
15
|
+
/**
|
|
16
|
+
* Whether every header in an `Access-Control-Request-Headers` list is allowed, ignoring case.
|
|
17
|
+
*/
|
|
18
|
+
export const isAllowedHeaders = (headers, allowedHeaders) => {
|
|
19
|
+
if (headers === undefined)
|
|
20
|
+
return false;
|
|
21
|
+
const allowed = allowedHeaders.map((header) => header.toLowerCase());
|
|
22
|
+
return headers.split(',').every((header) => allowed.includes(header.trim().toLowerCase()));
|
|
23
|
+
};
|
|
24
|
+
const parseList = (value) => (typeof value === 'string' ? value.split(',') : value).map((item) => item.trim()).filter(Boolean);
|
|
25
|
+
/**
|
|
26
|
+
* Sets the CORS headers for the request's origin. It doesn't answer preflight requests itself:
|
|
27
|
+
* give the route an `OPTIONS` pattern that sends 204 after it.
|
|
28
|
+
*
|
|
29
|
+
* @example
|
|
30
|
+
* defineMiddleware([
|
|
31
|
+
* useCorsHeaders({ allowedOrigins: ['app.example.com'], allowedMethods: ['GET', 'POST'] }),
|
|
32
|
+
* async ({ serverResponse }) => serverResponse.sendNoContentResponse(),
|
|
33
|
+
* ]);
|
|
34
|
+
*/
|
|
35
|
+
export const useCorsHeaders = (options) => {
|
|
36
|
+
const allowedHeaders = options.allowedHeaders === undefined || options.allowedHeaders === '*'
|
|
37
|
+
? '*'
|
|
38
|
+
: parseList(options.allowedHeaders).map((header) => header.toLowerCase());
|
|
39
|
+
const allowedMethods = options.allowedMethods === '*'
|
|
40
|
+
? '*'
|
|
41
|
+
: options.allowedMethods.map((method) => method.trim().toUpperCase());
|
|
42
|
+
if (allowedMethods !== '*' && isArrayOfHttpMethods(allowedMethods) === false) {
|
|
43
|
+
throw new TypeError(`Invalid allowedMethods: ${allowedMethods.filter((method) => !isHttpMethod(method)).join(', ')}`);
|
|
44
|
+
}
|
|
45
|
+
const originsNow = () => {
|
|
46
|
+
const origins = typeof options.allowedOrigins === 'function' ? options.allowedOrigins() : options.allowedOrigins;
|
|
47
|
+
if (origins === '*')
|
|
48
|
+
return '*';
|
|
49
|
+
return parseList(origins);
|
|
50
|
+
};
|
|
51
|
+
return async ({ incomingMessage, serverResponse }) => {
|
|
52
|
+
const allowedOrigins = originsNow();
|
|
53
|
+
const origin = incomingMessage.headers.origin;
|
|
54
|
+
if (allowedOrigins === '*') {
|
|
55
|
+
serverResponse.setHeader('Access-Control-Allow-Origin', '*');
|
|
56
|
+
}
|
|
57
|
+
else {
|
|
58
|
+
// the header depends on the request's origin, so caches must keep them apart
|
|
59
|
+
serverResponse.appendHeader('Vary', 'Origin');
|
|
60
|
+
if (isAllowedOrigin(origin, allowedOrigins)) {
|
|
61
|
+
serverResponse.setHeader('Access-Control-Allow-Origin', origin);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
serverResponse.setHeader('Access-Control-Allow-Methods', allowedMethods === '*' ? '*' : allowedMethods.join(', '));
|
|
65
|
+
const isPreflight = incomingMessage.method === 'OPTIONS' && incomingMessage.headers['access-control-request-method'] !== undefined;
|
|
66
|
+
if (isPreflight) {
|
|
67
|
+
serverResponse.setHeader('Access-Control-Allow-Headers', allowedHeaders === '*' ? '*' : allowedHeaders.join(', '));
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
};
|
|
71
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,YAAY,EAAoC,MAAM,gBAAgB,CAAC;AAgBtG;;GAEG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG,CAAC,MAA0B,EAAE,cAAiC,EAAoB,EAAE;IACjH,IAAI,MAAM,KAAK,SAAS;QAAE,OAAO,KAAK,CAAC;IACvC,IAAI,CAAC;QACH,OAAO,cAAc,CAAC,QAAQ,CAAC,IAAI,GAAG,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,CAAC;IACvD,CAAC;IACD,MAAM,CAAC;QACL,OAAO,KAAK,CAAC;IACf,CAAC;AACH,CAAC,CAAA;AAED;;GAEG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,OAA2B,EAAE,cAAiC,EAAqB,EAAE;IACpH,IAAI,OAAO,KAAK,SAAS;QAAE,OAAO,KAAK,CAAC;IACxC,MAAM,OAAO,GAAG,cAAc,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,E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WAAW,EAAE,CAAC;YAChB,cAAc,CAAC,SAAS,CAAC,8BAA8B,EAAE,cAAc,KAAK,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,cAAc,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;QACrH,CAAC;IACH,CAAC,CAAC;AACJ,CAAC,CAAA"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,32 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@webframe/use-cors-headers",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "CORS headers middleware for webframe.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": {
|
|
9
|
+
"types": "./dist/index.d.ts",
|
|
10
|
+
"default": "./dist/index.js"
|
|
11
|
+
}
|
|
12
|
+
},
|
|
13
|
+
"files": [
|
|
14
|
+
"dist",
|
|
15
|
+
"src"
|
|
16
|
+
],
|
|
17
|
+
"dependencies": {
|
|
18
|
+
"@webframe/core": "^0.1.0"
|
|
19
|
+
},
|
|
20
|
+
"engines": {
|
|
21
|
+
"node": ">=22"
|
|
22
|
+
},
|
|
23
|
+
"repository": {
|
|
24
|
+
"type": "git",
|
|
25
|
+
"url": "git+https://github.com/tw050x/webframe.git",
|
|
26
|
+
"directory": "packages/node/use-cors-headers"
|
|
27
|
+
},
|
|
28
|
+
"homepage": "https://webframe.tw050x.net/packages/use-cors-headers",
|
|
29
|
+
"publishConfig": {
|
|
30
|
+
"access": "public"
|
|
31
|
+
}
|
|
32
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { isArrayOfHttpMethods, isHttpMethod, type HttpMethod, type Middleware } from "@webframe/core";
|
|
2
|
+
|
|
3
|
+
/** The allowed origins: their hosts (`app.example.com`, `localhost:3000`), or `'*'` for any. */
|
|
4
|
+
export type AllowedOrigins = readonly string[] | '*';
|
|
5
|
+
|
|
6
|
+
export type UseCorsHeadersOptions = {
|
|
7
|
+
/**
|
|
8
|
+
* Origins allowed, by host. A function is called for each request, for origins read from
|
|
9
|
+
* config (`() => configs.read('cors.allowed-origins').split(',')`).
|
|
10
|
+
*/
|
|
11
|
+
allowedOrigins: AllowedOrigins | (() => AllowedOrigins | string);
|
|
12
|
+
allowedMethods: readonly HttpMethod[] | '*';
|
|
13
|
+
/** Headers a preflight may ask for: an array, a comma-separated list, or `'*'` (the default). */
|
|
14
|
+
allowedHeaders?: readonly string[] | string;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Whether an `Origin` header's host is one of those allowed. A missing or malformed origin isn't.
|
|
19
|
+
*/
|
|
20
|
+
export const isAllowedOrigin = (origin: string | undefined, allowedOrigins: readonly string[]): origin is string => {
|
|
21
|
+
if (origin === undefined) return false;
|
|
22
|
+
try {
|
|
23
|
+
return allowedOrigins.includes(new URL(origin).host);
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
return false;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Whether every header in an `Access-Control-Request-Headers` list is allowed, ignoring case.
|
|
32
|
+
*/
|
|
33
|
+
export const isAllowedHeaders = (headers: string | undefined, allowedHeaders: readonly string[]): headers is string => {
|
|
34
|
+
if (headers === undefined) return false;
|
|
35
|
+
const allowed = allowedHeaders.map((header) => header.toLowerCase());
|
|
36
|
+
return headers.split(',').every((header) => allowed.includes(header.trim().toLowerCase()));
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const parseList = (value: readonly string[] | string) =>
|
|
40
|
+
(typeof value === 'string' ? value.split(',') : value).map((item) => item.trim()).filter(Boolean);
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Sets the CORS headers for the request's origin. It doesn't answer preflight requests itself:
|
|
44
|
+
* give the route an `OPTIONS` pattern that sends 204 after it.
|
|
45
|
+
*
|
|
46
|
+
* @example
|
|
47
|
+
* defineMiddleware([
|
|
48
|
+
* useCorsHeaders({ allowedOrigins: ['app.example.com'], allowedMethods: ['GET', 'POST'] }),
|
|
49
|
+
* async ({ serverResponse }) => serverResponse.sendNoContentResponse(),
|
|
50
|
+
* ]);
|
|
51
|
+
*/
|
|
52
|
+
export const useCorsHeaders = (options: UseCorsHeadersOptions): Middleware => {
|
|
53
|
+
const allowedHeaders = options.allowedHeaders === undefined || options.allowedHeaders === '*'
|
|
54
|
+
? '*'
|
|
55
|
+
: parseList(options.allowedHeaders).map((header) => header.toLowerCase());
|
|
56
|
+
|
|
57
|
+
const allowedMethods = options.allowedMethods === '*'
|
|
58
|
+
? '*'
|
|
59
|
+
: options.allowedMethods.map((method) => method.trim().toUpperCase());
|
|
60
|
+
if (allowedMethods !== '*' && isArrayOfHttpMethods(allowedMethods) === false) {
|
|
61
|
+
throw new TypeError(`Invalid allowedMethods: ${allowedMethods.filter((method) => !isHttpMethod(method)).join(', ')}`);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const originsNow = (): AllowedOrigins => {
|
|
65
|
+
const origins = typeof options.allowedOrigins === 'function' ? options.allowedOrigins() : options.allowedOrigins;
|
|
66
|
+
if (origins === '*') return '*';
|
|
67
|
+
return parseList(origins);
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
return async ({ incomingMessage, serverResponse }) => {
|
|
71
|
+
const allowedOrigins = originsNow();
|
|
72
|
+
const origin = incomingMessage.headers.origin;
|
|
73
|
+
|
|
74
|
+
if (allowedOrigins === '*') {
|
|
75
|
+
serverResponse.setHeader('Access-Control-Allow-Origin', '*');
|
|
76
|
+
}
|
|
77
|
+
else {
|
|
78
|
+
// the header depends on the request's origin, so caches must keep them apart
|
|
79
|
+
serverResponse.appendHeader('Vary', 'Origin');
|
|
80
|
+
if (isAllowedOrigin(origin, allowedOrigins)) {
|
|
81
|
+
serverResponse.setHeader('Access-Control-Allow-Origin', origin);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
serverResponse.setHeader('Access-Control-Allow-Methods', allowedMethods === '*' ? '*' : allowedMethods.join(', '));
|
|
86
|
+
|
|
87
|
+
const isPreflight = incomingMessage.method === 'OPTIONS' && incomingMessage.headers['access-control-request-method'] !== undefined;
|
|
88
|
+
if (isPreflight) {
|
|
89
|
+
serverResponse.setHeader('Access-Control-Allow-Headers', allowedHeaders === '*' ? '*' : allowedHeaders.join(', '));
|
|
90
|
+
}
|
|
91
|
+
};
|
|
92
|
+
}
|