@nexusts/shield 0.7.0 → 0.7.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/README.md +2 -2
- package/dist/guards/csrf.d.ts +32 -0
- package/dist/guards/headers.d.ts +21 -0
- package/dist/guards/index.d.ts +5 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +4 -4
- package/dist/index.js.map +4 -4
- package/dist/shield.module.d.ts +24 -0
- package/dist/shield.service.d.ts +20 -0
- package/dist/types.d.ts +94 -0
- package/package.json +6 -11
package/README.md
CHANGED
|
@@ -15,7 +15,7 @@ This module is part of the NexusTS monorepo. Each module is published as its own
|
|
|
15
15
|
Most apps start with just the core:
|
|
16
16
|
|
|
17
17
|
```bash
|
|
18
|
-
bun add @nexusts/core
|
|
18
|
+
bun add @nexusts/core
|
|
19
19
|
```
|
|
20
20
|
|
|
21
21
|
Then add this module only if you need it:
|
|
@@ -26,7 +26,7 @@ bun add @nexusts/shield
|
|
|
26
26
|
|
|
27
27
|
## Peer dependencies
|
|
28
28
|
|
|
29
|
-
None
|
|
29
|
+
**None.** No external dependencies.
|
|
30
30
|
|
|
31
31
|
## Usage
|
|
32
32
|
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CSRF guard — synchronizer token pattern.
|
|
3
|
+
*
|
|
4
|
+
* On `GET` (or any non-mutating request) we ensure a `nexus-csrf` cookie
|
|
5
|
+
* is set. On `POST`/`PUT`/`DELETE`/`PATCH` we read the cookie, then
|
|
6
|
+
* compare it against the `X-CSRF-Token` header (or `_csrf` form field).
|
|
7
|
+
*
|
|
8
|
+
* Both values must match (constant-time compare) for the request to pass.
|
|
9
|
+
*/
|
|
10
|
+
import type { CsrfConfig, CsrfToken } from "../types.js";
|
|
11
|
+
export declare class CsrfGuard {
|
|
12
|
+
private config;
|
|
13
|
+
private secret;
|
|
14
|
+
constructor(config: CsrfConfig, secret: string);
|
|
15
|
+
/**
|
|
16
|
+
* Issue a CSRF token. Sets the cookie on the response.
|
|
17
|
+
*/
|
|
18
|
+
issue(res: Headers): CsrfToken;
|
|
19
|
+
/**
|
|
20
|
+
* Verify a request. Returns `true` if the request is allowed.
|
|
21
|
+
*/
|
|
22
|
+
verify(req: {
|
|
23
|
+
method: string;
|
|
24
|
+
headers: Headers;
|
|
25
|
+
}): boolean;
|
|
26
|
+
/**
|
|
27
|
+
* Build a Hono middleware. Sets the cookie on every safe request and
|
|
28
|
+
* enforces the check on mutating ones.
|
|
29
|
+
*/
|
|
30
|
+
middleware(): (c: any, next: () => Promise<any>) => Promise<any>;
|
|
31
|
+
private extractCookie;
|
|
32
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Security headers middleware. Sets HSTS, X-Frame-Options,
|
|
3
|
+
* X-Content-Type-Options, Referrer-Policy, and CSP on every response.
|
|
4
|
+
*/
|
|
5
|
+
import type { CspConfig, HstsConfig } from "../types.js";
|
|
6
|
+
export declare class HeadersGuard {
|
|
7
|
+
hsts: HstsConfig | false;
|
|
8
|
+
csp: CspConfig | false;
|
|
9
|
+
xFrameOptions: "DENY" | "SAMEORIGIN" | false;
|
|
10
|
+
xContentTypeOptions: boolean;
|
|
11
|
+
referrerPolicy: string | undefined;
|
|
12
|
+
constructor(hsts: HstsConfig | false, csp: CspConfig | false, xFrameOptions: "DENY" | "SAMEORIGIN" | false, xContentTypeOptions: boolean, referrerPolicy: string | undefined);
|
|
13
|
+
/**
|
|
14
|
+
* Apply configured headers to the given `Headers` instance in place.
|
|
15
|
+
* Useful when you already have a Response and want to enrich it.
|
|
16
|
+
*/
|
|
17
|
+
apply(headers: Headers): void;
|
|
18
|
+
middleware(): (_c: any, next: () => Promise<any>) => Promise<any>;
|
|
19
|
+
private buildHstsHeader;
|
|
20
|
+
private buildCspHeader;
|
|
21
|
+
}
|
package/dist/index.d.ts
ADDED
package/dist/index.js
CHANGED
|
@@ -18,7 +18,7 @@ var __legacyMetadataTS = (k, v) => {
|
|
|
18
18
|
// packages/shield/src/types.ts
|
|
19
19
|
import"reflect-metadata";
|
|
20
20
|
import { randomBytes } from "crypto";
|
|
21
|
-
import { EncryptionService } from "@nexusts/crypto
|
|
21
|
+
import { EncryptionService } from "@nexusts/crypto";
|
|
22
22
|
function randomToken(bytes = 24) {
|
|
23
23
|
return randomBytes(bytes).toString("base64url");
|
|
24
24
|
}
|
|
@@ -190,7 +190,7 @@ function camelToKebab(s) {
|
|
|
190
190
|
return s.replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`);
|
|
191
191
|
}
|
|
192
192
|
// packages/shield/src/shield.service.ts
|
|
193
|
-
import { Inject, Injectable } from "@nexusts/core
|
|
193
|
+
import { Inject, Injectable } from "@nexusts/core";
|
|
194
194
|
class ShieldService {
|
|
195
195
|
static TOKEN = Symbol.for("nexus:ShieldService");
|
|
196
196
|
csrf;
|
|
@@ -246,7 +246,7 @@ ShieldService = __legacyDecorateClassTS([
|
|
|
246
246
|
], ShieldService);
|
|
247
247
|
// packages/shield/src/shield.module.ts
|
|
248
248
|
import"reflect-metadata";
|
|
249
|
-
import { Module } from "@nexusts/core
|
|
249
|
+
import { Module } from "@nexusts/core";
|
|
250
250
|
class ShieldModule {
|
|
251
251
|
static forRoot(config = {}) {
|
|
252
252
|
class ConfiguredShieldModule {
|
|
@@ -284,5 +284,5 @@ export {
|
|
|
284
284
|
CsrfGuard
|
|
285
285
|
};
|
|
286
286
|
|
|
287
|
-
//# debugId=
|
|
287
|
+
//# debugId=78F89FE2F2B0E78F64756E2164756E21
|
|
288
288
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -2,13 +2,13 @@
|
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/types.ts", "../src/guards/csrf.ts", "../src/guards/headers.ts", "../src/shield.service.ts", "../src/shield.module.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
|
-
"/**\n * `nexusjs/shield` — security middleware suite.\n *\n * Inspired by AdonisJS Shield. Provides:\n * - CSRF protection (synchronizer token pattern)\n * - Security headers (X-Frame-Options, X-Content-Type-Options, Referrer-Policy)\n * - HSTS (Strict-Transport-Security)\n * - CSP (Content-Security-Policy) — optional\n * - XSS filter (browser-level, for legacy browsers)\n *\n * @Module({\n * imports: [\n * ShieldModule.forRoot({\n * csrf: { enabled: true },\n * hsts: { maxAge: 31_536_000, includeSubDomains: true },\n * csp: { directives: { defaultSrc: [\"'self'\"] } },\n * }),\n * ],\n * })\n * export class AppModule {}\n */\n\nimport \"reflect-metadata\";\nimport { randomBytes } from \"node:crypto\";\nimport { EncryptionService } from \"@nexusts/crypto
|
|
5
|
+
"/**\n * `nexusjs/shield` — security middleware suite.\n *\n * Inspired by AdonisJS Shield. Provides:\n * - CSRF protection (synchronizer token pattern)\n * - Security headers (X-Frame-Options, X-Content-Type-Options, Referrer-Policy)\n * - HSTS (Strict-Transport-Security)\n * - CSP (Content-Security-Policy) — optional\n * - XSS filter (browser-level, for legacy browsers)\n *\n * @Module({\n * imports: [\n * ShieldModule.forRoot({\n * csrf: { enabled: true },\n * hsts: { maxAge: 31_536_000, includeSubDomains: true },\n * csp: { directives: { defaultSrc: [\"'self'\"] } },\n * }),\n * ],\n * })\n * export class AppModule {}\n */\n\nimport \"reflect-metadata\";\nimport { randomBytes } from \"node:crypto\";\nimport { EncryptionService } from \"@nexusts/crypto\";\n\n/** CSRF protection configuration. */\nexport interface CsrfConfig {\n\tenabled: boolean;\n\t/** Cookie name. Default: 'nexus-csrf'. */\n\tcookieName?: string;\n\t/** Header name expected from clients. Default: 'x-csrf-token'. */\n\theaderName?: string;\n\t/** Form field name. Default: '_csrf'. */\n\tfieldName?: string;\n\t/** Whether to require the token on GET. Default: false. */\n\tprotectGet?: boolean;\n\t/** Cookie attributes. */\n\tcookie?: {\n\t\tsameSite?: \"Strict\" | \"Lax\" | \"None\";\n\t\tsecure?: boolean;\n\t\thttpOnly?: boolean;\n\t\tpath?: string;\n\t};\n\t/** Methods that bypass CSRF check. Default: ['GET', 'HEAD', 'OPTIONS']. */\n\tignoreMethods?: string[];\n}\n\n/** HSTS configuration. */\nexport interface HstsConfig {\n\tmaxAge: number;\n\tincludeSubDomains?: boolean;\n\tpreload?: boolean;\n}\n\n/** CSP configuration. */\nexport interface CspConfig {\n\tdirectives: Record<string, string[]>;\n\treportOnly?: boolean;\n\treportUri?: string;\n}\n\n/** Top-level Shield config. */\nexport interface ShieldConfig {\n\tcsrf?: CsrfConfig | false;\n\thsts?: HstsConfig | false;\n\tcsp?: CspConfig | false;\n\txFrameOptions?: \"DENY\" | \"SAMEORIGIN\" | false;\n\txContentTypeOptions?: boolean;\n\treferrerPolicy?: string;\n\t/** Secret used to sign CSRF tokens. */\n\tsecret?: string;\n}\n\n/** CSRF token (synchronizer pattern). */\nexport interface CsrfToken {\n\t/** The token to embed in forms/headers. */\n\ttoken: string;\n\t/** A pre-formed <meta> tag. */\n\thtml: string;\n}\n\n/** Generate a random base64url string. */\nfunction randomToken(bytes = 24): string {\n\treturn randomBytes(bytes).toString(\"base64url\");\n}\n\n/**\n * Sign `value` with `secret` using EncryptionService.\n *\n * Returns the signed value in `<value>.<signature>` format. The\n * HMAC is HKDF-derived from the secret + purpose tag (\"csrf\"), so\n * a CSRF token can't be replayed as another-purpose token.\n */\nfunction sign(value: string, secret: string): string {\n\tconst sig = new EncryptionService(secret).signRaw(value, \"csrf\");\n\treturn `${value}.${sig}`;\n}\n\n/**\n * Verify a signed token. Returns the original value on success,\n * `null` on failure (tampered, wrong purpose, malformed).\n */\nfunction verify(signed: string, secret: string): string | null {\n\tconst lastDot = signed.lastIndexOf(\".\");\n\tif (lastDot < 1) return null;\n\tconst value = signed.slice(0, lastDot);\n\tconst sig = signed.slice(lastDot + 1);\n\tif (!new EncryptionService(secret).verifyRaw(value, sig, \"csrf\")) return null;\n\treturn value;\n}\n\nexport const ShieldInternals = {\n\tsign,\n\tverify,\n\trandomToken,\n};\n",
|
|
6
6
|
"/**\n * CSRF guard — synchronizer token pattern.\n *\n * On `GET` (or any non-mutating request) we ensure a `nexus-csrf` cookie\n * is set. On `POST`/`PUT`/`DELETE`/`PATCH` we read the cookie, then\n * compare it against the `X-CSRF-Token` header (or `_csrf` form field).\n *\n * Both values must match (constant-time compare) for the request to pass.\n */\nimport type { CsrfConfig, CsrfToken } from \"../types.js\";\nimport { ShieldInternals } from \"../types.js\";\n\nexport class CsrfGuard {\n\tprivate config: Required<CsrfConfig>;\n\tprivate secret: string;\n\n\tconstructor(config: CsrfConfig, secret: string) {\n\t\tthis.config = {\n\t\t\tenabled: config.enabled,\n\t\t\tcookieName: config.cookieName ?? \"nexus-csrf\",\n\t\t\theaderName: config.headerName ?? \"x-csrf-token\",\n\t\t\tfieldName: config.fieldName ?? \"_csrf\",\n\t\t\tprotectGet: config.protectGet ?? false,\n\t\t\tcookie: {\n\t\t\t\tsameSite: config.cookie?.sameSite ?? \"Lax\",\n\t\t\t\tsecure: config.cookie?.secure ?? true,\n\t\t\t\thttpOnly: config.cookie?.httpOnly ?? false,\n\t\t\t\tpath: config.cookie?.path ?? \"/\",\n\t\t\t},\n\t\t\tignoreMethods: config.ignoreMethods ?? [\"GET\", \"HEAD\", \"OPTIONS\"],\n\t\t};\n\t\tthis.secret = secret;\n\t}\n\n\t/**\n\t * Issue a CSRF token. Sets the cookie on the response.\n\t */\n\tissue(res: Headers): CsrfToken {\n\t\tconst raw = ShieldInternals.randomToken();\n\t\tconst signed = ShieldInternals.sign(raw, this.secret);\n\t\t// Set the cookie. The unsigned value is stored.\n\t\tconst cookieParts = [\n\t\t\t`${this.config.cookieName}=${raw}`,\n\t\t\t`Path=${this.config.cookie.path}`,\n\t\t\t`SameSite=${this.config.cookie.sameSite}`,\n\t\t];\n\t\tif (this.config.cookie.secure) cookieParts.push(\"Secure\");\n\t\tif (this.config.cookie.httpOnly) cookieParts.push(\"HttpOnly\");\n\t\tres.append(\"Set-Cookie\", cookieParts.join(\"; \"));\n\t\treturn {\n\t\t\ttoken: signed,\n\t\t\thtml: `<meta name=\"csrf-token\" content=\"${signed}\">`,\n\t\t};\n\t}\n\n\t/**\n\t * Verify a request. Returns `true` if the request is allowed.\n\t */\n\tverify(req: { method: string; headers: Headers }): boolean {\n\t\tconst method = req.method.toUpperCase();\n\t\tif (\n\t\t\tthis.config.ignoreMethods.map((m) => m.toUpperCase()).includes(method)\n\t\t) {\n\t\t\treturn true;\n\t\t}\n\t\tif (this.config.protectGet) {\n\t\t\t// (no-op; protectGet currently shares ignoreMethods logic)\n\t\t}\n\t\tconst cookieHeader = req.headers.get(\"cookie\") ?? \"\";\n\t\tconst cookieToken = this.extractCookie(\n\t\t\tcookieHeader,\n\t\t\tthis.config.cookieName,\n\t\t);\n\t\tif (!cookieToken) return false;\n\t\t// Header value\n\t\tconst headerToken = req.headers.get(this.config.headerName);\n\t\tif (\n\t\t\theaderToken &&\n\t\t\tShieldInternals.verify(headerToken, this.secret) === cookieToken\n\t\t) {\n\t\t\treturn true;\n\t\t}\n\t\t// Form field (parsed from x-www-form-urlencoded body or multipart)\n\t\t// For simplicity, we accept a custom header `x-csrf-field` with the value.\n\t\tconst fieldToken = req.headers.get(\"x-csrf-field\");\n\t\tif (\n\t\t\tfieldToken &&\n\t\t\tShieldInternals.verify(fieldToken, this.secret) === cookieToken\n\t\t) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * Build a Hono middleware. Sets the cookie on every safe request and\n\t * enforces the check on mutating ones.\n\t */\n\tmiddleware() {\n\t\treturn async (c: any, next: () => Promise<any>) => {\n\t\t\tconst method = (c.req.method as string).toUpperCase();\n\t\t\tif (\n\t\t\t\tthis.config.ignoreMethods.map((m) => m.toUpperCase()).includes(method)\n\t\t\t) {\n\t\t\t\t// Safe method: ensure a cookie is present.\n\t\t\t\tconst cookieHeader = c.req.header(\"cookie\") ?? \"\";\n\t\t\t\tif (!this.extractCookie(cookieHeader, this.config.cookieName)) {\n\t\t\t\t\tthis.issue(c.res.headers);\n\t\t\t\t}\n\t\t\t\treturn next();\n\t\t\t}\n\t\t\tif (!this.verify(c.req.raw)) {\n\t\t\t\treturn c.text(\"Invalid CSRF token\", 403);\n\t\t\t}\n\t\t\treturn next();\n\t\t};\n\t}\n\n\tprivate extractCookie(cookieHeader: string, name: string): string | null {\n\t\tfor (const part of cookieHeader.split(\";\")) {\n\t\t\tconst [k, ...rest] = part.trim().split(\"=\");\n\t\t\tif (k === name) return rest.join(\"=\");\n\t\t}\n\t\treturn null;\n\t}\n}\n",
|
|
7
7
|
"/**\n * Security headers middleware. Sets HSTS, X-Frame-Options,\n * X-Content-Type-Options, Referrer-Policy, and CSP on every response.\n */\nimport type { CspConfig, HstsConfig } from \"../types.js\";\n\nexport class HeadersGuard {\n\thsts: HstsConfig | false;\n\tcsp: CspConfig | false;\n\txFrameOptions: \"DENY\" | \"SAMEORIGIN\" | false;\n\txContentTypeOptions: boolean;\n\treferrerPolicy: string | undefined;\n\n\tconstructor(\n\t\thsts: HstsConfig | false,\n\t\tcsp: CspConfig | false,\n\t\txFrameOptions: \"DENY\" | \"SAMEORIGIN\" | false,\n\t\txContentTypeOptions: boolean,\n\t\treferrerPolicy: string | undefined,\n\t) {\n\t\tthis.hsts = hsts;\n\t\tthis.csp = csp;\n\t\tthis.xFrameOptions = xFrameOptions;\n\t\tthis.xContentTypeOptions = xContentTypeOptions;\n\t\tthis.referrerPolicy = referrerPolicy;\n\t}\n\n\t/**\n\t * Apply configured headers to the given `Headers` instance in place.\n\t * Useful when you already have a Response and want to enrich it.\n\t */\n\tapply(headers: Headers): void {\n\t\tif (this.hsts) {\n\t\t\tconst h = this.buildHstsHeader(this.hsts);\n\t\t\tif (h) headers.set(\"Strict-Transport-Security\", h);\n\t\t}\n\t\tif (this.csp) {\n\t\t\tconst header = this.buildCspHeader(this.csp);\n\t\t\tconst name = this.csp.reportOnly\n\t\t\t\t? \"Content-Security-Policy-Report-Only\"\n\t\t\t\t: \"Content-Security-Policy\";\n\t\t\theaders.set(name, header);\n\t\t}\n\t\tif (this.xFrameOptions) {\n\t\t\theaders.set(\"X-Frame-Options\", this.xFrameOptions);\n\t\t}\n\t\tif (this.xContentTypeOptions) {\n\t\t\theaders.set(\"X-Content-Type-Options\", \"nosniff\");\n\t\t}\n\t\tif (this.referrerPolicy) {\n\t\t\theaders.set(\"Referrer-Policy\", this.referrerPolicy);\n\t\t}\n\t}\n\n\tmiddleware() {\n\t\treturn async (_c: any, next: () => Promise<any>) => {\n\t\t\t// Apply headers to c.res BEFORE next() so the handler inherits them.\n\t\t\tthis.apply(_c.res.headers as Headers);\n\t\t\treturn next();\n\t\t};\n\t}\n\n\tprivate buildHstsHeader(cfg: HstsConfig): string {\n\t\tlet v = `max-age=${cfg.maxAge}`;\n\t\tif (cfg.includeSubDomains) v += \"; includeSubDomains\";\n\t\tif (cfg.preload) v += \"; preload\";\n\t\treturn v;\n\t}\n\n\tprivate buildCspHeader(cfg: CspConfig): string {\n\t\tconst parts: string[] = [];\n\t\tfor (const [name, values] of Object.entries(cfg.directives)) {\n\t\t\tif (!values || values.length === 0) continue;\n\t\t\tparts.push(`${camelToKebab(name)} ${values.join(\" \")}`);\n\t\t}\n\t\tif (cfg.reportUri) parts.push(`report-uri ${cfg.reportUri}`);\n\t\treturn parts.join(\"; \");\n\t}\n}\n\n/** Convert `defaultSrc` → `default-src`. Already-kebab names pass through. */\nfunction camelToKebab(s: string): string {\n\treturn s.replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`);\n}\n",
|
|
8
|
-
"/**\n * `ShieldService` — orchestrator. Aggregates the per-feature guards\n * into a single Hono middleware that can be mounted globally.\n */\nimport { Inject, Injectable } from \"@nexusts/core
|
|
9
|
-
"/**\n * `ShieldModule` — drop-in security middleware suite.\n *\n * @Module({\n * imports: [\n * ShieldModule.forRoot({\n * csrf: { enabled: true },\n * hsts: { maxAge: 31_536_000, includeSubDomains: true },\n * csp: { directives: { defaultSrc: [\"'self'\"] } },\n * xFrameOptions: 'SAMEORIGIN',\n * xContentTypeOptions: true,\n * referrerPolicy: 'strict-origin-when-cross-origin',\n * }),\n * ],\n * })\n * export class AppModule {}\n */\nimport \"reflect-metadata\";\nimport { Module } from \"@nexusts/core
|
|
8
|
+
"/**\n * `ShieldService` — orchestrator. Aggregates the per-feature guards\n * into a single Hono middleware that can be mounted globally.\n */\nimport { Inject, Injectable } from \"@nexusts/core\";\nimport type { CsrfConfig, ShieldConfig } from \"./types.js\";\nimport { CsrfGuard, HeadersGuard } from \"./guards/index.js\";\n\n@Injectable()\nexport class ShieldService {\n\t/** DI token. */\n\tstatic readonly TOKEN = Symbol.for(\"nexus:ShieldService\");\n\n\tcsrf?: CsrfGuard;\n\theaders: HeadersGuard;\n\n\tconstructor(@Inject(\"SHIELD_CONFIG\") config: ShieldConfig = {}) {\n\t\tif (config.csrf) {\n\t\t\tconst secret =\n\t\t\t\tconfig.secret ??\n\t\t\t\tprocess.env[\"NEXUS_SHIELD_SECRET\"] ??\n\t\t\t\t\"change-me-in-production-please\";\n\t\t\tthis.csrf = new CsrfGuard(config.csrf as CsrfConfig, secret);\n\t\t}\n\t\tthis.headers = new HeadersGuard(\n\t\t\tconfig.hsts ?? false,\n\t\t\tconfig.csp ?? false,\n\t\t\tconfig.xFrameOptions ?? \"SAMEORIGIN\",\n\t\t\tconfig.xContentTypeOptions ?? true,\n\t\t\tconfig.referrerPolicy,\n\t\t);\n\t}\n\n\t/**\n\t * Returns a Hono middleware that applies all configured guards.\n\t *\n\t * Order:\n\t * 1. CSRF check on mutating requests (rejects with 403 + security headers)\n\t * 2. Security headers applied to the final response\n\t */\n\tmiddleware() {\n\t\treturn async (c: any, next: () => Promise<any>) => {\n\t\t\t// 1. CSRF check — must run before `next()` so we can short-circuit.\n\t\t\tif (this.csrf) {\n\t\t\t\tconst method = (c.req.method as string).toUpperCase();\n\t\t\t\tconst ignoreMethods = (this.csrf as any).config.ignoreMethods as string[];\n\t\t\t\tif (ignoreMethods.map((m) => m.toUpperCase()).includes(method)) {\n\t\t\t\t\t// Safe method: ensure a CSRF cookie is present.\n\t\t\t\t\tconst cookieHeader = c.req.header(\"cookie\") ?? \"\";\n\t\t\t\t\tconst cookieName = (this.csrf as any).config.cookieName as string;\n\t\t\t\t\tif (!this.extractCookie(cookieHeader, cookieName)) {\n\t\t\t\t\t\t(this.csrf as any).issue(c.res.headers);\n\t\t\t\t\t}\n\t\t\t\t} else if (!(this.csrf as any).verify(c.req.raw)) {\n\t\t\t\t\t// 403 — apply security headers and return.\n\t\t\t\t\tconst resp = c.text(\"Invalid CSRF token\", 403);\n\t\t\t\t\tthis.headers.apply(resp.headers as Headers);\n\t\t\t\t\treturn resp;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// 2. Apply security headers to c.res BEFORE the handler runs.\n\t\t\t// Hono's c.text()/c.json() etc. create a new Response but\n\t\t\t// inherit existing headers from c.res.headers.\n\t\t\tthis.headers.apply(c.res.headers as Headers);\n\n\t\t\t// 3. Continue to next middleware/handler.\n\t\t\treturn next();\n\t\t};\n\t}\n\n\t/** Generate a CSRF token and set the cookie. Useful for forms. */\n\tissueToken(headers: Headers) {\n\t\tif (!this.csrf) throw new Error(\"CSRF guard is not enabled\");\n\t\treturn this.csrf.issue(headers);\n\t}\n\n\tprivate extractCookie(cookieHeader: string, name: string): string | null {\n\t\tfor (const part of cookieHeader.split(\";\")) {\n\t\t\tconst [k, ...rest] = part.trim().split(\"=\");\n\t\t\tif (k === name) return rest.join(\"=\");\n\t\t}\n\t\treturn null;\n\t}\n}\n",
|
|
9
|
+
"/**\n * `ShieldModule` — drop-in security middleware suite.\n *\n * @Module({\n * imports: [\n * ShieldModule.forRoot({\n * csrf: { enabled: true },\n * hsts: { maxAge: 31_536_000, includeSubDomains: true },\n * csp: { directives: { defaultSrc: [\"'self'\"] } },\n * xFrameOptions: 'SAMEORIGIN',\n * xContentTypeOptions: true,\n * referrerPolicy: 'strict-origin-when-cross-origin',\n * }),\n * ],\n * })\n * export class AppModule {}\n */\nimport \"reflect-metadata\";\nimport { Module } from \"@nexusts/core\";\nimport { ShieldService } from \"./shield.service.js\";\nimport type { ShieldConfig } from \"./types.js\";\n\n@Module({\n\tproviders: [\n\t\tShieldService,\n\t\t{ provide: ShieldService.TOKEN, useExisting: ShieldService },\n\t],\n\texports: [ShieldService, ShieldService.TOKEN],\n})\nexport class ShieldModule {\n\tstatic forRoot(config: ShieldConfig = {}) {\n\t\t@Module({\n\t\t\tproviders: [\n\t\t\t\tShieldService,\n\t\t\t\t{ provide: ShieldService.TOKEN, useExisting: ShieldService },\n\t\t\t\t{ provide: \"SHIELD_CONFIG\", useValue: config },\n\t\t\t],\n\t\t\texports: [ShieldService, ShieldService.TOKEN],\n\t\t})\n\t\tclass ConfiguredShieldModule {}\n\t\tObject.defineProperty(ConfiguredShieldModule, \"name\", {\n\t\t\tvalue: \"ConfiguredShieldModule\",\n\t\t});\n\t\treturn ConfiguredShieldModule;\n\t}\n}\n"
|
|
10
10
|
],
|
|
11
11
|
"mappings": ";;;;;;;;;;;;;;;;;;AAsBA;AACA;AACA;AA2DA,SAAS,WAAW,CAAC,QAAQ,IAAY;AAAA,EACxC,OAAO,YAAY,KAAK,EAAE,SAAS,WAAW;AAAA;AAU/C,SAAS,IAAI,CAAC,OAAe,QAAwB;AAAA,EACpD,MAAM,MAAM,IAAI,kBAAkB,MAAM,EAAE,QAAQ,OAAO,MAAM;AAAA,EAC/D,OAAO,GAAG,SAAS;AAAA;AAOpB,SAAS,MAAM,CAAC,QAAgB,QAA+B;AAAA,EAC9D,MAAM,UAAU,OAAO,YAAY,GAAG;AAAA,EACtC,IAAI,UAAU;AAAA,IAAG,OAAO;AAAA,EACxB,MAAM,QAAQ,OAAO,MAAM,GAAG,OAAO;AAAA,EACrC,MAAM,MAAM,OAAO,MAAM,UAAU,CAAC;AAAA,EACpC,IAAI,CAAC,IAAI,kBAAkB,MAAM,EAAE,UAAU,OAAO,KAAK,MAAM;AAAA,IAAG,OAAO;AAAA,EACzE,OAAO;AAAA;AAGD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AAC;AAAA,IAAxB,yBAAN;AAAA,MARC,OAAO;AAAA,QACP,WAAW;AAAA,UACV;AAAA,UACA,EAAE,SAAS,cAAc,OAAO,aAAa,cAAc;AAAA,UAC3D,EAAE,SAAS,iBAAiB,UAAU,OAAO;AAAA,QAC9C;AAAA,QACA,SAAS,CAAC,eAAe,cAAc,KAAK;AAAA,MAC7C,CAAC;AAAA,OACK;AAAA,IACN,OAAO,eAAe,wBAAwB,QAAQ;AAAA,MACrD,OAAO;AAAA,IACR,CAAC;AAAA,IACD,OAAO;AAAA;AAET;AAhBa,eAAN;AAAA,EAPN,OAAO;AAAA,IACP,WAAW;AAAA,MACV;AAAA,MACA,EAAE,SAAS,cAAc,OAAO,aAAa,cAAc;AAAA,IAC5D;AAAA,IACA,SAAS,CAAC,eAAe,cAAc,KAAK;AAAA,EAC7C,CAAC;AAAA,GACY;",
|
|
12
|
-
"debugId": "
|
|
12
|
+
"debugId": "78F89FE2F2B0E78F64756E2164756E21",
|
|
13
13
|
"names": []
|
|
14
14
|
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `ShieldModule` — drop-in security middleware suite.
|
|
3
|
+
*
|
|
4
|
+
* @Module({
|
|
5
|
+
* imports: [
|
|
6
|
+
* ShieldModule.forRoot({
|
|
7
|
+
* csrf: { enabled: true },
|
|
8
|
+
* hsts: { maxAge: 31_536_000, includeSubDomains: true },
|
|
9
|
+
* csp: { directives: { defaultSrc: ["'self'"] } },
|
|
10
|
+
* xFrameOptions: 'SAMEORIGIN',
|
|
11
|
+
* xContentTypeOptions: true,
|
|
12
|
+
* referrerPolicy: 'strict-origin-when-cross-origin',
|
|
13
|
+
* }),
|
|
14
|
+
* ],
|
|
15
|
+
* })
|
|
16
|
+
* export class AppModule {}
|
|
17
|
+
*/
|
|
18
|
+
import "reflect-metadata";
|
|
19
|
+
import type { ShieldConfig } from "./types.js";
|
|
20
|
+
export declare class ShieldModule {
|
|
21
|
+
static forRoot(config?: ShieldConfig): {
|
|
22
|
+
new (): {};
|
|
23
|
+
};
|
|
24
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { ShieldConfig } from "./types.js";
|
|
2
|
+
import { CsrfGuard, HeadersGuard } from "./guards/index.js";
|
|
3
|
+
export declare class ShieldService {
|
|
4
|
+
/** DI token. */
|
|
5
|
+
static readonly TOKEN: unique symbol;
|
|
6
|
+
csrf?: CsrfGuard;
|
|
7
|
+
headers: HeadersGuard;
|
|
8
|
+
constructor(config?: ShieldConfig);
|
|
9
|
+
/**
|
|
10
|
+
* Returns a Hono middleware that applies all configured guards.
|
|
11
|
+
*
|
|
12
|
+
* Order:
|
|
13
|
+
* 1. CSRF check on mutating requests (rejects with 403 + security headers)
|
|
14
|
+
* 2. Security headers applied to the final response
|
|
15
|
+
*/
|
|
16
|
+
middleware(): (c: any, next: () => Promise<any>) => Promise<any>;
|
|
17
|
+
/** Generate a CSRF token and set the cookie. Useful for forms. */
|
|
18
|
+
issueToken(headers: Headers): import("./types.js").CsrfToken;
|
|
19
|
+
private extractCookie;
|
|
20
|
+
}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `nexusjs/shield` — security middleware suite.
|
|
3
|
+
*
|
|
4
|
+
* Inspired by AdonisJS Shield. Provides:
|
|
5
|
+
* - CSRF protection (synchronizer token pattern)
|
|
6
|
+
* - Security headers (X-Frame-Options, X-Content-Type-Options, Referrer-Policy)
|
|
7
|
+
* - HSTS (Strict-Transport-Security)
|
|
8
|
+
* - CSP (Content-Security-Policy) — optional
|
|
9
|
+
* - XSS filter (browser-level, for legacy browsers)
|
|
10
|
+
*
|
|
11
|
+
* @Module({
|
|
12
|
+
* imports: [
|
|
13
|
+
* ShieldModule.forRoot({
|
|
14
|
+
* csrf: { enabled: true },
|
|
15
|
+
* hsts: { maxAge: 31_536_000, includeSubDomains: true },
|
|
16
|
+
* csp: { directives: { defaultSrc: ["'self'"] } },
|
|
17
|
+
* }),
|
|
18
|
+
* ],
|
|
19
|
+
* })
|
|
20
|
+
* export class AppModule {}
|
|
21
|
+
*/
|
|
22
|
+
import "reflect-metadata";
|
|
23
|
+
/** CSRF protection configuration. */
|
|
24
|
+
export interface CsrfConfig {
|
|
25
|
+
enabled: boolean;
|
|
26
|
+
/** Cookie name. Default: 'nexus-csrf'. */
|
|
27
|
+
cookieName?: string;
|
|
28
|
+
/** Header name expected from clients. Default: 'x-csrf-token'. */
|
|
29
|
+
headerName?: string;
|
|
30
|
+
/** Form field name. Default: '_csrf'. */
|
|
31
|
+
fieldName?: string;
|
|
32
|
+
/** Whether to require the token on GET. Default: false. */
|
|
33
|
+
protectGet?: boolean;
|
|
34
|
+
/** Cookie attributes. */
|
|
35
|
+
cookie?: {
|
|
36
|
+
sameSite?: "Strict" | "Lax" | "None";
|
|
37
|
+
secure?: boolean;
|
|
38
|
+
httpOnly?: boolean;
|
|
39
|
+
path?: string;
|
|
40
|
+
};
|
|
41
|
+
/** Methods that bypass CSRF check. Default: ['GET', 'HEAD', 'OPTIONS']. */
|
|
42
|
+
ignoreMethods?: string[];
|
|
43
|
+
}
|
|
44
|
+
/** HSTS configuration. */
|
|
45
|
+
export interface HstsConfig {
|
|
46
|
+
maxAge: number;
|
|
47
|
+
includeSubDomains?: boolean;
|
|
48
|
+
preload?: boolean;
|
|
49
|
+
}
|
|
50
|
+
/** CSP configuration. */
|
|
51
|
+
export interface CspConfig {
|
|
52
|
+
directives: Record<string, string[]>;
|
|
53
|
+
reportOnly?: boolean;
|
|
54
|
+
reportUri?: string;
|
|
55
|
+
}
|
|
56
|
+
/** Top-level Shield config. */
|
|
57
|
+
export interface ShieldConfig {
|
|
58
|
+
csrf?: CsrfConfig | false;
|
|
59
|
+
hsts?: HstsConfig | false;
|
|
60
|
+
csp?: CspConfig | false;
|
|
61
|
+
xFrameOptions?: "DENY" | "SAMEORIGIN" | false;
|
|
62
|
+
xContentTypeOptions?: boolean;
|
|
63
|
+
referrerPolicy?: string;
|
|
64
|
+
/** Secret used to sign CSRF tokens. */
|
|
65
|
+
secret?: string;
|
|
66
|
+
}
|
|
67
|
+
/** CSRF token (synchronizer pattern). */
|
|
68
|
+
export interface CsrfToken {
|
|
69
|
+
/** The token to embed in forms/headers. */
|
|
70
|
+
token: string;
|
|
71
|
+
/** A pre-formed <meta> tag. */
|
|
72
|
+
html: string;
|
|
73
|
+
}
|
|
74
|
+
/** Generate a random base64url string. */
|
|
75
|
+
declare function randomToken(bytes?: number): string;
|
|
76
|
+
/**
|
|
77
|
+
* Sign `value` with `secret` using EncryptionService.
|
|
78
|
+
*
|
|
79
|
+
* Returns the signed value in `<value>.<signature>` format. The
|
|
80
|
+
* HMAC is HKDF-derived from the secret + purpose tag ("csrf"), so
|
|
81
|
+
* a CSRF token can't be replayed as another-purpose token.
|
|
82
|
+
*/
|
|
83
|
+
declare function sign(value: string, secret: string): string;
|
|
84
|
+
/**
|
|
85
|
+
* Verify a signed token. Returns the original value on success,
|
|
86
|
+
* `null` on failure (tampered, wrong purpose, malformed).
|
|
87
|
+
*/
|
|
88
|
+
declare function verify(signed: string, secret: string): string | null;
|
|
89
|
+
export declare const ShieldInternals: {
|
|
90
|
+
sign: typeof sign;
|
|
91
|
+
verify: typeof verify;
|
|
92
|
+
randomToken: typeof randomToken;
|
|
93
|
+
};
|
|
94
|
+
export {};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nexusts/shield",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.1",
|
|
4
4
|
"description": "CSRF / HSTS / CSP security middleware",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -12,20 +12,15 @@
|
|
|
12
12
|
"import": "./dist/index.js"
|
|
13
13
|
}
|
|
14
14
|
},
|
|
15
|
-
"files": [
|
|
16
|
-
"dist",
|
|
17
|
-
"README.md"
|
|
18
|
-
],
|
|
15
|
+
"files": ["dist", "README.md"],
|
|
19
16
|
"scripts": {
|
|
20
17
|
"build": "bun run ../../build.ts"
|
|
21
18
|
},
|
|
22
|
-
"keywords": [
|
|
23
|
-
"nexusts",
|
|
24
|
-
"framework",
|
|
25
|
-
"bun"
|
|
26
|
-
],
|
|
19
|
+
"keywords": ["nexusts", "framework", "bun"],
|
|
27
20
|
"license": "MIT",
|
|
21
|
+
|
|
22
|
+
|
|
28
23
|
"dependencies": {
|
|
29
|
-
"@nexusts/core": "
|
|
24
|
+
"@nexusts/core": "file:../core"
|
|
30
25
|
}
|
|
31
26
|
}
|