@avijs/security 0.0.0-stage → 0.1.1

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 Christopher Robin Chase
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,23 @@
1
- # Temporary Holding Version
1
+ # @avijs/security
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ CORS and security headers for Avi.js, as `onRequest` hooks.
4
+
5
+ ```sh
6
+ npm install @avijs/security
7
+ ```
8
+
9
+ ```ts
10
+ import { createAvi } from '@avijs/core';
11
+ import { cors, securityHeaders } from '@avijs/security';
12
+
13
+ const app = createAvi({
14
+ onRequest: [securityHeaders(), cors({ origin: 'https://app.example.com' })],
15
+ });
16
+ ```
17
+
18
+ Part of [Avi.js](https://github.com/chrischase011/avi-js), a TypeScript framework for Node.js with
19
+ modules, controllers and dependency injection, without `reflect-metadata`. See the
20
+ [security chapter](https://github.com/chrischase011/avi-js/blob/main/docs/tutorial/12-security.md)
21
+ of the tutorial.
22
+
23
+ Requires Node.js 22.12 or newer. MIT licensed.
package/dist/cors.d.ts ADDED
@@ -0,0 +1,22 @@
1
+ import { type RequestHook } from '@avijs/http';
2
+ export type CorsOrigin = string | readonly string[] | RegExp | ((origin: string) => boolean);
3
+ export interface CorsOptions {
4
+ /**
5
+ * Origins allowed to call the API: `'*'` for any, an origin like `'https://app.example.com'`,
6
+ * a list, a RegExp or a function.
7
+ */
8
+ origin: CorsOrigin;
9
+ /** Methods allowed in preflights. Default: GET, HEAD, PUT, PATCH, POST, DELETE. */
10
+ methods?: readonly string[];
11
+ /** Request headers allowed in preflights. Default: the headers the browser asks for. */
12
+ allowedHeaders?: readonly string[];
13
+ /** Response headers the browser may read. */
14
+ exposedHeaders?: readonly string[];
15
+ /** Allow cookies and `Authorization`. Requires explicit origins. */
16
+ credentials?: boolean;
17
+ /** How long browsers may cache a preflight, in seconds. */
18
+ maxAge?: number;
19
+ }
20
+ /** CORS as an `onRequest` hook: answers preflights and adds headers to allowed origins. */
21
+ export declare function cors(options: CorsOptions): RequestHook;
22
+ //# sourceMappingURL=cors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cors.d.ts","sourceRoot":"","sources":["../src/cors.ts"],"names":[],"mappings":"AAAA,OAAO,EAAS,KAAK,WAAW,EAAE,MAAM,aAAa,CAAC;AAGtD,MAAM,MAAM,UAAU,GAAG,MAAM,GAAG,SAAS,MAAM,EAAE,GAAG,MAAM,GAAG,CAAC,CAAC,MAAM,EAAE,MAAM,KAAK,OAAO,CAAC,CAAC;AAE7F,MAAM,WAAW,WAAW;IAC1B;;;OAGG;IACH,MAAM,EAAE,UAAU,CAAC;IACnB,mFAAmF;IACnF,OAAO,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC5B,wFAAwF;IACxF,cAAc,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACnC,6CAA6C;IAC7C,cAAc,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACnC,oEAAoE;IACpE,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,2DAA2D;IAC3D,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAMD,2FAA2F;AAC3F,wBAAgB,IAAI,CAAC,OAAO,EAAE,WAAW,GAAG,WAAW,CA6CtD"}
package/dist/cors.js ADDED
@@ -0,0 +1,93 @@
1
+ import { reply } from '@avijs/http';
2
+ const DEFAULT_METHODS = ['GET', 'HEAD', 'PUT', 'PATCH', 'POST', 'DELETE'];
3
+ const VISIBLE_ASCII = /^[!-~]+$/;
4
+ const TOKEN_LIST = /^[\w!#$%&'*+.^`|~-]+(?:[ \t]*,[ \t]*[\w!#$%&'*+.^`|~-]+)*$/;
5
+ /** CORS as an `onRequest` hook: answers preflights and adds headers to allowed origins. */
6
+ export function cors(options) {
7
+ const any = options.origin === '*';
8
+ const allows = originMatcher(options.origin);
9
+ const credentials = options.credentials === true;
10
+ if (any && credentials) {
11
+ throw new TypeError("cors: credentials cannot be used with origin '*'; list the origins");
12
+ }
13
+ const methods = (options.methods ?? DEFAULT_METHODS).join(', ');
14
+ const allowedHeaders = options.allowedHeaders?.join(', ');
15
+ const exposed = options.exposedHeaders?.length ? options.exposedHeaders.join(', ') : undefined;
16
+ const maxAge = options.maxAge === undefined ? undefined : seconds(options.maxAge);
17
+ return (ctx) => {
18
+ if (!any)
19
+ ctx.setHeader('vary', 'Origin');
20
+ const origin = ctx.headers.origin;
21
+ if (origin === undefined || !VISIBLE_ASCII.test(origin) || !allows(origin))
22
+ return undefined;
23
+ const allowOrigin = any ? '*' : origin;
24
+ const requestMethod = ctx.headers['access-control-request-method'];
25
+ if (ctx.method === 'OPTIONS' && requestMethod !== undefined) {
26
+ const headers = {
27
+ 'access-control-allow-origin': allowOrigin,
28
+ 'access-control-allow-methods': methods,
29
+ };
30
+ if (credentials)
31
+ headers['access-control-allow-credentials'] = 'true';
32
+ if (maxAge !== undefined)
33
+ headers['access-control-max-age'] = maxAge;
34
+ if (allowedHeaders !== undefined) {
35
+ headers['access-control-allow-headers'] = allowedHeaders;
36
+ }
37
+ else {
38
+ headers.vary = any
39
+ ? 'Access-Control-Request-Headers'
40
+ : 'Origin, Access-Control-Request-Headers';
41
+ const requested = ctx.headers['access-control-request-headers'];
42
+ if (requested !== undefined && TOKEN_LIST.test(requested)) {
43
+ headers['access-control-allow-headers'] = requested;
44
+ }
45
+ }
46
+ return reply(undefined, { status: 204, headers });
47
+ }
48
+ ctx.setHeader('access-control-allow-origin', allowOrigin);
49
+ if (credentials)
50
+ ctx.setHeader('access-control-allow-credentials', 'true');
51
+ if (exposed !== undefined)
52
+ ctx.setHeader('access-control-expose-headers', exposed);
53
+ return undefined;
54
+ };
55
+ }
56
+ function originMatcher(origin) {
57
+ if (origin === '*')
58
+ return () => true;
59
+ if (typeof origin === 'function')
60
+ return origin;
61
+ if (origin instanceof RegExp) {
62
+ return (value) => {
63
+ origin.lastIndex = 0;
64
+ return origin.test(value);
65
+ };
66
+ }
67
+ const list = typeof origin === 'string' ? [origin] : origin;
68
+ if (!Array.isArray(list) || list.length === 0) {
69
+ throw new TypeError('cors: origin must be set');
70
+ }
71
+ const allowed = new Set(list.map(checkOrigin));
72
+ return (value) => allowed.has(value);
73
+ }
74
+ function checkOrigin(value) {
75
+ let parsed;
76
+ try {
77
+ parsed = new URL(value);
78
+ }
79
+ catch {
80
+ parsed = undefined;
81
+ }
82
+ if (parsed?.origin !== value) {
83
+ throw new TypeError(`cors: '${value}' is not an origin. Use scheme, host and optional port, like 'https://example.com'`);
84
+ }
85
+ return value;
86
+ }
87
+ function seconds(value) {
88
+ if (!Number.isInteger(value) || value < 0) {
89
+ throw new RangeError(`cors: maxAge must be a non-negative integer, got ${String(value)}`);
90
+ }
91
+ return String(value);
92
+ }
93
+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,IAAI,CAAC;QACH,MAAM,GAAG,IAAI,GAAG,CAAC,KAAK,CAAC,CAAC;IAC1B,CAAC;IAAC,MAAM,CAAC;QACP,MAAM,GAAG,SAAS,CAAC;IACrB,CAAC;IACD,IAAI,MAAM,EAAE,MAAM,KAAK,KAAK,EAAE,CAAC;QAC7B,MAAM,IAAI,SAAS,CACjB,UAAU,KAAK,oFAAoF,CACpG,CAAC;IACJ,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC;AAED,SAAS,OAAO,CAAC,KAAa;IAC5B,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,KAAK,GAAG,CAAC,EAAE,CAAC;QAC1C,MAAM,IAAI,UAAU,CAAC,oDAAoD,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;IAC5F,CAAC;IACD,OAAO,MAAM,CAAC,KAAK,CAAC,CAAC;AACvB,CAAC"}
@@ -0,0 +1,19 @@
1
+ import type { RequestHook } from '@avijs/http';
2
+ export interface SecurityHeadersOptions {
3
+ /** Default: `default-src 'none'; frame-ancestors 'none'`, for JSON APIs. Relax it to serve HTML. */
4
+ contentSecurityPolicy?: string | false;
5
+ /** Default: `max-age=31536000; includeSubDomains`. Browsers only honor it over HTTPS. */
6
+ strictTransportSecurity?: string | false;
7
+ /** Default: `DENY`. */
8
+ frameOptions?: 'DENY' | 'SAMEORIGIN' | false;
9
+ /** Default: `no-referrer`. */
10
+ referrerPolicy?: string | false;
11
+ /** Default: `same-origin`. Use `cross-origin` for public assets embedded elsewhere. */
12
+ crossOriginResourcePolicy?: 'same-origin' | 'same-site' | 'cross-origin' | false;
13
+ }
14
+ /**
15
+ * Common security headers as an `onRequest` hook. Pass `false` to leave one out. Headers set by
16
+ * a handler with `reply()` win. `X-Content-Type-Options: nosniff` is always sent by Avi.js.
17
+ */
18
+ export declare function securityHeaders(options?: SecurityHeadersOptions): RequestHook;
19
+ //# sourceMappingURL=headers.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"headers.d.ts","sourceRoot":"","sources":["../src/headers.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAG/C,MAAM,WAAW,sBAAsB;IACrC,oGAAoG;IACpG,qBAAqB,CAAC,EAAE,MAAM,GAAG,KAAK,CAAC;IACvC,yFAAyF;IACzF,uBAAuB,CAAC,EAAE,MAAM,GAAG,KAAK,CAAC;IACzC,uBAAuB;IACvB,YAAY,CAAC,EAAE,MAAM,GAAG,YAAY,GAAG,KAAK,CAAC;IAC7C,8BAA8B;IAC9B,cAAc,CAAC,EAAE,MAAM,GAAG,KAAK,CAAC;IAChC,uFAAuF;IACvF,yBAAyB,CAAC,EAAE,aAAa,GAAG,WAAW,GAAG,cAAc,GAAG,KAAK,CAAC;CAClF;AAED;;;GAGG;AACH,wBAAgB,eAAe,CAAC,OAAO,GAAE,sBAA2B,GAAG,WAAW,CA2BjF"}
@@ -0,0 +1,26 @@
1
+ import { validateHeaderValue } from 'node:http';
2
+ /**
3
+ * Common security headers as an `onRequest` hook. Pass `false` to leave one out. Headers set by
4
+ * a handler with `reply()` win. `X-Content-Type-Options: nosniff` is always sent by Avi.js.
5
+ */
6
+ export function securityHeaders(options = {}) {
7
+ const entries = [];
8
+ const add = (name, value, fallback) => {
9
+ if (value === false)
10
+ return;
11
+ const resolved = value ?? fallback;
12
+ validateHeaderValue(name, resolved);
13
+ entries.push([name, resolved]);
14
+ };
15
+ add('content-security-policy', options.contentSecurityPolicy, "default-src 'none'; frame-ancestors 'none'");
16
+ add('strict-transport-security', options.strictTransportSecurity, 'max-age=31536000; includeSubDomains');
17
+ add('x-frame-options', options.frameOptions, 'DENY');
18
+ add('referrer-policy', options.referrerPolicy, 'no-referrer');
19
+ add('cross-origin-resource-policy', options.crossOriginResourcePolicy, 'same-origin');
20
+ return (ctx) => {
21
+ for (const [name, value] of entries)
22
+ ctx.setHeader(name, value);
23
+ return undefined;
24
+ };
25
+ }
26
+ //# sourceMappingURL=headers.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"headers.js","sourceRoot":"","sources":["../src/headers.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAC;AAehD;;;GAGG;AACH,MAAM,UAAU,eAAe,CAAC,UAAkC,EAAE;IAClE,MAAM,OAAO,GAAuB,EAAE,CAAC;IACvC,MAAM,GAAG,GAAG,CAAC,IAAY,EAAE,KAAiC,EAAE,QAAgB,EAAE,EAAE;QAChF,IAAI,KAAK,KAAK,KAAK;YAAE,OAAO;QAC5B,MAAM,QAAQ,GAAG,KAAK,IAAI,QAAQ,CAAC;QACnC,mBAAmB,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;QACpC,OAAO,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC,CAAC;IACjC,CAAC,CAAC;IAEF,GAAG,CACD,yBAAyB,EACzB,OAAO,CAAC,qBAAqB,EAC7B,4CAA4C,CAC7C,CAAC;IACF,GAAG,CACD,2BAA2B,EAC3B,OAAO,CAAC,uBAAuB,EAC/B,qCAAqC,CACtC,CAAC;IACF,GAAG,CAAC,iBAAiB,EAAE,OAAO,CAAC,YAAY,EAAE,MAAM,CAAC,CAAC;IACrD,GAAG,CAAC,iBAAiB,EAAE,OAAO,CAAC,cAAc,EAAE,aAAa,CAAC,CAAC;IAC9D,GAAG,CAAC,8BAA8B,EAAE,OAAO,CAAC,yBAAyB,EAAE,aAAa,CAAC,CAAC;IAEtF,OAAO,CAAC,GAAG,EAAE,EAAE;QACb,KAAK,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,IAAI,OAAO;YAAE,GAAG,CAAC,SAAS,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;QAChE,OAAO,SAAS,CAAC;IACnB,CAAC,CAAC;AACJ,CAAC"}
@@ -0,0 +1,5 @@
1
+ export { cors } from './cors.js';
2
+ export type { CorsOptions, CorsOrigin } from './cors.js';
3
+ export { securityHeaders } from './headers.js';
4
+ export type { SecurityHeadersOptions } from './headers.js';
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,YAAY,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AACzD,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAC/C,YAAY,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { cors } from './cors.js';
2
+ export { securityHeaders } from './headers.js';
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEjC,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,50 @@
1
1
  {
2
2
  "name": "@avijs/security",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.1",
4
+ "description": "CORS and security headers for Avi.js.",
5
+ "keywords": [
6
+ "avi",
7
+ "avi.js",
8
+ "cors",
9
+ "security",
10
+ "headers"
11
+ ],
12
+ "license": "MIT",
13
+ "author": "Christopher Robin Chase",
14
+ "homepage": "https://github.com/chrischase011/avi-js#readme",
15
+ "bugs": {
16
+ "url": "https://github.com/chrischase011/avi-js/issues"
17
+ },
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "git+https://github.com/chrischase011/avi-js.git",
21
+ "directory": "packages/security"
22
+ },
23
+ "type": "module",
24
+ "engines": {
25
+ "node": ">=22.12"
26
+ },
27
+ "sideEffects": false,
28
+ "exports": {
29
+ ".": {
30
+ "@avijs/source": "./src/index.ts",
31
+ "types": "./dist/index.d.ts",
32
+ "default": "./dist/index.js"
33
+ }
34
+ },
35
+ "files": [
36
+ "dist",
37
+ "src",
38
+ "README.md",
39
+ "LICENSE"
40
+ ],
41
+ "publishConfig": {
42
+ "access": "public"
43
+ },
44
+ "dependencies": {
45
+ "@avijs/http": "0.1.1"
46
+ },
47
+ "scripts": {
48
+ "typecheck": "tsc -p tsconfig.json"
49
+ }
6
50
  }
package/src/cors.ts ADDED
@@ -0,0 +1,113 @@
1
+ import { reply, type RequestHook } from '@avijs/http';
2
+ import type { OutgoingHttpHeaders } from 'node:http';
3
+
4
+ export type CorsOrigin = string | readonly string[] | RegExp | ((origin: string) => boolean);
5
+
6
+ export interface CorsOptions {
7
+ /**
8
+ * Origins allowed to call the API: `'*'` for any, an origin like `'https://app.example.com'`,
9
+ * a list, a RegExp or a function.
10
+ */
11
+ origin: CorsOrigin;
12
+ /** Methods allowed in preflights. Default: GET, HEAD, PUT, PATCH, POST, DELETE. */
13
+ methods?: readonly string[];
14
+ /** Request headers allowed in preflights. Default: the headers the browser asks for. */
15
+ allowedHeaders?: readonly string[];
16
+ /** Response headers the browser may read. */
17
+ exposedHeaders?: readonly string[];
18
+ /** Allow cookies and `Authorization`. Requires explicit origins. */
19
+ credentials?: boolean;
20
+ /** How long browsers may cache a preflight, in seconds. */
21
+ maxAge?: number;
22
+ }
23
+
24
+ const DEFAULT_METHODS = ['GET', 'HEAD', 'PUT', 'PATCH', 'POST', 'DELETE'];
25
+ const VISIBLE_ASCII = /^[!-~]+$/;
26
+ const TOKEN_LIST = /^[\w!#$%&'*+.^`|~-]+(?:[ \t]*,[ \t]*[\w!#$%&'*+.^`|~-]+)*$/;
27
+
28
+ /** CORS as an `onRequest` hook: answers preflights and adds headers to allowed origins. */
29
+ export function cors(options: CorsOptions): RequestHook {
30
+ const any = options.origin === '*';
31
+ const allows = originMatcher(options.origin);
32
+ const credentials = options.credentials === true;
33
+ if (any && credentials) {
34
+ throw new TypeError("cors: credentials cannot be used with origin '*'; list the origins");
35
+ }
36
+ const methods = (options.methods ?? DEFAULT_METHODS).join(', ');
37
+ const allowedHeaders = options.allowedHeaders?.join(', ');
38
+ const exposed = options.exposedHeaders?.length ? options.exposedHeaders.join(', ') : undefined;
39
+ const maxAge = options.maxAge === undefined ? undefined : seconds(options.maxAge);
40
+
41
+ return (ctx) => {
42
+ if (!any) ctx.setHeader('vary', 'Origin');
43
+ const origin = ctx.headers.origin;
44
+ if (origin === undefined || !VISIBLE_ASCII.test(origin) || !allows(origin)) return undefined;
45
+
46
+ const allowOrigin = any ? '*' : origin;
47
+ const requestMethod = ctx.headers['access-control-request-method'];
48
+ if (ctx.method === 'OPTIONS' && requestMethod !== undefined) {
49
+ const headers: OutgoingHttpHeaders = {
50
+ 'access-control-allow-origin': allowOrigin,
51
+ 'access-control-allow-methods': methods,
52
+ };
53
+ if (credentials) headers['access-control-allow-credentials'] = 'true';
54
+ if (maxAge !== undefined) headers['access-control-max-age'] = maxAge;
55
+ if (allowedHeaders !== undefined) {
56
+ headers['access-control-allow-headers'] = allowedHeaders;
57
+ } else {
58
+ headers.vary = any
59
+ ? 'Access-Control-Request-Headers'
60
+ : 'Origin, Access-Control-Request-Headers';
61
+ const requested = ctx.headers['access-control-request-headers'];
62
+ if (requested !== undefined && TOKEN_LIST.test(requested)) {
63
+ headers['access-control-allow-headers'] = requested;
64
+ }
65
+ }
66
+ return reply(undefined, { status: 204, headers });
67
+ }
68
+
69
+ ctx.setHeader('access-control-allow-origin', allowOrigin);
70
+ if (credentials) ctx.setHeader('access-control-allow-credentials', 'true');
71
+ if (exposed !== undefined) ctx.setHeader('access-control-expose-headers', exposed);
72
+ return undefined;
73
+ };
74
+ }
75
+
76
+ function originMatcher(origin: CorsOrigin): (value: string) => boolean {
77
+ if (origin === '*') return () => true;
78
+ if (typeof origin === 'function') return origin;
79
+ if (origin instanceof RegExp) {
80
+ return (value) => {
81
+ origin.lastIndex = 0;
82
+ return origin.test(value);
83
+ };
84
+ }
85
+ const list = typeof origin === 'string' ? [origin] : origin;
86
+ if (!Array.isArray(list) || list.length === 0) {
87
+ throw new TypeError('cors: origin must be set');
88
+ }
89
+ const allowed = new Set(list.map(checkOrigin));
90
+ return (value) => allowed.has(value);
91
+ }
92
+
93
+ function checkOrigin(value: string): string {
94
+ let parsed: URL | undefined;
95
+ try {
96
+ parsed = new URL(value);
97
+ } catch {
98
+ parsed = undefined;
99
+ }
100
+ if (parsed?.origin !== value) {
101
+ throw new TypeError(
102
+ `cors: '${value}' is not an origin. Use scheme, host and optional port, like 'https://example.com'`,
103
+ );
104
+ }
105
+ return value;
106
+ }
107
+
108
+ function seconds(value: number): string {
109
+ if (!Number.isInteger(value) || value < 0) {
110
+ throw new RangeError(`cors: maxAge must be a non-negative integer, got ${String(value)}`);
111
+ }
112
+ return String(value);
113
+ }
package/src/headers.ts ADDED
@@ -0,0 +1,48 @@
1
+ import type { RequestHook } from '@avijs/http';
2
+ import { validateHeaderValue } from 'node:http';
3
+
4
+ export interface SecurityHeadersOptions {
5
+ /** Default: `default-src 'none'; frame-ancestors 'none'`, for JSON APIs. Relax it to serve HTML. */
6
+ contentSecurityPolicy?: string | false;
7
+ /** Default: `max-age=31536000; includeSubDomains`. Browsers only honor it over HTTPS. */
8
+ strictTransportSecurity?: string | false;
9
+ /** Default: `DENY`. */
10
+ frameOptions?: 'DENY' | 'SAMEORIGIN' | false;
11
+ /** Default: `no-referrer`. */
12
+ referrerPolicy?: string | false;
13
+ /** Default: `same-origin`. Use `cross-origin` for public assets embedded elsewhere. */
14
+ crossOriginResourcePolicy?: 'same-origin' | 'same-site' | 'cross-origin' | false;
15
+ }
16
+
17
+ /**
18
+ * Common security headers as an `onRequest` hook. Pass `false` to leave one out. Headers set by
19
+ * a handler with `reply()` win. `X-Content-Type-Options: nosniff` is always sent by Avi.js.
20
+ */
21
+ export function securityHeaders(options: SecurityHeadersOptions = {}): RequestHook {
22
+ const entries: [string, string][] = [];
23
+ const add = (name: string, value: string | false | undefined, fallback: string) => {
24
+ if (value === false) return;
25
+ const resolved = value ?? fallback;
26
+ validateHeaderValue(name, resolved);
27
+ entries.push([name, resolved]);
28
+ };
29
+
30
+ add(
31
+ 'content-security-policy',
32
+ options.contentSecurityPolicy,
33
+ "default-src 'none'; frame-ancestors 'none'",
34
+ );
35
+ add(
36
+ 'strict-transport-security',
37
+ options.strictTransportSecurity,
38
+ 'max-age=31536000; includeSubDomains',
39
+ );
40
+ add('x-frame-options', options.frameOptions, 'DENY');
41
+ add('referrer-policy', options.referrerPolicy, 'no-referrer');
42
+ add('cross-origin-resource-policy', options.crossOriginResourcePolicy, 'same-origin');
43
+
44
+ return (ctx) => {
45
+ for (const [name, value] of entries) ctx.setHeader(name, value);
46
+ return undefined;
47
+ };
48
+ }
package/src/index.ts ADDED
@@ -0,0 +1,4 @@
1
+ export { cors } from './cors.js';
2
+ export type { CorsOptions, CorsOrigin } from './cors.js';
3
+ export { securityHeaders } from './headers.js';
4
+ export type { SecurityHeadersOptions } from './headers.js';