-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp.ts
More file actions
69 lines (61 loc) · 2.47 KB
/
Copy pathhttp.ts
File metadata and controls
69 lines (61 loc) · 2.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import type { IncomingMessage, ServerResponse } from 'node:http';
import type { TLSSocket } from 'node:tls';
import { handleApiRequest } from '../api-router';
/**
* Adapter to handle Node-compatible requests (Vite dev server, Vercel)
* and route them through the Web-standard handleApiRequest.
*/
export async function handleNodeRequest(
nodeReq: IncomingMessage,
nodeRes: ServerResponse,
): Promise<boolean> {
const headers = new Headers();
for (const [key, value] of Object.entries(nodeReq.headers)) {
if (value) {
if (Array.isArray(value)) {
value.forEach((v) => headers.append(key, v));
} else {
headers.set(key, value);
}
}
}
const protocol = (nodeReq.socket as TLSSocket).encrypted ? 'https' : 'http';
const host = nodeReq.headers.host ?? 'localhost';
const url = `${protocol}://${host}${nodeReq.url}`;
let body: BodyInit | undefined;
const requestWithBody = nodeReq as IncomingMessage & { body?: unknown };
if (requestWithBody.body !== undefined) {
const parsedBody = requestWithBody.body;
body = typeof parsedBody === 'string' ? parsedBody : JSON.stringify(parsedBody);
} else if (nodeReq.method !== 'GET' && nodeReq.method !== 'HEAD') {
const chunks: Buffer[] = [];
for await (const chunk of nodeReq) {
chunks.push(chunk as Buffer);
}
body = Buffer.concat(chunks);
}
const webReq = new Request(url, {
method: nodeReq.method,
headers,
body,
});
const webRes = await handleApiRequest(webReq);
if (!webRes) {
return false;
}
nodeRes.statusCode = webRes.status;
webRes.headers.forEach((value, key) => {
nodeRes.setHeader(key, value);
});
const arrayBuffer = await webRes.arrayBuffer();
nodeRes.end(Buffer.from(arrayBuffer));
return true;
}
export function addSecurityHeaders(response: Response): Response {
response.headers.set('X-Content-Type-Options', 'nosniff');
response.headers.set('X-Frame-Options', 'DENY');
// X-XSS-Protection is deprecated; use CSP instead
response.headers.set('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');
response.headers.set('Content-Security-Policy', "default-src 'self'; base-uri 'self'; script-src 'self' 'sha256-mhDq8RP/TAuNwiFSk7hwZsZ3tIWH410AupSuJ9xEhZg=' 'sha256-47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU='; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data: https:; connect-src 'self' https: wss:;");
return response;
}