@cosmstack/blackshield
Version:
A developer-first security toolkit for React/Next.js applications
224 lines (213 loc) • 7.23 kB
text/typescript
import React, { JSX } from 'react';
import { z, ZodSchema } from 'zod';
interface BlackshieldConfig {
/** Enable development mode warnings */
dev?: boolean;
/** Custom environment variable validation */
envValidation?: {
/** Allowed NEXT_PUBLIC_ variables */
allowedPublicVars?: string[];
/** Custom validation schema */
schema?: z.ZodSchema;
};
/** XSS protection settings */
xssProtection?: {
/** Enable automatic sanitization */
autoSanitize?: boolean;
/** Custom sanitization rules */
customRules?: Record<string, (input: string) => string>;
};
/** Server/client boundary protection */
boundaryProtection?: {
/** Enable server-side validation */
validateServerProps?: boolean;
/** Custom prop validators */
customValidators?: Record<string, z.ZodSchema>;
};
/** CSRF protection settings */
csrfProtection?: {
/** Enable CSRF protection */
enabled?: boolean;
/** Custom token header name */
tokenHeader?: string;
/** Custom token cookie name */
tokenCookie?: string;
/** Token expiry time in seconds */
tokenExpiry?: number;
};
}
interface SecureUser {
id: string;
email?: string;
roles?: string[];
permissions?: string[];
metadata?: Record<string, unknown>;
}
interface AuthContext {
user: SecureUser | null;
isLoading: boolean;
isAuthenticated: boolean;
error?: Error;
}
interface RouteGuardConfig {
/** Required roles for access */
requiredRoles?: string[];
/** Required permissions for access */
requiredPermissions?: string[];
/** Redirect path for unauthorized users */
redirectTo?: string;
/** Custom authorization logic */
customAuth?: (user: SecureUser | null) => boolean;
}
interface EnvValidationResult {
isValid: boolean;
errors: string[];
warnings: string[];
exposedVars: string[];
}
interface EnvAuditResult {
isValid: boolean;
sensitiveVars: Array<{
name: string;
file: string;
line: number;
severity: 'error' | 'warning';
suggestion: string;
}>;
summary: {
totalVars: number;
sensitiveCount: number;
filesScanned: string[];
};
}
interface CsrfToken {
token: string;
expiresAt: number;
}
interface CsrfConfig {
tokenHeader?: string;
tokenCookie?: string;
tokenExpiry?: number;
}
interface XSSProtectionResult {
sanitized: string;
wasModified: boolean;
removedTags: string[];
warnings: string[];
}
interface SecurityIssue {
type: 'env-exposure' | 'xss-vulnerability' | 'boundary-violation' | 'csrf-vulnerability' | 'env-leak';
severity: 'error' | 'warning' | 'info';
message: string;
file: string;
line: number;
column: number;
suggestion?: string;
}
interface AnalysisResult {
projectPath: string;
timestamp: string;
issues: SecurityIssue[];
summary: {
total: number;
errors: number;
warnings: number;
info: number;
};
config: BlackshieldConfig;
}
interface BlackshieldContextValue {
config: Required<BlackshieldConfig>;
auth: AuthContext;
updateUser: (user: SecureUser | null) => void;
setLoading: (loading: boolean) => void;
setError: (error: Error | undefined) => void;
}
interface SecureProviderProps {
children: React.ReactNode;
config?: Partial<BlackshieldConfig>;
initialUser?: SecureUser | null;
onAuthChange?: (user: SecureUser | null) => void;
}
declare function SecureProvider({ children, config, initialUser, onAuthChange, }: SecureProviderProps): React.JSX.Element;
declare function useBlackshield(): BlackshieldContextValue;
declare function useSecureUser(): {
user: SecureUser | null;
isLoading: boolean;
isAuthenticated: boolean;
error: Error | undefined;
login: (user: SecureUser) => Promise<void>;
logout: () => Promise<void>;
hasRole: (role: string) => boolean;
hasPermission: (permission: string) => boolean;
hasAnyRole: (roles: string[]) => boolean;
hasAllRoles: (roles: string[]) => boolean;
};
declare function useGuardedRoute(config?: RouteGuardConfig): {
isAuthorized: boolean;
isLoading: boolean;
user: SecureUser | null;
};
interface CsrfProtectionOptions extends Partial<CsrfConfig> {
/** Enable automatic token injection */
autoInject?: boolean;
/** Only inject for requests with credentials */
credentialsOnly?: boolean;
}
interface CsrfProtectionResult {
/** Current CSRF token */
token: string | null;
/** Whether token is loading */
isLoading: boolean;
/** Get fresh token */
refreshToken: () => Promise<void>;
/** Get token for manual use */
getCsrfToken: () => string | null;
/** Enhanced fetch with CSRF protection */
protectedFetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
}
/**
* Hook for client-side CSRF protection
*/
declare function useCsrfProtection(options?: CsrfProtectionOptions): CsrfProtectionResult;
/**
* Utility function to get CSRF token from cookie
*/
declare function getCsrfToken(tokenCookie?: string): string | null;
declare function sanitizeHTML(input: string, options?: {
allowedTags?: string[];
allowedAttributes?: string[];
customRules?: Record<string, (input: string) => string>;
}): XSSProtectionResult;
declare function createSafeHTML(html: string): {
__html: string;
};
declare function SafeHTML({ html, tag, className, allowedTags, allowedAttributes, ...props }: {
html: string;
tag?: keyof JSX.IntrinsicElements;
className?: string;
allowedTags?: string[];
allowedAttributes?: string[];
} & Record<string, unknown>): JSX.Element;
declare function useSanitizedHTML(html: string, options?: {
allowedTags?: string[];
allowedAttributes?: string[];
customRules?: Record<string, (input: string) => string>;
}): XSSProtectionResult;
declare function validateEnvironmentVariables(config?: {
allowedPublicVars?: string[];
schema?: ZodSchema;
}): EnvValidationResult;
declare function createEnvValidator(allowedVars: string[]): () => EnvValidationResult;
interface EnvAuditOptions {
/** Project root path */
projectPath?: string;
/** Additional sensitive patterns to check */
customPatterns?: RegExp[];
/** Variables that are explicitly allowed to be public */
allowedPublicVars?: string[];
}
declare function envAudit(options?: EnvAuditOptions): Promise<EnvAuditResult>;
declare function scanEnvFiles(projectPath?: string): Promise<void>;
declare const DEFAULT_CONFIG: Required<BlackshieldConfig>;
export { type AnalysisResult, type AuthContext, type BlackshieldConfig, type CsrfConfig, type CsrfToken, DEFAULT_CONFIG, type EnvAuditResult, type EnvValidationResult, type RouteGuardConfig, SafeHTML, SecureProvider, type SecureUser, type SecurityIssue, type XSSProtectionResult, createEnvValidator, createSafeHTML, envAudit, getCsrfToken, sanitizeHTML, scanEnvFiles, useBlackshield, useCsrfProtection, useGuardedRoute, useSanitizedHTML, useSecureUser, validateEnvironmentVariables };