Skip to content

Commit 194a865

Browse files
committed
feat: small changes on Cors class and add README
1 parent cbeb8be commit 194a865

File tree

6 files changed

+116
-76
lines changed

6 files changed

+116
-76
lines changed

README.md

+37-22
Original file line numberDiff line numberDiff line change
@@ -13,26 +13,28 @@
1313

1414
<br />
1515
<div align="center">
16-
<a href="https://github.com/lottojs/params-parser">
16+
<a href="https://github.com/lottojs/cors">
1717
<img src=".github/logo.png" alt="Logo" width="100" height="115">
1818
</a>
1919

20-
<h3 align="center">@lottojs/params-parser</h3>
20+
<h3 align="center">@lottojs/cors</h3>
2121

2222
<p align="center">
23-
NodeJS HTTP Request path and query parameters parser.
23+
NodeJS HTTP CORS Middleware for secure cross-origin resource sharing.
2424
<br />
2525
<br />
26-
<a href="https://github.com/lottojs/params-parser/issues">Report Bug</a>
26+
<a href="https://github.com/lottojs/cors/issues">Report Bug</a>
2727
·
28-
<a href="https://github.com/lottojs/params-parser/issues">Request Feature</a>
28+
<a href="https://github.com/lottojs/cors/issues">Request Feature</a>
2929
</p>
3030
</div>
3131

3232

3333
## About The Project
3434

