Skip to content

Commit a50918f

Browse files
authored
Create api.mjs
1 parent 834fdbe commit a50918f

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

main/netlify/functions/api.mjs

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
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+
};

0 commit comments

Comments
 (0)