@nexusts/shield 0.9.0 → 0.9.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/dist/index.d.ts +1 -1
- package/dist/index.js.map +1 -1
- package/dist/types.d.ts +1 -1
- package/package.json +2 -2
package/dist/index.d.ts
CHANGED
package/dist/index.js.map
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/types.ts", "../src/guards/csrf.ts", "../src/guards/headers.ts", "../src/guards/cors.ts", "../src/shield.service.ts", "../src/shield.module.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
|
-
"/**\n *
|
|
5
|
+
"/**\n * `@nexusts/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 { randomBytes } from \"node:crypto\";\nimport { EncryptionService } from \"@nexusts/crypto\";\nimport { safeGetMeta, safeDefineMeta, safeHasMeta } from \"@nexusts/core/di/safe-reflect\";\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/** CORS configuration. */\nexport interface CorsConfig {\n\t/**\n\t * Allowed origin(s). Default: `\"*\"` (all origins).\n\t * - `\"*\"` — reflect wildcard (credentials not supported)\n\t * - `string` — exact match\n\t * - `string[]` — whitelist\n\t * - `(origin) => boolean | string | null` — custom resolver\n\t */\n\torigin?: string | string[] | ((origin: string) => boolean | string | null);\n\t/** Allowed HTTP methods. Default: GET POST PUT PATCH DELETE HEAD OPTIONS. */\n\tmethods?: string[];\n\t/** Allowed request headers (`Access-Control-Allow-Headers`). */\n\tallowedHeaders?: string[];\n\t/** Headers exposed to the browser (`Access-Control-Expose-Headers`). */\n\texposedHeaders?: string[];\n\t/** Set `Access-Control-Allow-Credentials: true`. Default: false. */\n\tcredentials?: boolean;\n\t/** Preflight cache duration in seconds (`Access-Control-Max-Age`). */\n\tmaxAge?: number;\n}\n\n/** Top-level Shield config. */\nexport interface ShieldConfig {\n\tcors?: CorsConfig | false;\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
8
|
"/**\n * CORS guard — handles preflight and sets Access-Control-* headers\n * on every response according to the configured policy.\n */\nimport type { CorsConfig } from \"../types.js\";\n\nexport class CorsGuard {\n\tconstructor(private config: CorsConfig) {}\n\n\t/**\n\t * Resolve the `Access-Control-Allow-Origin` value for a given\n\t * request origin. Returns `null` when the origin is not allowed.\n\t */\n\tresolveOrigin(requestOrigin: string): string | null {\n\t\tconst { origin = \"*\" } = this.config;\n\t\tif (origin === \"*\") return \"*\";\n\t\tif (typeof origin === \"string\")\n\t\t\treturn requestOrigin === origin ? origin : null;\n\t\tif (Array.isArray(origin))\n\t\t\treturn origin.includes(requestOrigin) ? requestOrigin : null;\n\t\tif (typeof origin === \"function\") {\n\t\t\tconst result = origin(requestOrigin);\n\t\t\tif (result === true) return requestOrigin;\n\t\t\tif (typeof result === \"string\") return result;\n\t\t\treturn null;\n\t\t}\n\t\treturn null;\n\t}\n\n\t/** Apply CORS response headers (non-preflight). */\n\tapplyHeaders(headers: Headers, requestOrigin: string): void {\n\t\tconst resolved = this.resolveOrigin(requestOrigin);\n\t\tif (!resolved) return;\n\t\theaders.set(\"Access-Control-Allow-Origin\", resolved);\n\t\tif (this.config.credentials) {\n\t\t\theaders.set(\"Access-Control-Allow-Credentials\", \"true\");\n\t\t}\n\t\tif (this.config.exposedHeaders?.length) {\n\t\t\theaders.set(\n\t\t\t\t\"Access-Control-Expose-Headers\",\n\t\t\t\tthis.config.exposedHeaders.join(\", \"),\n\t\t\t);\n\t\t}\n\t\tif (resolved !== \"*\") {\n\t\t\t// Vary so caches don't conflate responses for different origins.\n\t\t\theaders.append(\"Vary\", \"Origin\");\n\t\t}\n\t}\n\n\t/** Apply preflight response headers. Returns false if origin is not allowed. */\n\tapplyPreflightHeaders(headers: Headers, requestOrigin: string): boolean {\n\t\tconst resolved = this.resolveOrigin(requestOrigin);\n\t\tif (!resolved) return false;\n\t\theaders.set(\"Access-Control-Allow-Origin\", resolved);\n\t\tconst methods = (\n\t\t\tthis.config.methods ?? [\"GET\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\", \"HEAD\", \"OPTIONS\"]\n\t\t).join(\", \");\n\t\theaders.set(\"Access-Control-Allow-Methods\", methods);\n\t\tif (this.config.allowedHeaders?.length) {\n\t\t\theaders.set(\n\t\t\t\t\"Access-Control-Allow-Headers\",\n\t\t\t\tthis.config.allowedHeaders.join(\", \"),\n\t\t\t);\n\t\t}\n\t\tif (this.config.credentials) {\n\t\t\theaders.set(\"Access-Control-Allow-Credentials\", \"true\");\n\t\t}\n\t\tif (this.config.maxAge !== undefined) {\n\t\t\theaders.set(\"Access-Control-Max-Age\", String(this.config.maxAge));\n\t\t}\n\t\tif (resolved !== \"*\") {\n\t\t\theaders.append(\"Vary\", \"Origin\");\n\t\t}\n\t\treturn true;\n\t}\n\n\t/** Hono middleware — handles preflight (OPTIONS) and annotates responses. */\n\tmiddleware() {\n\t\treturn async (c: any, next: () => Promise<any>) => {\n\t\t\tconst requestOrigin = (c.req.header(\"origin\") as string) ?? \"\";\n\t\t\tconst method = (c.req.method as string).toUpperCase();\n\n\t\t\t// Preflight: OPTIONS + Access-Control-Request-Method\n\t\t\tif (method === \"OPTIONS\" && c.req.header(\"access-control-request-method\")) {\n\t\t\t\tconst headers = new Headers();\n\t\t\t\tconst allowed = this.applyPreflightHeaders(headers, requestOrigin);\n\t\t\t\treturn new Response(null, { status: allowed ? 204 : 403, headers });\n\t\t\t}\n\n\t\t\t// Regular request: apply CORS headers before the handler.\n\t\t\tthis.applyHeaders(c.res.headers as Headers, requestOrigin);\n\t\t\treturn next();\n\t\t};\n\t}\n}\n",
|
package/dist/types.d.ts
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nexusts/shield",
|
|
3
|
-
"version": "0.9.
|
|
3
|
+
"version": "0.9.1",
|
|
4
4
|
"description": "CSRF / HSTS / CSP security middleware",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -26,7 +26,7 @@
|
|
|
26
26
|
],
|
|
27
27
|
"license": "MIT",
|
|
28
28
|
"dependencies": {
|
|
29
|
-
"@nexusts/core": "^0.9.
|
|
29
|
+
"@nexusts/core": "^0.9.1"
|
|
30
30
|
},
|
|
31
31
|
"repository": {
|
|
32
32
|
"type": "git",
|