File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed
Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change 1+ import { serve } from 'serverless-http' ;
2+ import { createApp } from './main.py' ; // Assuming main.py is bundled as ESM
3+ import { v4 as uuidv4 } from 'uuid' ;
4+
5+ const app = createApp ( ) ;
6+ const handler = serve ( app ) ;
7+
8+ // Generate CSP nonce
9+ const generateNonce = ( ) => {
10+ return Buffer . from ( uuidv4 ( ) ) . toString ( 'base64' ) . replace ( / \+ / g, '-' ) . replace ( / \/ / g, '_' ) . replace ( / = / g, '' ) ;
11+ } ;
12+
13+ export default async ( req , context ) => {
14+ const nonce = generateNonce ( ) ;
15+
16+ // Inject nonce into HTML responses
17+ if ( req . path === '/' || req . path === '/index.html' ) {
18+ const response = await handler ( req , context ) ;
19+ if ( response . statusCode === 200 && response . headers [ 'content-type' ] . includes ( 'text/html' ) ) {
20+ const body = Buffer . from ( response . body , 'base64' ) . toString ( 'utf-8' ) ;
21+ const modifiedBody = body . replace ( / { { nonce} } / g, nonce ) ;
22+ return {
23+ ...response ,
24+ body : Buffer . from ( modifiedBody ) . toString ( 'base64' ) ,
25+ headers : {
26+ ...response . headers ,
27+ 'Content-Security-Policy' : response . headers [ 'Content-Security-Policy' ] . replace ( '{{nonce}}' , nonce )
28+ }
29+ } ;
30+ }
31+ return response ;
32+ }
33+
34+ return handler ( req , context ) ;
35+ } ;
You can’t perform that action at this time.
0 commit comments