-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathhttp-server.ts
More file actions
48 lines (42 loc) · 1.59 KB
/
Copy pathhttp-server.ts
File metadata and controls
48 lines (42 loc) · 1.59 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
import * as HTTP from 'node:http'
import * as Fs from 'node:fs'
import * as Process from 'node:process'
import * as Path from 'node:path'
import { SafeInitCwd } from './safe-init-cwd.js'
function IsLoopBack(IP: string) {
return IP === '127.0.0.1' || IP === '::1' || IP === '::ffff:127.0.0.1'
}
export function RunDebugServer(Port: number, FileName: string[], ShouldPreventHTTPResponse: boolean) {
const HTTPServer = HTTP.createServer((Req, Res) => {
let ProjectRoot = SafeInitCwd({ Cwd: Process.cwd(), InitCwd: Process.env.INIT_CWD })
const RequestPath = Req.url?.substring(1) || ''
const ResolvedPath = Path.resolve(ProjectRoot + '/dist', RequestPath)
const RelativePath = Path.relative(ProjectRoot + '/dist', ResolvedPath)
// Ensure the resolved path stays within the dist root to prevent directory traversal
if (RelativePath.startsWith('..') || Path.isAbsolute(RelativePath)) {
Res.writeHead(403)
Res.end()
return
}
if (!FileName.includes(RequestPath)) {
Res.writeHead(404)
Res.end()
return
} else if (!IsLoopBack(Req.socket.remoteAddress ?? '')) {
Res.writeHead(403)
Res.end()
return
} else if (ShouldPreventHTTPResponse || !Fs.existsSync(ResolvedPath)) {
Res.writeHead(503)
Res.end('File not built yet.')
return
}
const Content = Fs.readFileSync(ResolvedPath, 'utf-8')
Res.writeHead(200, {
'content-type': 'application/javascript; charset=utf-8',
'content-length': new TextEncoder().encode(Content).byteLength.toString()
})
Res.end(Content)
})
HTTPServer.listen(Port)
}