@tekir/cors 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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 tekir
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,31 @@
1
+ <p align="center">
2
+ <img src="https://tekir.io/logo.svg" width="80" alt="tekir" />
3
+ </p>
4
+
5
+ <h1 align="center">@tekir/cors</h1>
6
+
7
+ <p align="center">CORS middleware for cross-origin requests.</p>
8
+
9
+ <p align="center">
10
+ <a href="https://www.npmjs.com/package/@tekir/cors"><img src="https://img.shields.io/npm/v/@tekir/cors.svg" alt="npm version" /></a>
11
+ <a href="https://www.npmjs.com/package/@tekir/cors"><img src="https://img.shields.io/npm/dm/@tekir/cors.svg" alt="npm downloads" /></a>
12
+ <a href="https://github.com/tekir-io/tekir/blob/main/LICENSE"><img src="https://img.shields.io/npm/l/@tekir/cors.svg" alt="license" /></a>
13
+ </p>
14
+
15
+ <p align="center">
16
+ <a href="https://tekir.io">Website</a> · <a href="https://docs.tekir.io">Documentation</a> · <a href="https://github.com/tekir-io/tekir">GitHub</a>
17
+ </p>
18
+
19
+ ---
20
+
21
+ ## Installation
22
+
23
+ ```bash
24
+ bun add @tekir/cors
25
+ ```
26
+
27
+ For full usage and configuration, see the [documentation](https://docs.tekir.io/advanced/cors).
28
+
29
+ ## License
30
+
31
+ MIT
package/dist/cors.d.ts ADDED
@@ -0,0 +1,32 @@
1
+ import type { CorsConfig } from './types';
2
+ /**
3
+ * CORS middleware that handles preflight OPTIONS requests and sets Access-Control headers.
4
+ * Supports wildcard, array, string, and function-based origin validation.
5
+ * When `credentials: true` with `origin: true`, reflects the request origin instead of using `*`.
6
+ *
7
+ * @param userConfig - CORS configuration options.
8
+ * @param userConfig.origin - Allowed origins: `true` (all), `false` (none), `string`, `string[]`, or `(origin) => boolean`.
9
+ * @param userConfig.methods - Allowed HTTP methods. Defaults to `['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE']`.
10
+ * @param userConfig.credentials - Allow credentials (cookies, auth headers). Defaults to `false`.
11
+ * @param userConfig.maxAge - Preflight cache duration in seconds. Defaults to `86400` (24h).
12
+ * @param userConfig.headers - Allowed request headers: `true` (reflect), or `string[]`.
13
+ * @param userConfig.exposeHeaders - Headers exposed to the browser.
14
+ *
15
+ * @example
16
+ * ```ts
17
+ * // Allow all origins
18
+ * app.use(cors())
19
+ *
20
+ * // Allow specific origins with credentials
21
+ * app.use(cors({
22
+ * origin: ['https://app.com', 'https://admin.app.com'],
23
+ * credentials: true,
24
+ * }))
25
+ *
26
+ * // Dynamic origin validation
27
+ * app.use(cors({
28
+ * origin: (origin) => origin.endsWith('.myapp.com'),
29
+ * }))
30
+ * ```
31
+ */
32
+ export declare function cors(userConfig?: CorsConfig): (ctx: any, next: () => Promise<void>) => Promise<void | Response>;
package/dist/cors.js ADDED
@@ -0,0 +1,94 @@
1
+ const defaults = {
2
+ enabled: true,
3
+ origin: true,
4
+ methods: ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE'],
5
+ headers: true,
6
+ credentials: false,
7
+ maxAge: 86400,
8
+ };
9
+ /**
10
+ * CORS middleware that handles preflight OPTIONS requests and sets Access-Control headers.
11
+ * Supports wildcard, array, string, and function-based origin validation.
12
+ * When `credentials: true` with `origin: true`, reflects the request origin instead of using `*`.
13
+ *
14
+ * @param userConfig - CORS configuration options.
15
+ * @param userConfig.origin - Allowed origins: `true` (all), `false` (none), `string`, `string[]`, or `(origin) => boolean`.
16
+ * @param userConfig.methods - Allowed HTTP methods. Defaults to `['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE']`.
17
+ * @param userConfig.credentials - Allow credentials (cookies, auth headers). Defaults to `false`.
18
+ * @param userConfig.maxAge - Preflight cache duration in seconds. Defaults to `86400` (24h).
19
+ * @param userConfig.headers - Allowed request headers: `true` (reflect), or `string[]`.
20
+ * @param userConfig.exposeHeaders - Headers exposed to the browser.
21
+ *
22
+ * @example
23
+ * ```ts
24
+ * // Allow all origins
25
+ * app.use(cors())
26
+ *
27
+ * // Allow specific origins with credentials
28
+ * app.use(cors({
29
+ * origin: ['https://app.com', 'https://admin.app.com'],
30
+ * credentials: true,
31
+ * }))
32
+ *
33
+ * // Dynamic origin validation
34
+ * app.use(cors({
35
+ * origin: (origin) => origin.endsWith('.myapp.com'),
36
+ * }))
37
+ * ```
38
+ */
39
+ export function cors(userConfig = {}) {
40
+ const cfg = { ...defaults, ...userConfig };
41
+ return async (ctx, next) => {
42
+ if (!cfg.enabled)
43
+ return next();
44
+ const origin = ctx.request.header('origin') || ctx.headers?.origin || '';
45
+ let allowOrigin = '';
46
+ if (cfg.origin === true) {
47
+ // When credentials are enabled, never use wildcard — reflect the request origin instead
48
+ if (cfg.credentials && origin) {
49
+ allowOrigin = origin;
50
+ }
51
+ else {
52
+ allowOrigin = origin || '*';
53
+ }
54
+ }
55
+ else if (cfg.origin === false) {
56
+ allowOrigin = '';
57
+ }
58
+ else if (typeof cfg.origin === 'string') {
59
+ allowOrigin = cfg.origin;
60
+ }
61
+ else if (Array.isArray(cfg.origin)) {
62
+ const lowerOrigin = origin.toLowerCase();
63
+ allowOrigin = cfg.origin.some(o => o.toLowerCase() === lowerOrigin) ? origin : '';
64
+ }
65
+ else if (typeof cfg.origin === 'function') {
66
+ allowOrigin = cfg.origin(origin) ? origin : '';
67
+ }
68
+ if (!allowOrigin)
69
+ return next();
70
+ const method = ctx.request?.method || ctx.request?.raw?.method || '';
71
+ if (method === 'OPTIONS') {
72
+ return new Response(null, {
73
+ status: 204,
74
+ headers: {
75
+ 'Access-Control-Allow-Origin': allowOrigin,
76
+ 'Access-Control-Allow-Methods': (cfg.methods || []).join(', '),
77
+ 'Access-Control-Allow-Headers': cfg.headers === true
78
+ ? ctx.request.header('access-control-request-headers') || '*'
79
+ : Array.isArray(cfg.headers) ? cfg.headers.join(', ') : '',
80
+ ...(cfg.credentials ? { 'Access-Control-Allow-Credentials': 'true' } : {}),
81
+ ...(cfg.maxAge ? { 'Access-Control-Max-Age': String(cfg.maxAge) } : {}),
82
+ ...(cfg.exposeHeaders?.length ? { 'Access-Control-Expose-Headers': cfg.exposeHeaders.join(', ') } : {}),
83
+ },
84
+ });
85
+ }
86
+ ctx.store = ctx.store || {};
87
+ ctx.store.__corsHeaders = {
88
+ 'Access-Control-Allow-Origin': allowOrigin,
89
+ ...(cfg.credentials ? { 'Access-Control-Allow-Credentials': 'true' } : {}),
90
+ ...(cfg.exposeHeaders?.length ? { 'Access-Control-Expose-Headers': cfg.exposeHeaders.join(', ') } : {}),
91
+ };
92
+ await next();
93
+ };
94
+ }
@@ -0,0 +1,2 @@
1
+ export type { CorsConfig } from './types';
2
+ export { cors } from './cors';
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export { cors } from './cors';
@@ -0,0 +1,9 @@
1
+ export interface CorsConfig {
2
+ enabled?: boolean;
3
+ origin?: boolean | string | string[] | ((origin: string) => boolean);
4
+ methods?: string[];
5
+ headers?: boolean | string[];
6
+ exposeHeaders?: string[];
7
+ credentials?: boolean;
8
+ maxAge?: number;
9
+ }
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/package.json ADDED
@@ -0,0 +1,53 @@
1
+ {
2
+ "name": "@tekir/cors",
3
+ "version": "0.1.0",
4
+ "description": "CORS middleware for cross-origin requests",
5
+ "author": "dev@tekir.io",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/tekir-io/tekir.git",
10
+ "directory": "packages/tekir-cors"
11
+ },
12
+ "homepage": "https://github.com/tekir-io/tekir/tree/main/packages/tekir-cors",
13
+ "keywords": [
14
+ "tekir",
15
+ "bun",
16
+ "typescript",
17
+ "framework",
18
+ "nodejs",
19
+ "fullstack"
20
+ ],
21
+ "type": "module",
22
+ "main": "dist/index.js",
23
+ "types": "src/index.ts",
24
+ "files": [
25
+ "src",
26
+ "README.md",
27
+ "LICENSE",
28
+ "dist"
29
+ ],
30
+ "publishConfig": {
31
+ "access": "public",
32
+ "types": "dist/index.d.ts",
33
+ "exports": {
34
+ ".": {
35
+ "types": "./dist/index.d.ts",
36
+ "import": "./dist/index.js",
37
+ "default": "./dist/index.js"
38
+ }
39
+ }
40
+ },
41
+ "scripts": {
42
+ "build": "rm -rf dist && tsc --noEmit false",
43
+ "prepublishOnly": "bun run build"
44
+ },
45
+ "exports": {
46
+ ".": {
47
+ "bun": "./src/index.ts",
48
+ "types": "./src/index.ts",
49
+ "import": "./dist/index.js",
50
+ "default": "./dist/index.js"
51
+ }
52
+ }
53
+ }
package/src/cors.ts ADDED
@@ -0,0 +1,97 @@
1
+ import type { CorsConfig } from './types'
2
+
3
+ const defaults: CorsConfig = {
4
+ enabled: true,
5
+ origin: true,
6
+ methods: ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE'],
7
+ headers: true,
8
+ credentials: false,
9
+ maxAge: 86400,
10
+ }
11
+
12
+ /**
13
+ * CORS middleware that handles preflight OPTIONS requests and sets Access-Control headers.
14
+ * Supports wildcard, array, string, and function-based origin validation.
15
+ * When `credentials: true` with `origin: true`, reflects the request origin instead of using `*`.
16
+ *
17
+ * @param userConfig - CORS configuration options.
18
+ * @param userConfig.origin - Allowed origins: `true` (all), `false` (none), `string`, `string[]`, or `(origin) => boolean`.
19
+ * @param userConfig.methods - Allowed HTTP methods. Defaults to `['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE']`.
20
+ * @param userConfig.credentials - Allow credentials (cookies, auth headers). Defaults to `false`.
21
+ * @param userConfig.maxAge - Preflight cache duration in seconds. Defaults to `86400` (24h).
22
+ * @param userConfig.headers - Allowed request headers: `true` (reflect), or `string[]`.
23
+ * @param userConfig.exposeHeaders - Headers exposed to the browser.
24
+ *
25
+ * @example
26
+ * ```ts
27
+ * // Allow all origins
28
+ * app.use(cors())
29
+ *
30
+ * // Allow specific origins with credentials
31
+ * app.use(cors({
32
+ * origin: ['https://app.com', 'https://admin.app.com'],
33
+ * credentials: true,
34
+ * }))
35
+ *
36
+ * // Dynamic origin validation
37
+ * app.use(cors({
38
+ * origin: (origin) => origin.endsWith('.myapp.com'),
39
+ * }))
40
+ * ```
41
+ */
42
+ export function cors(userConfig: CorsConfig = {}) {
43
+ const cfg = { ...defaults, ...userConfig }
44
+
45
+ return async (ctx: any, next: () => Promise<void>) => {
46
+ if (!cfg.enabled) return next()
47
+
48
+ const origin = ctx.request.header('origin') || ctx.headers?.origin || ''
49
+
50
+ let allowOrigin = ''
51
+ if (cfg.origin === true) {
52
+ // When credentials are enabled, never use wildcard — reflect the request origin instead
53
+ if (cfg.credentials && origin) {
54
+ allowOrigin = origin
55
+ } else {
56
+ allowOrigin = origin || '*'
57
+ }
58
+ } else if (cfg.origin === false) {
59
+ allowOrigin = ''
60
+ } else if (typeof cfg.origin === 'string') {
61
+ allowOrigin = cfg.origin
62
+ } else if (Array.isArray(cfg.origin)) {
63
+ const lowerOrigin = origin.toLowerCase()
64
+ allowOrigin = cfg.origin.some(o => o.toLowerCase() === lowerOrigin) ? origin : ''
65
+ } else if (typeof cfg.origin === 'function') {
66
+ allowOrigin = cfg.origin(origin) ? origin : ''
67
+ }
68
+
69
+ if (!allowOrigin) return next()
70
+
71
+ const method = ctx.request?.method || ctx.request?.raw?.method || ''
72
+ if (method === 'OPTIONS') {
73
+ return new Response(null, {
74
+ status: 204,
75
+ headers: {
76
+ 'Access-Control-Allow-Origin': allowOrigin,
77
+ 'Access-Control-Allow-Methods': (cfg.methods || []).join(', '),
78
+ 'Access-Control-Allow-Headers': cfg.headers === true
79
+ ? ctx.request.header('access-control-request-headers') || '*'
80
+ : Array.isArray(cfg.headers) ? cfg.headers.join(', ') : '',
81
+ ...(cfg.credentials ? { 'Access-Control-Allow-Credentials': 'true' } : {}),
82
+ ...(cfg.maxAge ? { 'Access-Control-Max-Age': String(cfg.maxAge) } : {}),
83
+ ...(cfg.exposeHeaders?.length ? { 'Access-Control-Expose-Headers': cfg.exposeHeaders.join(', ') } : {}),
84
+ },
85
+ })
86
+ }
87
+
88
+ ctx.store = ctx.store || {}
89
+ ctx.store.__corsHeaders = {
90
+ 'Access-Control-Allow-Origin': allowOrigin,
91
+ ...(cfg.credentials ? { 'Access-Control-Allow-Credentials': 'true' } : {}),
92
+ ...(cfg.exposeHeaders?.length ? { 'Access-Control-Expose-Headers': cfg.exposeHeaders.join(', ') } : {}),
93
+ }
94
+
95
+ await next()
96
+ }
97
+ }
package/src/index.ts ADDED
@@ -0,0 +1,2 @@
1
+ export type { CorsConfig } from './types'
2
+ export { cors } from './cors'
package/src/types.ts ADDED
@@ -0,0 +1,9 @@
1
+ export interface CorsConfig {
2
+ enabled?: boolean
3
+ origin?: boolean | string | string[] | ((origin: string) => boolean)
4
+ methods?: string[]
5
+ headers?: boolean | string[]
6
+ exposeHeaders?: string[]
7
+ credentials?: boolean
8
+ maxAge?: number
9
+ }