File tree Expand file tree Collapse file tree 2 files changed +21
-11
lines changed
Expand file tree Collapse file tree 2 files changed +21
-11
lines changed Original file line number Diff line number Diff line change @@ -16,6 +16,23 @@ export interface APIHandler {
1616 */
1717export function withSecurity ( handler : APIHandler ) {
1818 return async ( request : NextRequest ) : Promise < Response > => {
19+ const requestId = crypto . randomUUID ( ) ;
20+
21+ try {
22+ // Add request ID to headers for tracking
23+ const response = await handler ( request ) ;
24+
25+ // Add security headers
26+ response . headers . set ( 'X-Request-ID' , requestId ) ;
27+ response . headers . set ( 'X-Content-Type-Options' , 'nosniff' ) ;
28+ response . headers . set ( 'X-Frame-Options' , 'DENY' ) ;
29+ response . headers . set ( 'X-XSS-Protection' , '1; mode=block' ) ;
30+
31+ // Add CSP header
32+ const cspConfig = getCSPConfig ( request ) ;
33+ response . headers . set ( 'Content-Security-Policy' , cspConfig . policy ) ;
34+
35+ return response ;
1936 } catch ( error ) {
2037 const res = ErrorSanitizer . createErrorResponse (
2138 error ,
@@ -32,14 +49,6 @@ export function withSecurity(handler: APIHandler) {
3249 res . headers . set ( 'Content-Security-Policy' , cspConfig . policy ) ;
3350 return res ;
3451 }
35- } catch ( error ) {
36- return ErrorSanitizer . createErrorResponse (
37- error ,
38- 500 ,
39- 'api-wrapper-catch' ,
40- requestId
41- ) ;
42- }
4352 } ;
4453}
4554
Original file line number Diff line number Diff line change @@ -16,16 +16,17 @@ export interface CSPConfig {
1616 */
1717export function generateNonce ( ) : string {
1818 // Prefer Web Crypto (Edge/Browser)
19- const webCrypto = ( globalThis as any ) . crypto ;
19+ const webCrypto = ( globalThis as { crypto ?: { getRandomValues ?: ( arr : Uint8Array ) => void } } ) . crypto ;
2020 if ( webCrypto ?. getRandomValues ) {
2121 const arr = new Uint8Array ( 16 ) ;
2222 webCrypto . getRandomValues ( arr ) ;
2323 // Base64 encode without Buffer dependency
2424 let binary = '' ;
2525 for ( let i = 0 ; i < arr . length ; i ++ ) binary += String . fromCharCode ( arr [ i ] ) ;
2626 // btoa is available in Edge/Browser
27- // @ts -ignore
28- return typeof btoa === 'function' ? btoa ( binary ) : Buffer . from ( arr ) . toString ( 'base64' ) ;
27+ return typeof ( globalThis as { btoa ?: ( str : string ) => string } ) . btoa === 'function'
28+ ? ( globalThis as { btoa : ( str : string ) => string } ) . btoa ( binary )
29+ : Buffer . from ( arr ) . toString ( 'base64' ) ;
2930 }
3031 // Node.js fallback
3132 return crypto . randomBytes ( 16 ) . toString ( 'base64' ) ;
You canβt perform that action at this time.
0 commit comments