@noony-serverless/core
Version:
A Middy base framework compatible with Firebase and GCP Cloud Functions with TypeScript
157 lines • 4.82 kB
TypeScript
import { BaseMiddleware, Context, NoonyRequest } from '../core';
/**
* Configuration for authentication functionality
*/
export interface AuthenticationConfig<T = unknown> {
tokenVerifier?: {
verifyToken(token: string): Promise<T>;
};
extractToken?: (req: NoonyRequest) => string | null;
onAuthFailure?: (error: Error, context: Context) => Promise<void>;
skipPaths?: string[];
optional?: boolean;
}
/**
* Configuration for security headers
*/
export interface SecurityHeadersConfig {
contentSecurityPolicy?: string;
xFrameOptions?: 'DENY' | 'SAMEORIGIN' | string;
strictTransportSecurity?: string;
xContentTypeOptions?: 'nosniff';
xXssProtection?: '1; mode=block' | '0' | '1';
referrerPolicy?: string;
permissionsPolicy?: string;
customHeaders?: Record<string, string>;
}
/**
* Configuration for security audit functionality
*/
export interface SecurityAuditConfig {
logFailedAuth?: boolean;
trackSuspiciousIPs?: boolean;
alertThresholds?: {
failedAttempts?: number;
timeWindowMs?: number;
};
enableMetrics?: boolean;
logSuccessfulAuth?: boolean;
customAuditor?: (event: SecurityAuditEvent, context: Context) => Promise<void>;
}
/**
* Security audit event types
*/
export interface SecurityAuditEvent {
type: 'AUTH_SUCCESS' | 'AUTH_FAILURE' | 'SUSPICIOUS_IP' | 'THRESHOLD_EXCEEDED';
ip?: string;
userAgent?: string;
path?: string;
timestamp: Date;
details?: Record<string, unknown>;
}
/**
* Complete configuration for SecurityMiddleware
*/
export interface SecurityMiddlewareConfig<T = unknown> {
authentication?: AuthenticationConfig<T>;
headers?: SecurityHeadersConfig;
audit?: SecurityAuditConfig;
}
/**
* Consolidated SecurityMiddleware that combines authentication, security headers, and audit logging.
*
* This middleware replaces the need for separate:
* - AuthenticationMiddleware
* - SecurityHeadersMiddleware
* - SecurityAuditMiddleware
*
* @example
* Basic security with authentication and headers:
* ```typescript
* const handler = new Handler()
* .use(new SecurityMiddleware({
* authentication: {
* tokenVerifier: {
* verifyToken: async (token) => jwt.verify(token, secret)
* },
* extractToken: (req) => req.headers.authorization?.replace('Bearer ', '')
* },
* headers: {
* contentSecurityPolicy: "default-src 'self'",
* xFrameOptions: 'DENY',
* strictTransportSecurity: 'max-age=31536000; includeSubDomains'
* },
* audit: {
* logFailedAuth: true,
* trackSuspiciousIPs: true
* }
* }))
* .handle(async (context) => {
* // context.user is populated if authentication succeeds
* const user = context.user;
* return { message: `Hello ${user?.name}` };
* });
* ```
*
* @example
* Advanced security with custom auditing:
* ```typescript
* const handler = new Handler()
* .use(new SecurityMiddleware({
* authentication: {
* tokenVerifier: customTokenVerifier,
* skipPaths: ['/health', '/metrics'],
* onAuthFailure: async (error, context) => {
* await logSecurityEvent('auth_failure', {
* ip: context.req.ip,
* error: error.message
* });
* }
* },
* audit: {
* customAuditor: async (event, context) => {
* await sendToSecuritySystem(event);
* },
* alertThresholds: {
* failedAttempts: 5,
* timeWindowMs: 300000 // 5 minutes
* }
* }
* }));
* ```
*/
export declare class SecurityMiddleware<T = unknown> implements BaseMiddleware<T> {
private config;
private failedAttempts;
constructor(config?: SecurityMiddlewareConfig<T>);
before(context: Context<T>): Promise<void>;
after(context: Context<T>): Promise<void>;
onError(error: Error, context: Context<T>): Promise<void>;
private setSecurityHeaders;
private authenticateRequest;
private extractTokenFromHeader;
private trackFailedAttempt;
private auditSecurityEvent;
}
/**
* Factory function for creating SecurityMiddleware with common configurations
*/
export declare const createSecurityMiddleware: {
/**
* Basic security setup with common headers and JWT authentication
*/
basic: <T = unknown>(tokenVerifier: {
verifyToken(token: string): Promise<T>;
}) => SecurityMiddleware<T>;
/**
* Advanced security with audit tracking and suspicious IP monitoring
*/
advanced: <T = unknown>(tokenVerifier: {
verifyToken(token: string): Promise<T>;
}) => SecurityMiddleware<T>;
/**
* Headers only - no authentication
*/
headersOnly: () => SecurityMiddleware;
};
//# sourceMappingURL=SecurityMiddleware.d.ts.map