35-
HTTP Middleware done to parse query and path parameters from a given url, initially created to serve the [@lottojs/router](https://github.com/lottojs/router) package but nothing excludes it to be also used by the community.
35+
36+
A CORS middleware designed to enhance security by enabling secure cross-origin resource sharing in Node.js applications. Initially created to serve the [@lottojs/lotto](https://github.com/lottojs/lotto) package but nothing excludes it to be also used by the community.
37+
3638

3739
## Documentation
3840
Complete API documentation is available at [lottojs.tech][documentation-url].
@@ -41,19 +43,32 @@ Complete API documentation is available at [lottojs.tech][documentation-url].
4143

4244
### Installation
4345
```sh
44-
npm i @lottojs/params-parser
46+
npm i @lottojs/cors
4547
```
4648
### Usage
47-
It will depend on your scenario, basically the package exports a middleware called `paramsParser`. This middleware can be used receiving a path from any http handler and returns a promise awaiting to receive a request and next parameters. On the end it put's each parsed group on the right place, query parameters at `req.query` object and path parameters at `req.params` object, all ready to be used.
49+
The package exports a middleware named `cors`. This middleware should be used within an HTTP server handler. It checks the request's origin and sets the appropriate CORS headers. This allows or restricts cross-origin requests based on the specified configuration.
50+
4851

4952
```typescript
5053
import { createServer } from 'node:http';
51-
import { paramsParser } from '@lottojs/params-parser';
54+
import { cors } from '@lottojs/cors';
5255

5356
createServer(
5457
async (req: IncomingMessage, res: ServerResponse) => {
5558
...
56-
paramsParser(req.url)(req, next())
59+
const allowedSites = ['http://localhost:3000']
60+
const allowedMethods = ['GET', 'POST']
61+
const allowedHeaders = ['Content-Type', 'Authorization']
62+
const exposeHeaders = ['Content-Length']
63+
const allowCredentials = true
64+
65+
cors(
66+
allowedSites,
67+
allowedMethods,
68+
allowedHeaders,
69+
exposeHeaders,
70+
allowCredentials
71+
)(req, res, next())
5772
...
5873
},
5974
)
@@ -77,16 +92,16 @@ Distributed under the MIT License. See `LICENSE` for more information.
7792
<p align="right">(<a href="#readme-top">back to top</a>)</p>
7893

7994

80-
[contributors-shield]: https://img.shields.io/github/contributors/lottojs/params-parser.svg?style=for-the-badge
81-
[contributors-url]: https://github.com/lottojs/params-parser/graphs/contributors
82-
[forks-shield]: https://img.shields.io/github/forks/lottojs/params-parser.svg?style=for-the-badge
83-
[forks-url]: https://github.com/lottojs/params-parser/network/members
84-
[stars-shield]: https://img.shields.io/github/stars/lottojs/params-parser.svg?style=for-the-badge
85-
[stars-url]: https://github.com/lottojs/params-parser/stargazers
86-
[issues-shield]: https://img.shields.io/github/issues/lottojs/params-parser.svg?style=for-the-badge
87-
[issues-url]: https://github.com/lottojs/params-parser/issues
88-
[license-shield]: https://img.shields.io/github/license/lottojs/params-parser.svg?style=for-the-badge
89-
[license-url]: https://github.com/lottojs/params-parser/blob/master/LICENSE.txt
90-
[npm-shield]: https://img.shields.io/npm/v/@lottojs/params-parser?style=for-the-badge&logo=npm&logoColor=FFFFFF&labelColor=555555&color=CB0001
91-
[npm-url]: https://www.npmjs.com/package/@lottojs/params-parser
95+
[contributors-shield]: https://img.shields.io/github/contributors/lottojs/cors.svg?style=for-the-badge
96+
[contributors-url]: https://github.com/lottojs/cors/graphs/contributors
97+
[forks-shield]: https://img.shields.io/github/forks/lottojs/cors.svg?style=for-the-badge
98+
[forks-url]: https://github.com/lottojs/cors/network/members
99+
[stars-shield]: https://img.shields.io/github/stars/lottojs/cors.svg?style=for-the-badge
100+
[stars-url]: https://github.com/lottojs/cors/stargazers
101+
[issues-shield]: https://img.shields.io/github/issues/lottojs/cors.svg?style=for-the-badge
102+
[issues-url]: https://github.com/lottojs/cors/issues
103+
[license-shield]: https://img.shields.io/github/license/lottojs/cors.svg?style=for-the-badge
104+
[license-url]: https://github.com/lottojs/cors/blob/master/LICENSE.txt
105+
[npm-shield]: https://img.shields.io/npm/v/@lottojs/cors?style=for-the-badge&logo=npm&logoColor=FFFFFF&labelColor=555555&color=CB0001
106+
[npm-url]: https://www.npmjs.com/package/@lottojs/cors
92107
[documentation-url]: https://lottojs.tech

package-lock.json

+2-2
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@lottojs/cors",
3-
"version": "0.1.0",
3+
"version": "0.1.1",
44
"description": "Custom HTTP CORS middleware to manage Cross-Origin Resource Sharing (CORS) headers and methods",
55
"author": "Pedro Harbs <[email protected]>",
66
"license": "MIT",

src/core/cors.ts

+44-34
Original file line numberDiff line numberDiff line change
@@ -1,49 +1,59 @@
1-
import { NextFunction, Request, Response } from '@core/types'
1+
import { Context } from '@core/types'
22

3-
export interface AbstractCors {
4-
apply: (req: Request, res: Response, next: NextFunction) => Promise<void>
5-
}
6-
7-
export class Cors implements AbstractCors {
8-
private allowedSites: string[]
3+
export class Cors {
4+
private allowedOrigins: string[]
95
private allowedMethods: string[]
106
private allowedHeaders: string[]
7+
private exposeHeaders: string[]
8+
private allowCredentials: boolean
119

1210
constructor(
13-
allowedSites = [''],
14-
allowedMethods = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
15-
allowedHeaders = ['Content-Type', 'Authorization'],
11+
allowedOrigins: string[] = ['*'],
12+
allowedMethods: string[] = [
13+
'GET',
14+
'POST',
15+
'PUT',
16+
'PATCH',
17+
'DELETE',
18+
'OPTIONS',
19+
],
20+
allowedHeaders: string[] = ['Content-Type', 'Authorization'],
21+
exposeHeaders: string[] = ['Content-Length'],
22+
allowCredentials = true,
1623
) {
17-
this.allowedSites = allowedSites
24+
this.allowedOrigins = allowedOrigins
1825
this.allowedMethods = allowedMethods
1926
this.allowedHeaders = allowedHeaders
27+
this.exposeHeaders = exposeHeaders
28+
this.allowCredentials = allowCredentials
2029
}
2130

22-
/**
23-
* Apply cors headers.
24-
* @param req Request
25-
* @param res Response
26-
* @param next NextFunction
27-
*/
28-
public async apply(
29-
req: Request,
30-
res: Response,
31-
next: NextFunction,
32-
): Promise<void> {
33-
const origin = req.headers.origin!
31+
apply({ req, res, next }: Context): void {
32+
const origin = req.headers.origin
3433

35-
if (this.allowedSites.includes(origin)) {
36-
res.setHeader('Access-Control-Allow-Origin', origin)
37-
}
34+
if (
35+
this.allowedOrigins.includes('*') ||
36+
this.allowedOrigins.includes(origin as string)
37+
) {
38+
res.setHeader('Access-Control-Allow-Origin', origin as string)
3839

39-
res.setHeader(
40-
'Access-Control-Allow-Methods',
41-
this.allowedMethods.join(', '),
42-
)
43-
res.setHeader(
44-
'Access-Control-Allow-Headers',
45-
this.allowedHeaders.join(', '),
46-
)
40+
res.setHeader(
41+
'Access-Control-Allow-Methods',
42+
this.allowedMethods.join(', '),
43+
)
44+
res.setHeader(
45+
'Access-Control-Allow-Headers',
46+
this.allowedHeaders.join(', '),
47+
)
48+
res.setHeader(
49+
'Access-Control-Expose-Headers',
50+
this.exposeHeaders.join(', '),
51+
)
52+
res.setHeader(
53+
'Access-Control-Allow-Credentials',
54+
String(this.allowCredentials),
55+
)
56+
}
4757

4858
if (req.method === 'OPTIONS') {
4959
res.writeHead(200)

src/index.ts

+10-2
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,18 @@ export function cors(
1313
allowedSites?: string[],
1414
allowedMethods?: string[],
1515
allowedHeaders?: string[],
16+
exposeHeaders?: string[],
17+
allowCredentials?: boolean,
1618
): Middleware {
17-
const { apply } = new Cors(allowedSites, allowedMethods, allowedHeaders)
19+
const corInstance = new Cors(
20+
allowedSites,
21+
allowedMethods,
22+
allowedHeaders,
23+
exposeHeaders,
24+
allowCredentials,
25+
)
1826

1927
return async ({ req, res, next }: Context) => {
20-
await apply(req, res, next)
28+
corInstance.apply({ req, res, next })
2129
}
2230
}

tsconfig.json

+22-15
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,23 @@
11
{
2-
"extends": "./node_modules/@lottojs/ts-config/base.json",
3-
"compilerOptions": {
4-
"lib": [ "es2021" ],
5-
"outDir": "./lib",
6-
"baseUrl": ".",
7-
"paths": {
8-
"@core/*": ["./src/core/*"],
9-
"@parsers/*": ["./src/parsers/*"]
10-
}
11-
},
12-
"include": ["src/**/*"],
13-
"ts-node": {
14-
"require": ["tsconfig-paths/register"]
15-
}
16-
}
2+
"extends": "./node_modules/@lottojs/ts-config/base.json",
3+
"compilerOptions": {
4+
"lib": [
5+
"es2021"
6+
],
7+
"outDir": "./lib",
8+
"baseUrl": ".",
9+
"paths": {
10+
"@core/*": [
11+
"./src/core/*"
12+
]
13+
}
14+
},
15+
"include": [
16+
"src/**/*"
17+
],
18+
"ts-node": {
19+
"require": [
20+
"tsconfig-paths/register"
21+
]
22+
}
23+
}

0 commit comments

Comments
 (0)