From 881bc59419ab44f847cc273f7f730f4921b5114b Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Mon, 6 Jul 2026 18:52:24 -0500 Subject: [PATCH] feat(security): pure CORS + security-header computation module Signed-off-by: Diego Resendez --- src/security.ts | 93 +++++++++++++++++++++++++++++++++++++++++++ test/security.test.ts | 62 +++++++++++++++++++++++++++++ 2 files changed, 155 insertions(+) create mode 100644 src/security.ts create mode 100644 test/security.test.ts diff --git a/src/security.ts b/src/security.ts new file mode 100644 index 0000000..988f627 --- /dev/null +++ b/src/security.ts @@ -0,0 +1,93 @@ +// src/security.ts — pure header computation, no server deps +export interface TlsOptions { key: Buffer | string; cert: Buffer | string; ca?: Buffer | string; passphrase?: string } + +export interface CorsOptions { + origins: string | string[] | '*' | ((origin: string) => boolean); + methods?: string[]; + allowedHeaders?: string[]; + exposedHeaders?: string[]; + credentials?: boolean; + maxAge?: number; +} + +export interface SecurityOptions { + hsts?: boolean | { maxAge?: number; includeSubDomains?: boolean; preload?: boolean }; + frameOptions?: 'SAMEORIGIN' | 'DENY' | false; + referrerPolicy?: string | false; + noSniff?: boolean; + dnsPrefetchControl?: boolean; + csp?: string; +} + +type Headers = Record; +const HSTS_DEFAULT_MAXAGE = 15552000; // 180 days + +// scheme "://" host [":" port], or literal "null". Rejects control chars/whitespace. +const ORIGIN_RE = /^(?:null|[a-z][a-z0-9+.-]*:\/\/[^\s/?#]+)$/i; +export function isValidOrigin(o: string): boolean { return ORIGIN_RE.test(o); } + +export function mergeVary(existing: string | undefined, add: string): string { + const parts = (existing ? existing.split(',').map((s) => s.trim()).filter(Boolean) : []); + if (!parts.some((p) => p.toLowerCase() === add.toLowerCase())) parts.push(add); + return parts.join(', '); +} + +export function buildSecurityHeaders(opts: boolean | SecurityOptions, secure: boolean): Headers { + if (opts === false) return {}; + const o: SecurityOptions = opts === true ? {} : opts; + const h: Headers = {}; + if (o.noSniff !== false) h['x-content-type-options'] = 'nosniff'; + if (o.frameOptions !== false) h['x-frame-options'] = o.frameOptions ?? 'SAMEORIGIN'; + if (o.referrerPolicy !== false) h['referrer-policy'] = o.referrerPolicy ?? 'no-referrer'; + if (o.dnsPrefetchControl !== false) h['x-dns-prefetch-control'] = 'off'; + if (o.csp) h['content-security-policy'] = o.csp; + if (secure && o.hsts !== false) { + const hs = o.hsts && o.hsts !== true ? o.hsts : {}; + let v = `max-age=${hs.maxAge ?? HSTS_DEFAULT_MAXAGE}`; + if (hs.includeSubDomains) v += '; includeSubDomains'; + if (hs.preload) v += '; preload'; + h['strict-transport-security'] = v; + } + return h; +} + +function originAllowed(spec: CorsOptions['origins'], origin: string): boolean { + if (spec === '*') return true; + if (typeof spec === 'function') return spec(origin); + if (Array.isArray(spec)) return spec.includes(origin); + return spec === origin; +} + +// req: minimal shape { headers: { origin? } } +export function resolveCors(opts: CorsOptions, req: { headers: Record }): Headers { + const h: Headers = {}; + const raw = req.headers['origin']; + const origin = Array.isArray(raw) ? raw[0] : raw; + if (!origin || !isValidOrigin(origin) || !originAllowed(opts.origins, origin)) return h; + + // credentials => never '*'; echo concrete origin. Also echo when allowlist is dynamic. + if (opts.credentials) { + h['access-control-allow-origin'] = origin; + h['access-control-allow-credentials'] = 'true'; + h['vary'] = mergeVary(h['vary'], 'Origin'); + } else if (opts.origins === '*') { + h['access-control-allow-origin'] = '*'; + } else { + h['access-control-allow-origin'] = origin; + h['vary'] = mergeVary(h['vary'], 'Origin'); + } + if (opts.exposedHeaders?.length) h['access-control-expose-headers'] = opts.exposedHeaders.join(', '); + return h; +} + +// Preflight-specific headers (methods/allowed-headers/max-age). Call only for OPTIONS+ACRM. +export function corsPreflightHeaders(opts: CorsOptions, req: { headers: Record }): Headers { + const h = resolveCors(opts, req); + if (!h['access-control-allow-origin']) return h; // origin not allowed → bare 204 + h['access-control-allow-methods'] = (opts.methods ?? ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS']).join(', '); + const reqHdrs = req.headers['access-control-request-headers']; + h['access-control-allow-headers'] = opts.allowedHeaders?.join(', ') + ?? (Array.isArray(reqHdrs) ? reqHdrs.join(', ') : reqHdrs ?? '*'); + if (opts.maxAge != null) h['access-control-max-age'] = String(opts.maxAge); + return h; +} diff --git a/test/security.test.ts b/test/security.test.ts new file mode 100644 index 0000000..9ad2ad4 --- /dev/null +++ b/test/security.test.ts @@ -0,0 +1,62 @@ +import { describe, it, expect } from 'vitest'; +import { buildSecurityHeaders, resolveCors, mergeVary } from '../src/security'; + +describe('buildSecurityHeaders', () => { + it('default set (security:true), no HSTS over insecure', () => { + const h = buildSecurityHeaders(true, false); + expect(h['x-content-type-options']).toBe('nosniff'); + expect(h['x-frame-options']).toBe('SAMEORIGIN'); + expect(h['referrer-policy']).toBe('no-referrer'); + expect(h['x-dns-prefetch-control']).toBe('off'); + expect(h['strict-transport-security']).toBeUndefined(); + }); + it('HSTS only when secure', () => { + const h = buildSecurityHeaders(true, true); + expect(h['strict-transport-security']).toBe('max-age=15552000'); + }); + it('security:false → empty', () => { + expect(buildSecurityHeaders(false, true)).toEqual({}); + }); + it('object overrides: disable frameOptions, custom referrer, csp, hsts opts', () => { + const h = buildSecurityHeaders({ frameOptions: false, referrerPolicy: 'strict-origin', + csp: "default-src 'self'", hsts: { maxAge: 100, includeSubDomains: true } }, true); + expect(h['x-frame-options']).toBeUndefined(); + expect(h['referrer-policy']).toBe('strict-origin'); + expect(h['content-security-policy']).toBe("default-src 'self'"); + expect(h['strict-transport-security']).toBe('max-age=100; includeSubDomains'); + }); +}); + +describe('resolveCors', () => { + const req = (origin?: string) => ({ headers: origin ? { origin } : {} }); + it('exact-string allowlist echoes origin + Vary', () => { + const r = resolveCors({ origins: 'https://a.com' }, req('https://a.com') as any); + expect(r['access-control-allow-origin']).toBe('https://a.com'); + expect(r['vary']).toBe('Origin'); + }); + it('disallowed origin → no allow-origin header', () => { + const r = resolveCors({ origins: 'https://a.com' }, req('https://evil.com') as any); + expect(r['access-control-allow-origin']).toBeUndefined(); + }); + it("'*' without credentials returns *", () => { + const r = resolveCors({ origins: '*' }, req('https://a.com') as any); + expect(r['access-control-allow-origin']).toBe('*'); + }); + it('credentials:true never returns * — echoes concrete origin', () => { + const r = resolveCors({ origins: '*', credentials: true }, req('https://a.com') as any); + expect(r['access-control-allow-origin']).toBe('https://a.com'); + expect(r['access-control-allow-credentials']).toBe('true'); + }); + it('rejects malformed Origin (control char) even if predicate allows', () => { + const r = resolveCors({ origins: () => true }, req('https://a.com\r\nX: y') as any); + expect(r['access-control-allow-origin']).toBeUndefined(); + }); +}); + +describe('mergeVary', () => { + it('appends, dedupes, handles empty', () => { + expect(mergeVary(undefined, 'Origin')).toBe('Origin'); + expect(mergeVary('Accept-Encoding', 'Origin')).toBe('Accept-Encoding, Origin'); + expect(mergeVary('Origin', 'Origin')).toBe('Origin'); + }); +});