1
- import { Request , Router } from "express"
1
+ import { Request , Response } from "express"
2
+ import * as path from "path"
2
3
import qs from "qs"
3
4
import { HttpCode , HttpError } from "../../common/http"
4
5
import { normalize } from "../../common/util"
5
6
import { authenticated , ensureAuthenticated , redirect } from "../http"
6
- import { proxy } from "../proxy"
7
- import { Router as WsRouter } from "../wsRouter"
7
+ import { proxy as _proxy } from "../proxy"
8
+ import { WebsocketRequest } from "../wsRouter"
8
9
9
- export const router = Router ( )
10
-
11
- const getProxyTarget = ( req : Request , passthroughPath : boolean ) : string => {
10
+ const getProxyTarget = ( req : Request , passthroughPath ?: boolean ) : string => {
12
11
if ( passthroughPath ) {
13
12
return `http://0.0.0.0:${ req . params . port } /${ req . originalUrl } `
14
13
}
15
14
const query = qs . stringify ( req . query )
16
15
return `http://0.0.0.0:${ req . params . port } /${ req . params [ 0 ] || "" } ${ query ? `?${ query } ` : "" } `
17
16
}
18
17
19
- router . all ( "/(:port)(/*)?" , ( req , res ) => {
18
+ export function proxy (
19
+ req : Request ,
20
+ res : Response ,
21
+ opts ?: {
22
+ passthroughPath ?: boolean
23
+ } ,
24
+ ) : void {
20
25
if ( ! authenticated ( req ) ) {
21
26
// If visiting the root (/:port only) redirect to the login page.
22
27
if ( ! req . params [ 0 ] || req . params [ 0 ] === "/" ) {
@@ -28,22 +33,27 @@ router.all("/(:port)(/*)?", (req, res) => {
28
33
throw new HttpError ( "Unauthorized" , HttpCode . Unauthorized )
29
34
}
30
35
31
- if ( ! req . args [ "proxy-path-passthrough" ] ) {
36
+ if ( ! opts ?. passthroughPath ) {
32
37
// Absolute redirects need to be based on the subpath when rewriting.
33
- ; ( req as any ) . base = `${ req . baseUrl } /${ req . params . port } `
38
+ // See proxy.ts.
39
+ ; ( req as any ) . base = req . path . split ( path . sep ) . slice ( 0 , 3 ) . join ( path . sep )
34
40
}
35
41
36
- proxy . web ( req , res , {
42
+ _proxy . web ( req , res , {
37
43
ignorePath : true ,
38
- target : getProxyTarget ( req , req . args [ "proxy-path-passthrough" ] || false ) ,
44
+ target : getProxyTarget ( req , opts ?. passthroughPath ) ,
39
45
} )
40
- } )
41
-
42
- export const wsRouter = WsRouter ( )
46
+ }
43
47
44
- wsRouter . ws ( "/(:port)(/*)?" , ensureAuthenticated , ( req ) => {
45
- proxy . ws ( req , req . ws , req . head , {
48
+ export function wsProxy (
49
+ req : WebsocketRequest ,
50
+ opts ?: {
51
+ passthroughPath ?: boolean
52
+ } ,
53
+ ) : void {
54
+ ensureAuthenticated ( req )
55
+ _proxy . ws ( req , req . ws , req . head , {
46
56
ignorePath : true ,
47
- target : getProxyTarget ( req , req . args [ "proxy-path-passthrough" ] || false ) ,
57
+ target : getProxyTarget ( req , opts ?. passthroughPath ) ,
48
58
} )
49
- } )
59
+ }
0 commit comments