1
1
import http from "http" ;
2
2
import apiSpeakers from "./api/speakers.js" ;
3
3
import apiTTS from "./api/tts.mp3.js" ;
4
- import { createReadStream , statSync } from "fs" ;
4
+ import { createReadStream , readFileSync , statSync } from "fs" ;
5
+ import { randomUUID } from "crypto" ;
5
6
6
- const exists = ( path ) => {
7
- try {
8
- return statSync ( path ) . isFile ( ) ;
9
- } catch ( e ) {
10
- return false ;
11
- }
12
- } ;
7
+ const kPort = process . env . PORT || 3000 ;
8
+ const kVersion = JSON . parse ( readFileSync ( "package.json" ) ) . version ;
9
+ const kSecretPath = process . env . SECRET_PATH || randomUUID ( ) . substring ( 0 , 8 ) ;
13
10
14
11
const server = http . createServer ( ( req , res ) => {
15
- req . url = req . url . replace ( "+text=" , "&text=" ) ; // 修正请求 URL
12
+ // 返回提示字符串
13
+ const response = ( msg ) => {
14
+ res . writeHead ( 404 , { "Content-Type" : "text/plain; charset=utf-8" } ) ;
15
+ res . end ( Buffer . from ( msg , "utf8" ) ) ;
16
+ } ;
17
+
18
+ // 修正请求 URL 中的转义字符
19
+ req . url = req . url . replace ( "+text=" , "&text=" ) ;
20
+
21
+ // 校验 secret path
22
+ const secretPath = req . url . split ( "/" ) [ 1 ] ;
23
+ if ( secretPath !== kSecretPath ) {
24
+ console . log ( "❌ 非法请求" + decodeURI ( req . url ) ) ;
25
+ return response ( "❌ 非法请求" ) ;
26
+ }
27
+
28
+ // 解析原始请求 URL
29
+ req . url = req . url . split ( kSecretPath ) [ 1 ] ;
16
30
const { pathname } = new URL ( "http://127.0.0.1" + req . url ) ;
17
31
const filePath = `public${ pathname } ` ;
18
32
@@ -30,14 +44,24 @@ const server = http.createServer((req, res) => {
30
44
const readStream = createReadStream ( filePath ) ;
31
45
readStream . pipe ( res ) ;
32
46
} else {
33
- res . writeHead ( 404 , { "Content-Type" : "text/plain" } ) ;
34
- res . end ( "404" ) ;
47
+ response ( "✅ 服务已启动" ) ;
35
48
}
36
49
} ) ;
37
50
38
- const PORT = process . env . PORT || 3000 ;
39
- server . listen ( PORT , ( ) => {
40
- console . log ( `MiGPT-TTS is running on port ${ PORT } \n` ) ;
41
- console . log ( "version: v2.0.0 by: del.wang\n" ) ;
42
- console . log ( "✅ 服务已启动...\n" ) ;
51
+ server . listen ( kPort , ( ) => {
52
+ console . log (
53
+ [
54
+ `MiGPT-TTS: v${ kVersion } by: del.wang` ,
55
+ `接口地址: http://localhost:${ kPort } /${ kSecretPath } /api` ,
56
+ "✅ 服务已启动...\n" ,
57
+ ] . join ( "\n\n" )
58
+ ) ;
43
59
} ) ;
60
+
61
+ function exists ( path ) {
62
+ try {
63
+ return statSync ( path ) . isFile ( ) ;
64
+ } catch ( e ) {
65
+ return false ;
66
+ }
67
+ }
0 commit comments